content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ToolsUtilities;
namespace Gum.DataTypes
{
public enum ElementType
{
Screen,
Component,
Standard
}
public enum LinkType
{
ReferenceOriginal,
CopyLocally
}
public class ElementReference
{
public const string ScreenSubfolder = "Screens";
public const string ComponentSubfolder = "Components";
public const string StandardSubfolder = "Standards";
public ElementType ElementType
{
get;
set;
}
public LinkType LinkType { get; set; }
public string Extension
{
get
{
switch (ElementType)
{
case DataTypes.ElementType.Standard:
return GumProjectSave.StandardExtension;
case DataTypes.ElementType.Component:
return GumProjectSave.ComponentExtension;
case DataTypes.ElementType.Screen:
return GumProjectSave.ScreenExtension;
}
throw new InvalidOperationException();
}
}
public string Subfolder
{
get
{
switch (ElementType)
{
case DataTypes.ElementType.Standard:
return StandardSubfolder;
case DataTypes.ElementType.Component:
return ComponentSubfolder;
case DataTypes.ElementType.Screen:
return ScreenSubfolder;
}
throw new InvalidOperationException();
}
}
public string Name;
/// <summary>
/// The location of the file relative to the project if it differs from the Name. By default
/// this will be empty, so the Name will be used to load/save the element. However, if this is not null,
/// then this value is used instead to load the referenced element.
/// </summary>
public string Link { get; set; }
//public ElementSave ToElementSave(string projectroot, string extension)
//{
// string fullName = projectroot + Subfolder + "/" + Name + "." + extension;
// ElementSave elementSave = FileManager.XmlDeserialize<ElementSave>(fullName);
// return elementSave;
//}
public T ToElementSave<T>(string projectroot, string extension, GumLoadResult result, LinkLoadingPreference linkLoadingPreference = LinkLoadingPreference.PreferLinked) where T : ElementSave, new()
{
FilePath linkedName = null;
FilePath containedReferenceName = null;
if (!string.IsNullOrWhiteSpace(this.Link))
{
linkedName = projectroot + this.Link;
}
containedReferenceName = projectroot + Subfolder + "/" + Name + "." + extension;
if (linkedName != null && ToolsUtilities.FileManager.IsRelative(linkedName.Original))
{
linkedName = ToolsUtilities.FileManager.RelativeDirectory + linkedName.Original;
}
if (ToolsUtilities.FileManager.IsRelative(containedReferenceName.Original))
{
containedReferenceName = ToolsUtilities.FileManager.RelativeDirectory + containedReferenceName.Original;
}
if (linkedName?.Exists() == true)
{
T elementSave = FileManager.XmlDeserialize<T>(linkedName.FullPath);
return elementSave;
}
else if (containedReferenceName.Exists() && (linkedName == null || linkLoadingPreference == LinkLoadingPreference.PreferLinked))
{
T elementSave = FileManager.XmlDeserialize<T>(containedReferenceName.FullPath);
if (Name != elementSave.Name)
{
// The file name doesn't match the name of the element. This can cause errors
// at runtime so let's tell the user:
result.ErrorMessage += "\nThe project references an element named " + Name + ", but the XML for this element has its name set to " + elementSave.Name + "\n";
}
return elementSave;
}
else
{
// I don't think we want to consider this an error anymore
// because Gum can handle it - it doesn't allow saving that
// individual element and it shows a red ! next to the element.
// We should just tolerate this and let the user deal with it.
// If we do treat this as an error, then Gum goes into a state
// where it can't save anything.
//errors += "\nCould not find the file name " + fullName;
// Update Feb 20, 2015
// But we can record it:
result.MissingFiles.Add(containedReferenceName.FullPath);
T elementSave = new T();
elementSave.Name = Name;
elementSave.IsSourceFileMissing = true;
return elementSave;
}
}
public override string ToString()
{
return Name;
}
}
}
| 33.732919 | 204 | 0.554778 | [
"MIT"
] | J-Swift/Gum | SkiaGum/DataTypes/ElementReference.cs | 5,433 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using ScriptFinder.Utilities;
using System;
namespace ScriptFinder
{
public sealed class Editor : EditorWindow
{
private sealed class Data
{
public struct AssetNames
{
public const string SkinScriptFinder = "ScriptFinderSkin";
public const string StyleHeader = "Header";
public const string StyleFindComponentsLabel = "FindComponentsLabel";
public const string StyleObjectFieldLabel = "ObjectFieldLabel";
public const string StyleRecurseLabel = "RecurseLabel";
public const string StyleResultLabel = "ResultLabel";
}
public struct Colours
{
public static readonly Color BackgroundHeader = new Color32(60, 60, 60, 255);
public static readonly Color BackgroundBodyOuter = new Color32(90, 90, 90, 255);
public static readonly Color BackgroundBodyBorder = new Color32(60, 60, 60, 255);
public static readonly Color BackgroundBodyInner = new Color32(70, 70, 70, 255);
public static readonly Color BackgroundResultsBorder = new Color32(60, 60, 60, 255);
public static readonly Color BackgroundResultsInner = new Color32(90, 90, 90, 255);
public static readonly Color ButtonMatchNormalBackground = new Color32(100, 100, 100, 255);
public static readonly Color ButtonMatchNormalBorder = new Color32(80, 80, 80, 255);
public static readonly Color ButtonMatchNormalText = new Color32(255, 255, 255, 255);
public static readonly Color ButtonMatchHoverBackground = new Color32(130, 130, 200, 255);
public static readonly Color ButtonMatchHoverBorder = new Color32(90, 90, 160, 255);
public static readonly Color ButtonMatchHoverText = new Color32(255, 255, 255, 255);
public static readonly Color ButtonMatchSelectedBackground = new Color32(110, 110, 180, 255);
public static readonly Color ButtonMatchSelectedBorder = new Color32(70, 70, 140, 255);
public static readonly Color ButtonMatchSelectedText = new Color32(255, 255, 255, 255);
}
public struct Labels
{
public const string ButtonFindMatches = "Find Components";
public const string ButtonSelect = "Select";
public const string FileTypePrefab = ".prefab";
public const string HeaderFindComponentsSuccess = "Matches:";
public const string HeaderFindComponentsFail = "No matches found.";
public const string HeaderScriptFinder = "ScriptFinder";
public const string HeaderShouldRecurse = "Recurse Dependencies (Warning: Very Slow)";
public const string HeaderTargetObjectField = "Select Target Script";
public const string WindowPath = "Tools/ScriptFinder";
public const string WindowTitle = "ScriptFinder - © 2018 Joeb Rogers";
}
public struct LayoutOptions
{
public static readonly GUILayoutOption[] ButtonMatch = new GUILayoutOption[]
{
GUILayout.Width(Rects.ButtonMatch.width),
GUILayout.Height(Rects.ButtonMatch.height)
};
}
public struct Padding
{
public static readonly RectOffset ButtonMatch = new RectOffset
{
left = 5,
top = 6
};
}
public struct Rects
{
public static readonly Rect AreaResults = new Rect(22.0f, 227.0f, 756.0f, 151.0f);
public static readonly Rect BackgroundHeader = new Rect(0.0f, 0.0f, 800.0f, 30.0f);
public static readonly Rect BackgroundBodyOuter = new Rect(0.0f, 30.0f, 800.0f, 370.0f);
public static readonly Rect BackgroundBodyBorder = new Rect(10.0f, 40.0f, 780.0f, 350.0f);
public static readonly Rect BackgroundBodyInner = new Rect(12.0f, 42.0f, 776.0f, 346.0f);
public static readonly Rect BackgroundResultsBorder = new Rect(20.0f, 225.0f, 760.0f, 155.0f);
public static readonly Rect BackgroundResultsInner = new Rect(22.0f, 227.0f, 756.0f, 151.0f);
public static readonly Rect ButtonFindMatches = new Rect(20.0f, 160.0f, 760.0f, 20.0f);
public static readonly Rect ButtonMatch = new Rect(0.0f, 0.0f, 756.0f, 30.0f);
public static readonly Rect FieldTargetObject = new Rect(20.0f, 80.0f, 762.0f, 17.0f);
public static readonly Rect FieldRecurseToggle = new Rect(18.0f, 135.0f, 20.0f, 20.0f);
}
public struct StyleStates
{
private const int ButtonMatchBorderThickness = 4;
public static readonly GUIStyleState ButtonMatchNormal = new GUIStyleState
{
background = Utility.GenerateColouredBackgroundWithBottomBorder
(
(int)Rects.ButtonMatch.width,
(int)Rects.ButtonMatch.height,
Colours.ButtonMatchNormalBackground,
Colours.ButtonMatchNormalBorder,
ButtonMatchBorderThickness
),
textColor = Colours.ButtonMatchNormalText
};
public static readonly GUIStyleState ButtonMatchHover = new GUIStyleState
{
background = Utility.GenerateColouredBackgroundWithBottomBorder
(
(int)Rects.ButtonMatch.width,
(int)Rects.ButtonMatch.height,
Colours.ButtonMatchHoverBackground,
Colours.ButtonMatchHoverBorder,
ButtonMatchBorderThickness
),
textColor = Colours.ButtonMatchHoverText
};
public static readonly GUIStyleState ButtonMatchSelected = new GUIStyleState
{
background = Utility.GenerateColouredBackgroundWithBottomBorder
(
(int)Rects.ButtonMatch.width,
(int)Rects.ButtonMatch.height,
Colours.ButtonMatchSelectedBackground,
Colours.ButtonMatchSelectedBorder,
ButtonMatchBorderThickness
),
textColor = Colours.ButtonMatchSelectedText
};
}
public struct Styles
{
public static readonly GUIStyle ButtonMatch = new GUIStyle
{
normal = StyleStates.ButtonMatchNormal,
onNormal = StyleStates.ButtonMatchNormal,
hover = StyleStates.ButtonMatchHover,
onHover = StyleStates.ButtonMatchHover,
fontStyle = FontStyle.Bold,
fontSize = 12,
padding = Padding.ButtonMatch
};
public static readonly GUIStyle ButtonMatchSelected = new GUIStyle
{
normal = StyleStates.ButtonMatchSelected,
onNormal = StyleStates.ButtonMatchSelected,
hover = StyleStates.ButtonMatchSelected,
onHover = StyleStates.ButtonMatchSelected,
fontStyle = FontStyle.Bold,
fontSize = 12,
padding = Padding.ButtonMatch
};
}
public static readonly Vector2 WindowSize = new Vector2
{
x = 800.0f,
y = 400.0f
};
}
#region Fields
#region Styles
private GUISkin skin;
private GUIStyle styleHeader;
private GUIStyle styleObjectFieldLabel;
private GUIStyle styleRecurseLabel;
private GUIStyle styleFindComponentsLabel;
private GUIStyle styleResultLabel;
#endregion
private MonoScript targetComponent;
private bool shouldRecurse = false;
private Vector2 scrollPosition = Vector2.zero;
private List<string> results;
private string selectedResult = "";
#endregion
#region Unity Methods
[MenuItem(Data.Labels.WindowPath)]
private static void Init()
{
// Get existing open window or if none, make a new one:
var window = (Editor)GetWindow(typeof(Editor), true, Data.Labels.WindowTitle);
window.minSize = Data.WindowSize;
window.maxSize = Data.WindowSize;
window.Show();
}
void OnEnable()
{
wantsMouseMove = true;
// Retrieve styles
skin = (GUISkin)Resources.Load(Data.AssetNames.SkinScriptFinder);
styleHeader = skin.GetStyle(Data.AssetNames.StyleHeader);
styleObjectFieldLabel = skin.GetStyle(Data.AssetNames.StyleObjectFieldLabel);
styleRecurseLabel = skin.GetStyle(Data.AssetNames.StyleRecurseLabel);
styleFindComponentsLabel = skin.GetStyle(Data.AssetNames.StyleFindComponentsLabel);
styleResultLabel = skin.GetStyle(Data.AssetNames.StyleResultLabel);
}
void OnGUI()
{
HandleEvents();
DrawGUIBackground();
DrawGUIControls();
DrawGUIResults();
}
#endregion
#region Input Events
private void HandleEvents()
{
var e = Event.current;
switch (e.type)
{
case EventType.MouseMove:
OnMouseMove();
break;
}
}
#region Mouse Events
private void OnMouseMove()
{
Repaint();
}
#endregion
#endregion
#region Draw GUI
private static void DrawGUIBackground()
{
EditorGUI.DrawRect(Data.Rects.BackgroundHeader, Data.Colours.BackgroundHeader);
EditorGUI.DrawRect(Data.Rects.BackgroundBodyOuter, Data.Colours.BackgroundBodyOuter);
EditorGUI.DrawRect(Data.Rects.BackgroundBodyBorder, Data.Colours.BackgroundBodyBorder);
EditorGUI.DrawRect(Data.Rects.BackgroundBodyInner, Data.Colours.BackgroundBodyInner);
EditorGUI.DrawRect(Data.Rects.BackgroundResultsBorder, Data.Colours.BackgroundResultsBorder);
EditorGUI.DrawRect(Data.Rects.BackgroundResultsInner, Data.Colours.BackgroundResultsInner);
}
private void DrawGUIControls()
{
EditorGUILayout.LabelField(Data.Labels.HeaderScriptFinder, styleHeader);
EditorGUILayout.LabelField(Data.Labels.HeaderTargetObjectField, styleObjectFieldLabel);
targetComponent = (MonoScript)EditorGUI.ObjectField(Data.Rects.FieldTargetObject, targetComponent, typeof(MonoScript), false);
EditorGUILayout.LabelField(Data.Labels.HeaderShouldRecurse, styleRecurseLabel);
shouldRecurse = EditorGUI.Toggle(Data.Rects.FieldRecurseToggle, shouldRecurse);
if (GUI.Button(Data.Rects.ButtonFindMatches, ""))
{
ActionSearchForComponent();
}
EditorGUILayout.LabelField(Data.Labels.ButtonFindMatches, styleFindComponentsLabel);
}
private void DrawGUIResults()
{
if (results != null)
{
if (results.Count == 0)
{
EditorGUILayout.LabelField(Data.Labels.HeaderFindComponentsFail, styleResultLabel);
}
else
{
EditorGUILayout.LabelField(Data.Labels.HeaderFindComponentsSuccess, styleResultLabel);
GUILayout.BeginArea(Data.Rects.AreaResults);
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
foreach (string s in results)
{
GUIStyle activeStyle = s == selectedResult ? Data.Styles.ButtonMatchSelected : Data.Styles.ButtonMatch;
if (GUILayout.Button(s, activeStyle, Data.LayoutOptions.ButtonMatch))
{
Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(s);
selectedResult = s;
}
}
EditorGUILayout.EndScrollView();
GUILayout.EndArea();
}
}
}
#endregion
#region Actions
private void ActionSearchForComponent()
{
string targetPath = AssetDatabase.GetAssetPath(targetComponent);
string[] allPrefabs = GetAllPrefabs();
results = new List<string>();
foreach (string prefab in allPrefabs)
{
string[] single = new string[] { prefab };
string[] dependencies = AssetDatabase.GetDependencies(single, shouldRecurse);
foreach (string dependentAsset in dependencies)
{
if (dependentAsset == targetPath)
{
results.Add(prefab);
}
}
}
}
#endregion
#region Utilities
public static string[] GetAllPrefabs()
{
string[] temp = AssetDatabase.GetAllAssetPaths();
List<string> result = new List<string>();
foreach (string s in temp)
{
if (s.Contains(Data.Labels.FileTypePrefab))
{
result.Add(s);
}
}
return result.ToArray();
}
#endregion
}
} | 43.726727 | 138 | 0.554976 | [
"MIT"
] | JoebRogers/ScriptFinder | ScriptFinder/Assets/ScriptFinder/Editor/Editor.cs | 14,564 | C# |
using Xunit;
using com.chronoxor.enums;
using com.chronoxor.enums.FBE;
namespace Tests
{
public class TestEnums
{
[Fact(DisplayName = "Serialization: enums")]
public void SerializationEnums()
{
var enums1 = Enums.Default;
// Serialize enums to the FBE stream
var writer = new EnumsModel();
Assert.True(writer.model.FBEOffset == 4);
long serialized = writer.Serialize(enums1);
Assert.True(serialized == writer.Buffer.Size);
Assert.True(writer.Verify());
writer.Next(serialized);
Assert.True(writer.model.FBEOffset == (4 + writer.Buffer.Size));
// Check the serialized FBE size
Assert.True(writer.Buffer.Size == 232);
// Deserialize enums from the FBE stream
var reader = new EnumsModel();
Assert.True(reader.model.FBEOffset == 4);
reader.Attach(writer.Buffer);
Assert.True(reader.Verify());
long deserialized = reader.Deserialize(out var enums2);
Assert.True(deserialized == reader.Buffer.Size);
reader.Next(deserialized);
Assert.True(reader.model.FBEOffset == (4 + reader.Buffer.Size));
Assert.True(enums2.byte0 == EnumByte.ENUM_VALUE_0);
Assert.True(enums2.byte1 == EnumByte.ENUM_VALUE_1);
Assert.True(enums2.byte2 == EnumByte.ENUM_VALUE_2);
Assert.True(enums2.byte3 == EnumByte.ENUM_VALUE_3);
Assert.True(enums2.byte4 == EnumByte.ENUM_VALUE_4);
Assert.True(enums2.byte5 == enums1.byte3);
Assert.True(enums2.char0 == EnumChar.ENUM_VALUE_0);
Assert.True(enums2.char1 == EnumChar.ENUM_VALUE_1);
Assert.True(enums2.char2 == EnumChar.ENUM_VALUE_2);
Assert.True(enums2.char3 == EnumChar.ENUM_VALUE_3);
Assert.True(enums2.char4 == EnumChar.ENUM_VALUE_4);
Assert.True(enums2.char5 == enums1.char3);
Assert.True(enums2.wchar0 == EnumWChar.ENUM_VALUE_0);
Assert.True(enums2.wchar1 == EnumWChar.ENUM_VALUE_1);
Assert.True(enums2.wchar2 == EnumWChar.ENUM_VALUE_2);
Assert.True(enums2.wchar3 == EnumWChar.ENUM_VALUE_3);
Assert.True(enums2.wchar4 == EnumWChar.ENUM_VALUE_4);
Assert.True(enums2.wchar5 == enums1.wchar3);
Assert.True(enums2.int8b0 == EnumInt8.ENUM_VALUE_0);
Assert.True(enums2.int8b1 == EnumInt8.ENUM_VALUE_1);
Assert.True(enums2.int8b2 == EnumInt8.ENUM_VALUE_2);
Assert.True(enums2.int8b3 == EnumInt8.ENUM_VALUE_3);
Assert.True(enums2.int8b4 == EnumInt8.ENUM_VALUE_4);
Assert.True(enums2.int8b5 == enums1.int8b3);
Assert.True(enums2.uint8b0 == EnumUInt8.ENUM_VALUE_0);
Assert.True(enums2.uint8b1 == EnumUInt8.ENUM_VALUE_1);
Assert.True(enums2.uint8b2 == EnumUInt8.ENUM_VALUE_2);
Assert.True(enums2.uint8b3 == EnumUInt8.ENUM_VALUE_3);
Assert.True(enums2.uint8b4 == EnumUInt8.ENUM_VALUE_4);
Assert.True(enums2.uint8b5 == enums1.uint8b3);
Assert.True(enums2.int16b0 == EnumInt16.ENUM_VALUE_0);
Assert.True(enums2.int16b1 == EnumInt16.ENUM_VALUE_1);
Assert.True(enums2.int16b2 == EnumInt16.ENUM_VALUE_2);
Assert.True(enums2.int16b3 == EnumInt16.ENUM_VALUE_3);
Assert.True(enums2.int16b4 == EnumInt16.ENUM_VALUE_4);
Assert.True(enums2.int16b5 == enums1.int16b3);
Assert.True(enums2.uint16b0 == EnumUInt16.ENUM_VALUE_0);
Assert.True(enums2.uint16b1 == EnumUInt16.ENUM_VALUE_1);
Assert.True(enums2.uint16b2 == EnumUInt16.ENUM_VALUE_2);
Assert.True(enums2.uint16b3 == EnumUInt16.ENUM_VALUE_3);
Assert.True(enums2.uint16b4 == EnumUInt16.ENUM_VALUE_4);
Assert.True(enums2.uint16b5 == enums1.uint16b3);
Assert.True(enums2.int32b0 == EnumInt32.ENUM_VALUE_0);
Assert.True(enums2.int32b1 == EnumInt32.ENUM_VALUE_1);
Assert.True(enums2.int32b2 == EnumInt32.ENUM_VALUE_2);
Assert.True(enums2.int32b3 == EnumInt32.ENUM_VALUE_3);
Assert.True(enums2.int32b4 == EnumInt32.ENUM_VALUE_4);
Assert.True(enums2.int32b5 == enums1.int32b3);
Assert.True(enums2.uint32b0 == EnumUInt32.ENUM_VALUE_0);
Assert.True(enums2.uint32b1 == EnumUInt32.ENUM_VALUE_1);
Assert.True(enums2.uint32b2 == EnumUInt32.ENUM_VALUE_2);
Assert.True(enums2.uint32b3 == EnumUInt32.ENUM_VALUE_3);
Assert.True(enums2.uint32b4 == EnumUInt32.ENUM_VALUE_4);
Assert.True(enums2.uint32b5 == enums1.uint32b3);
Assert.True(enums2.int64b0 == EnumInt64.ENUM_VALUE_0);
Assert.True(enums2.int64b1 == EnumInt64.ENUM_VALUE_1);
Assert.True(enums2.int64b2 == EnumInt64.ENUM_VALUE_2);
Assert.True(enums2.int64b3 == EnumInt64.ENUM_VALUE_3);
Assert.True(enums2.int64b4 == EnumInt64.ENUM_VALUE_4);
Assert.True(enums2.int64b5 == enums1.int64b3);
Assert.True(enums2.uint64b0 == EnumUInt64.ENUM_VALUE_0);
Assert.True(enums2.uint64b1 == EnumUInt64.ENUM_VALUE_1);
Assert.True(enums2.uint64b2 == EnumUInt64.ENUM_VALUE_2);
Assert.True(enums2.uint64b3 == EnumUInt64.ENUM_VALUE_3);
Assert.True(enums2.uint64b4 == EnumUInt64.ENUM_VALUE_4);
Assert.True(enums2.uint64b5 == enums1.uint64b3);
}
[Fact(DisplayName = "Serialization (Final): enums")]
public void SerializationFinalEnums()
{
var enums1 = Enums.Default;
// Serialize enums to the FBE stream
var writer = new EnumsFinalModel();
long serialized = writer.Serialize(enums1);
Assert.True(serialized == writer.Buffer.Size);
Assert.True(writer.Verify());
writer.Next(serialized);
// Check the serialized FBE size
Assert.True(writer.Buffer.Size == 224);
// Deserialize enums from the FBE stream
var reader = new EnumsFinalModel();
reader.Attach(writer.Buffer);
Assert.True(reader.Verify());
long deserialized = reader.Deserialize(out var enums2);
Assert.True(deserialized == reader.Buffer.Size);
reader.Next(deserialized);
Assert.True(enums2.byte0 == EnumByte.ENUM_VALUE_0);
Assert.True(enums2.byte1 == EnumByte.ENUM_VALUE_1);
Assert.True(enums2.byte2 == EnumByte.ENUM_VALUE_2);
Assert.True(enums2.byte3 == EnumByte.ENUM_VALUE_3);
Assert.True(enums2.byte4 == EnumByte.ENUM_VALUE_4);
Assert.True(enums2.byte5 == enums1.byte3);
Assert.True(enums2.char0 == EnumChar.ENUM_VALUE_0);
Assert.True(enums2.char1 == EnumChar.ENUM_VALUE_1);
Assert.True(enums2.char2 == EnumChar.ENUM_VALUE_2);
Assert.True(enums2.char3 == EnumChar.ENUM_VALUE_3);
Assert.True(enums2.char4 == EnumChar.ENUM_VALUE_4);
Assert.True(enums2.char5 == enums1.char3);
Assert.True(enums2.wchar0 == EnumWChar.ENUM_VALUE_0);
Assert.True(enums2.wchar1 == EnumWChar.ENUM_VALUE_1);
Assert.True(enums2.wchar2 == EnumWChar.ENUM_VALUE_2);
Assert.True(enums2.wchar3 == EnumWChar.ENUM_VALUE_3);
Assert.True(enums2.wchar4 == EnumWChar.ENUM_VALUE_4);
Assert.True(enums2.wchar5 == enums1.wchar3);
Assert.True(enums2.int8b0 == EnumInt8.ENUM_VALUE_0);
Assert.True(enums2.int8b1 == EnumInt8.ENUM_VALUE_1);
Assert.True(enums2.int8b2 == EnumInt8.ENUM_VALUE_2);
Assert.True(enums2.int8b3 == EnumInt8.ENUM_VALUE_3);
Assert.True(enums2.int8b4 == EnumInt8.ENUM_VALUE_4);
Assert.True(enums2.int8b5 == enums1.int8b3);
Assert.True(enums2.uint8b0 == EnumUInt8.ENUM_VALUE_0);
Assert.True(enums2.uint8b1 == EnumUInt8.ENUM_VALUE_1);
Assert.True(enums2.uint8b2 == EnumUInt8.ENUM_VALUE_2);
Assert.True(enums2.uint8b3 == EnumUInt8.ENUM_VALUE_3);
Assert.True(enums2.uint8b4 == EnumUInt8.ENUM_VALUE_4);
Assert.True(enums2.uint8b5 == enums1.uint8b3);
Assert.True(enums2.int16b0 == EnumInt16.ENUM_VALUE_0);
Assert.True(enums2.int16b1 == EnumInt16.ENUM_VALUE_1);
Assert.True(enums2.int16b2 == EnumInt16.ENUM_VALUE_2);
Assert.True(enums2.int16b3 == EnumInt16.ENUM_VALUE_3);
Assert.True(enums2.int16b4 == EnumInt16.ENUM_VALUE_4);
Assert.True(enums2.int16b5 == enums1.int16b3);
Assert.True(enums2.uint16b0 == EnumUInt16.ENUM_VALUE_0);
Assert.True(enums2.uint16b1 == EnumUInt16.ENUM_VALUE_1);
Assert.True(enums2.uint16b2 == EnumUInt16.ENUM_VALUE_2);
Assert.True(enums2.uint16b3 == EnumUInt16.ENUM_VALUE_3);
Assert.True(enums2.uint16b4 == EnumUInt16.ENUM_VALUE_4);
Assert.True(enums2.uint16b5 == enums1.uint16b3);
Assert.True(enums2.int32b0 == EnumInt32.ENUM_VALUE_0);
Assert.True(enums2.int32b1 == EnumInt32.ENUM_VALUE_1);
Assert.True(enums2.int32b2 == EnumInt32.ENUM_VALUE_2);
Assert.True(enums2.int32b3 == EnumInt32.ENUM_VALUE_3);
Assert.True(enums2.int32b4 == EnumInt32.ENUM_VALUE_4);
Assert.True(enums2.int32b5 == enums1.int32b3);
Assert.True(enums2.uint32b0 == EnumUInt32.ENUM_VALUE_0);
Assert.True(enums2.uint32b1 == EnumUInt32.ENUM_VALUE_1);
Assert.True(enums2.uint32b2 == EnumUInt32.ENUM_VALUE_2);
Assert.True(enums2.uint32b3 == EnumUInt32.ENUM_VALUE_3);
Assert.True(enums2.uint32b4 == EnumUInt32.ENUM_VALUE_4);
Assert.True(enums2.uint32b5 == enums1.uint32b3);
Assert.True(enums2.int64b0 == EnumInt64.ENUM_VALUE_0);
Assert.True(enums2.int64b1 == EnumInt64.ENUM_VALUE_1);
Assert.True(enums2.int64b2 == EnumInt64.ENUM_VALUE_2);
Assert.True(enums2.int64b3 == EnumInt64.ENUM_VALUE_3);
Assert.True(enums2.int64b4 == EnumInt64.ENUM_VALUE_4);
Assert.True(enums2.int64b5 == enums1.int64b3);
Assert.True(enums2.uint64b0 == EnumUInt64.ENUM_VALUE_0);
Assert.True(enums2.uint64b1 == EnumUInt64.ENUM_VALUE_1);
Assert.True(enums2.uint64b2 == EnumUInt64.ENUM_VALUE_2);
Assert.True(enums2.uint64b3 == EnumUInt64.ENUM_VALUE_3);
Assert.True(enums2.uint64b4 == EnumUInt64.ENUM_VALUE_4);
Assert.True(enums2.uint64b5 == enums1.uint64b3);
}
[Fact(DisplayName = "Serialization (JSON): enums")]
public void SerializationJsonEnums()
{
// Define a source JSON string
var json = @"{""byte0"":0,""byte1"":0,""byte2"":1,""byte3"":254,""byte4"":255,""byte5"":254,""char0"":0,""char1"":49,""char2"":50,""char3"":51,""char4"":52,""char5"":51,""wchar0"":0,""wchar1"":1092,""wchar2"":1093,""wchar3"":1365,""wchar4"":1366,""wchar5"":1365,""int8b0"":0,""int8b1"":-128,""int8b2"":-127,""int8b3"":126,""int8b4"":127,""int8b5"":126,""uint8b0"":0,""uint8b1"":0,""uint8b2"":1,""uint8b3"":254,""uint8b4"":255,""uint8b5"":254,""int16b0"":0,""int16b1"":-32768,""int16b2"":-32767,""int16b3"":32766,""int16b4"":32767,""int16b5"":32766,""uint16b0"":0,""uint16b1"":0,""uint16b2"":1,""uint16b3"":65534,""uint16b4"":65535,""uint16b5"":65534,""int32b0"":0,""int32b1"":-2147483648,""int32b2"":-2147483647,""int32b3"":2147483646,""int32b4"":2147483647,""int32b5"":2147483646,""uint32b0"":0,""uint32b1"":0,""uint32b2"":1,""uint32b3"":4294967294,""uint32b4"":4294967295,""uint32b5"":4294967294,""int64b0"":0,""int64b1"":-9223372036854775807,""int64b2"":-9223372036854775806,""int64b3"":9223372036854775806,""int64b4"":9223372036854775807,""int64b5"":9223372036854775806,""uint64b0"":0,""uint64b1"":0,""uint64b2"":1,""uint64b3"":18446744073709551614,""uint64b4"":18446744073709551615,""uint64b5"":18446744073709551614}";
// Create enums from the source JSON string
var enums1 = Enums.FromJson(json);
// Serialize enums to the JSON string
json = enums1.ToJson();
// Check the serialized JSON and its size
Assert.True(json.Length > 0);
// Deserialize enums from the JSON string
var enums2 = Enums.FromJson(json);
Assert.True(enums2.byte0 == EnumByte.ENUM_VALUE_0);
Assert.True(enums2.byte1 == EnumByte.ENUM_VALUE_1);
Assert.True(enums2.byte2 == EnumByte.ENUM_VALUE_2);
Assert.True(enums2.byte3 == EnumByte.ENUM_VALUE_3);
Assert.True(enums2.byte4 == EnumByte.ENUM_VALUE_4);
Assert.True(enums2.byte5 == enums1.byte3);
Assert.True(enums2.char0 == EnumChar.ENUM_VALUE_0);
Assert.True(enums2.char1 == EnumChar.ENUM_VALUE_1);
Assert.True(enums2.char2 == EnumChar.ENUM_VALUE_2);
Assert.True(enums2.char3 == EnumChar.ENUM_VALUE_3);
Assert.True(enums2.char4 == EnumChar.ENUM_VALUE_4);
Assert.True(enums2.char5 == enums1.char3);
Assert.True(enums2.wchar0 == EnumWChar.ENUM_VALUE_0);
Assert.True(enums2.wchar1 == EnumWChar.ENUM_VALUE_1);
Assert.True(enums2.wchar2 == EnumWChar.ENUM_VALUE_2);
Assert.True(enums2.wchar3 == EnumWChar.ENUM_VALUE_3);
Assert.True(enums2.wchar4 == EnumWChar.ENUM_VALUE_4);
Assert.True(enums2.wchar5 == enums1.wchar3);
Assert.True(enums2.int8b0 == EnumInt8.ENUM_VALUE_0);
Assert.True(enums2.int8b1 == EnumInt8.ENUM_VALUE_1);
Assert.True(enums2.int8b2 == EnumInt8.ENUM_VALUE_2);
Assert.True(enums2.int8b3 == EnumInt8.ENUM_VALUE_3);
Assert.True(enums2.int8b4 == EnumInt8.ENUM_VALUE_4);
Assert.True(enums2.int8b5 == enums1.int8b3);
Assert.True(enums2.uint8b0 == EnumUInt8.ENUM_VALUE_0);
Assert.True(enums2.uint8b1 == EnumUInt8.ENUM_VALUE_1);
Assert.True(enums2.uint8b2 == EnumUInt8.ENUM_VALUE_2);
Assert.True(enums2.uint8b3 == EnumUInt8.ENUM_VALUE_3);
Assert.True(enums2.uint8b4 == EnumUInt8.ENUM_VALUE_4);
Assert.True(enums2.uint8b5 == enums1.uint8b3);
Assert.True(enums2.int16b0 == EnumInt16.ENUM_VALUE_0);
Assert.True(enums2.int16b1 == EnumInt16.ENUM_VALUE_1);
Assert.True(enums2.int16b2 == EnumInt16.ENUM_VALUE_2);
Assert.True(enums2.int16b3 == EnumInt16.ENUM_VALUE_3);
Assert.True(enums2.int16b4 == EnumInt16.ENUM_VALUE_4);
Assert.True(enums2.int16b5 == enums1.int16b3);
Assert.True(enums2.uint16b0 == EnumUInt16.ENUM_VALUE_0);
Assert.True(enums2.uint16b1 == EnumUInt16.ENUM_VALUE_1);
Assert.True(enums2.uint16b2 == EnumUInt16.ENUM_VALUE_2);
Assert.True(enums2.uint16b3 == EnumUInt16.ENUM_VALUE_3);
Assert.True(enums2.uint16b4 == EnumUInt16.ENUM_VALUE_4);
Assert.True(enums2.uint16b5 == enums1.uint16b3);
Assert.True(enums2.int32b0 == EnumInt32.ENUM_VALUE_0);
Assert.True(enums2.int32b1 == EnumInt32.ENUM_VALUE_1);
Assert.True(enums2.int32b2 == EnumInt32.ENUM_VALUE_2);
Assert.True(enums2.int32b3 == EnumInt32.ENUM_VALUE_3);
Assert.True(enums2.int32b4 == EnumInt32.ENUM_VALUE_4);
Assert.True(enums2.int32b5 == enums1.int32b3);
Assert.True(enums2.uint32b0 == EnumUInt32.ENUM_VALUE_0);
Assert.True(enums2.uint32b1 == EnumUInt32.ENUM_VALUE_1);
Assert.True(enums2.uint32b2 == EnumUInt32.ENUM_VALUE_2);
Assert.True(enums2.uint32b3 == EnumUInt32.ENUM_VALUE_3);
Assert.True(enums2.uint32b4 == EnumUInt32.ENUM_VALUE_4);
Assert.True(enums2.uint32b5 == enums1.uint32b3);
Assert.True(enums2.int64b0 == EnumInt64.ENUM_VALUE_0);
Assert.True(enums2.int64b1 == EnumInt64.ENUM_VALUE_1);
Assert.True(enums2.int64b2 == EnumInt64.ENUM_VALUE_2);
Assert.True(enums2.int64b3 == EnumInt64.ENUM_VALUE_3);
Assert.True(enums2.int64b4 == EnumInt64.ENUM_VALUE_4);
Assert.True(enums2.int64b5 == enums1.int64b3);
Assert.True(enums2.uint64b0 == EnumUInt64.ENUM_VALUE_0);
Assert.True(enums2.uint64b1 == EnumUInt64.ENUM_VALUE_1);
Assert.True(enums2.uint64b2 == EnumUInt64.ENUM_VALUE_2);
Assert.True(enums2.uint64b3 == EnumUInt64.ENUM_VALUE_3);
Assert.True(enums2.uint64b4 == EnumUInt64.ENUM_VALUE_4);
Assert.True(enums2.uint64b5 == enums1.uint64b3);
}
}
}
| 54.191693 | 1,235 | 0.635479 | [
"MIT"
] | chronoxor/Fast-Binary-Encoding | projects/CSharp/Tests/Enums.cs | 16,964 | C# |
using System.Collections.Concurrent;
using AElf.CSharp.Core.Extension;
using AElf.Kernel;
using Google.Protobuf.WellKnownTypes;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Volo.Abp.DependencyInjection;
namespace AElf.OS.Network.Infrastructure
{
public interface IPeerInvalidTransactionProvider
{
bool TryMarkInvalidTransaction(string host);
bool TryRemoveInvalidRecord(string host);
}
public class PeerInvalidTransactionProvider : IPeerInvalidTransactionProvider, ISingletonDependency
{
private readonly NetworkOptions _networkOptions;
private readonly ConcurrentDictionary<string, ConcurrentQueue<Timestamp>> _invalidTransactionCache;
public ILogger<PeerInvalidTransactionProvider> Logger { get; set; }
public PeerInvalidTransactionProvider(IOptionsSnapshot<NetworkOptions> networkOptions)
{
_networkOptions = networkOptions.Value;
_invalidTransactionCache = new ConcurrentDictionary<string, ConcurrentQueue<Timestamp>>();
Logger = NullLogger<PeerInvalidTransactionProvider>.Instance;
}
public bool TryMarkInvalidTransaction(string host)
{
if (!_invalidTransactionCache.TryGetValue(host, out var queue))
{
queue = new ConcurrentQueue<Timestamp>();
_invalidTransactionCache[host] = queue;
}
CleanCache(queue);
Logger.LogDebug($"Mark peer invalid transaction. host: {host}, count: {queue.Count}");
if (queue.Count >= _networkOptions.PeerInvalidTransactionLimit)
return false;
queue.Enqueue(TimestampHelper.GetUtcNow());
return true;
}
public bool TryRemoveInvalidRecord(string host)
{
return _invalidTransactionCache.TryRemove(host, out _);
}
private void CleanCache(ConcurrentQueue<Timestamp> queue)
{
while (!queue.IsEmpty
&& queue.TryPeek(out var timestamp)
&& timestamp.AddMilliseconds(_networkOptions.PeerInvalidTransactionTimeout) < TimestampHelper.GetUtcNow())
{
queue.TryDequeue(out _);
}
}
}
} | 34.376812 | 125 | 0.66231 | [
"MIT"
] | ezaruba/AElf | src/AElf.OS.Core/Network/Infrastructure/IPeerInvalidTransactionProvider.cs | 2,372 | C# |
/*
http://www.cgsoso.com/forum-211-1.html
CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源!
CGSOSO 主打游戏开发,影视设计等CG资源素材。
插件如若商用,请务必官网购买!
daily assets update for try.
U should buy the asset from home store if u use it in your project!
*/
using UnityEngine;
using System.Collections;
public class LoadLevelWithDelay : MonoBehaviour
{
[Tooltip("Seconds to wait before loading next level.")]
public float waitSeconds = 0f;
[Tooltip("Next level number. No level is loaded, if the number is negative.")]
public int nextLevel = -1;
[Tooltip("Whether to check for initialized KinectManager or not.")]
public bool validateKinectManager = true;
[Tooltip("GUI-Text used to display the debug messages.")]
public GUIText debugText;
private float timeToLoadLevel = 0f;
private bool levelLoaded = false;
void Start()
{
timeToLoadLevel = Time.realtimeSinceStartup + waitSeconds;
if(validateKinectManager && debugText != null)
{
KinectManager manager = KinectManager.Instance;
if(manager == null || !manager.IsInitialized())
{
debugText.GetComponent<GUIText>().text = "KinectManager is not initialized!";
levelLoaded = true;
}
}
}
void Update()
{
if(!levelLoaded && nextLevel >= 0)
{
if(Time.realtimeSinceStartup >= timeToLoadLevel)
{
levelLoaded = true;
Application.LoadLevel(nextLevel);
}
else
{
float timeRest = timeToLoadLevel - Time.realtimeSinceStartup;
if(debugText != null)
{
debugText.GetComponent<GUIText>().text = string.Format("Time to the next level: {0:F0} s.", timeRest);
}
}
}
}
}
| 21.146667 | 107 | 0.701765 | [
"Apache-2.0"
] | 154544017/BorderEscape | Assets/Scripts/KinectScripts/MultiScene/LoadLevelWithDelay.cs | 1,680 | C# |
// Copyright 2009-2012 Matvei Stefarov <me@matvei.org>
using System;
using System.Collections.Generic;
using System.Linq;
using GemsCraft.fSystem;
using GemsCraft.Configuration;
using GemsCraft.Players;
using GemsCraft.Utils;
using JetBrains.Annotations;
namespace GemsCraft.Commands
{
/// <summary> Delegate for command handlers/callbacks. </summary>
/// <param name="source"> Player who called the command. </param>
/// <param name="cmd"> Command arguments. </param>
public delegate void CommandHandler(Player source, Command cmd);
/// <summary> Describes a chat command. Defines properties, permission requirements, and usage information.
/// Specifies a handler method. </summary>
public sealed class CommandDescriptor : IClassy
{
/// <summary> List of aliases. May be null or empty. Default: null </summary>
[CanBeNull]
public string[] Aliases { get; set; }
/// <summary> Command category. Must be set before registering. </summary>
public CommandCategory Category { get; set; }
/// <summary> Whether the command may be used from console. Default: false </summary>
public bool IsConsoleSafe { get; set; }
/// <summary> Callback function to execute when command is called. Must be set before registering. </summary>
public CommandHandler Handler { get; set; }
/// <summary> Full text of the help message. Default: null </summary>
public string Help { get; set; }
/// <summary> Whether the command is hidden from command list (/cmds). Default: false </summary>
public bool IsHidden { get; set; }
/// <summary> Whether the command is not part of fCraft core (set automatically). </summary>
public bool IsCustom { get; internal set; }
/// <summary> Whether the command should be repeated by the "/" shortcut. Default: false </summary>
public bool NotRepeatable { get; set; }
/// <summary> Whether the command should be usable by frozen players. Default: false </summary>
public bool UsableByFrozenPlayers { get; set; }
/// <summary> Whether calls to this command should not be logged. </summary>
public bool DisableLogging { get; set; }
/// <summary> Primary command name. Must be set before registering. </summary>
public string Name { get; set; }
/// <summary> List of permissions required to call the command. May be empty or null. Default: null </summary>
public Permission[] Permissions { get; set; }
/// <summary> Whether any permission from the list is enough.
/// If this is false, ALL permissions are required. </summary>
public bool AnyPermission { get; set; }
/// <summary> Brief demonstration of command's usage syntax. Defaults to "/Name". </summary>
public string Usage { get; set; }
/// <summary> Help sub-sectionses. </summary>
public Dictionary<string, string> HelpSections { get; set; }
/// <summary> Whether this command involves a selection that can be repeated with /static. Default: false </summary>
public bool RepeatableSelection { get; set; }
/// <summary> Checks whether this command may be called by players of a given rank. </summary>
public bool CanBeCalledBy([NotNull] Rank rank, bool isConsole)
{
if (rank == null && !isConsole)
{
throw new ArgumentNullException("rank");
}
if (isConsole) return true;
return Permissions == null ||
Permissions.All(rank.Can) ||
AnyPermission && Permissions.Any(rank.Can);
}
public Rank MinRank
{
get
{
if (AnyPermission)
{
return RankManager.GetMinRankWithAnyPermission(Permissions);
}
else
{
return RankManager.GetMinRankWithAllPermissions(Permissions);
}
}
}
/// <summary> Checks whether players of the given rank should see this command in /cmds list.
/// Takes permissions and the hidden flag into account. </summary>
public bool IsVisibleTo([NotNull] Rank rank, bool isConsole)
{
if (rank == null) throw new ArgumentNullException("rank");
return !IsHidden && CanBeCalledBy(rank, isConsole);
}
/// <summary> Prints command usage syntax to the given player. </summary>
public void PrintUsage([NotNull] Player player)
{
if (player == null) throw new ArgumentNullException("player");
if (Usage != null)
{
player.Message("Usage: &H{0}", Usage);
}
else
{
player.Message("Usage: &H/{0}", Name);
}
}
/// <summary> Calls this command. </summary>
/// <param name="player"> Player who called the command. </param>
/// <param name="cmd"> Command arguments. </param>
/// <param name="raiseEvent"> Whether CommandCalling and CommandCalled events should be raised. </param>
/// <returns> True if the command was called succesfully.
/// False if the call was cancelled by the CommandCalling event. </returns>
public bool Call([NotNull] Player player, [NotNull] Command cmd, bool raiseEvent)
{
if (player == null) throw new ArgumentNullException("player");
if (cmd == null) throw new ArgumentNullException("cmd");
if (raiseEvent && CommandManager.RaiseCommandCallingEvent(cmd, this, player)) return false;
Handler(player, cmd);
if (raiseEvent) CommandManager.RaiseCommandCalledEvent(cmd, this, player);
return true;
}
public override string ToString()
{
return $"CommandDescriptor({Name})";
}
public string ClassyName
{
get
{
if (ConfigKey.RankColorsInChat.Enabled())
{
Rank minRank;
if (Permissions != null && Permissions.Length > 0)
{
minRank = MinRank;
}
else
{
minRank = RankManager.LowestRank;
}
if (minRank == null)
{
return Name;
}
else if (ConfigKey.RankPrefixesInChat.Enabled())
{
return minRank.Color + minRank.Prefix + Name;
}
else
{
return minRank.Color + Name;
}
}
else
{
return Name;
}
}
}
}
} | 37.322751 | 124 | 0.56025 | [
"MIT"
] | apotter96/GemsCraft-Classic | GemsCraft/Commands/CommandDescriptor.cs | 7,056 | C# |
using System;
using Knet.Kudu.Client.Internal;
namespace Knet.Kudu.Client.Protocol;
public sealed class KuduMessage
{
private ArrayPoolBuffer<byte>? _messageBuffer;
private int _messageProtobufLength;
private SidecarOffset[]? _sidecarOffsets;
internal void Init(
ArrayPoolBuffer<byte> messageBuffer,
int messageProtobufLength,
SidecarOffset[] sidecarOffsets)
{
_messageBuffer = messageBuffer;
_messageProtobufLength = messageProtobufLength;
_sidecarOffsets = sidecarOffsets;
}
public byte[] Buffer => _messageBuffer!.Buffer;
public ReadOnlySpan<byte> MessageProtobuf =>
Buffer.AsSpan(0, _messageProtobufLength);
public SidecarOffset GetSidecarOffset(int sidecar) => _sidecarOffsets![sidecar];
internal ArrayPoolBuffer<byte> TakeMemory()
{
var messageBuffer = _messageBuffer;
_messageBuffer = null;
return messageBuffer!;
}
internal void Reset()
{
var buffer = _messageBuffer;
if (buffer is not null)
{
_messageBuffer = null;
buffer.Dispose();
}
_messageProtobufLength = 0;
_sidecarOffsets = null;
}
}
| 24.938776 | 84 | 0.663666 | [
"Apache-2.0"
] | xqrzd/kudu | src/Knet.Kudu.Client/Protocol/KuduMessage.cs | 1,222 | C# |
using BotDetect.Web.Mvc;
using GISCore.Business.Abstract;
using GISCore.Infrastructure.Utils;
using GISModel.DTO.Conta;
using GISModel.DTO.Shared;
using GISWeb.Infraestrutura.Filters;
using GISWeb.Infraestrutura.Provider.Abstract;
using Ninject;
using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.SessionState;
using System.Web.UI;
namespace GISWeb.Controllers
{
[SessionState(SessionStateBehavior.ReadOnly)]
public class AccountController : BaseController
{
#region Inject
[Inject]
public ICustomAuthorizationProvider AutorizacaoProvider { get; set; }
[Inject]
public IUsuarioBusiness UsuarioBusiness { get; set; }
#endregion
public ActionResult Login(string path)
{
ViewBag.OcultarMenus = true;
ViewBag.IncluirCaptcha = Convert.ToBoolean(ConfigurationManager.AppSettings["AD:DMZ"]);
ViewBag.UrlAnterior = path;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(AutenticacaoModel usuario)
{
try
{
if (ModelState.IsValid)
{
foreach (var cookieKey in Request.Cookies.AllKeys.Where(c => !c.Equals("__RequestVerificationToken")))
{
var deleteCookie = new HttpCookie(cookieKey);
deleteCookie.Expires = DateTime.Now;
Response.Cookies.Add(deleteCookie);
}
AutorizacaoProvider.Logar(usuario);
if (!string.IsNullOrWhiteSpace(usuario.Nome))
return Json(new { url = usuario.Nome.Replace("$", "&") });
else
return Json(new { url = Url.Action(ConfigurationManager.AppSettings["Web:DefaultAction"], ConfigurationManager.AppSettings["Web:DefaultController"]) });
}
return View(usuario);
}
catch (Exception ex)
{
return Json(new { alerta = ex.Message, titulo = "Oops! Problema ao realizar login..." });
}
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[CaptchaValidation("CaptchaCode", "LoginCaptcha", "Código do CAPTCHA incorreto.")]
public ActionResult LoginComCaptcha(AutenticacaoModel usuario)
{
MvcCaptcha.ResetCaptcha("LoginCaptcha");
ViewBag.IncluirCaptcha = Convert.ToBoolean(ConfigurationManager.AppSettings["AD:DMZ"]);
try
{
if (ModelState.IsValid)
{
AutorizacaoProvider.Logar(usuario);
if (!string.IsNullOrWhiteSpace(usuario.Nome))
return Json(new { url = usuario.Nome.Replace("$", "&") });
else
return Json(new { url = Url.Action(ConfigurationManager.AppSettings["Web:DefaultAction"], ConfigurationManager.AppSettings["Web:DefaultController"]) });
}
return View("Login", usuario);
}
catch (Exception ex)
{
return Json(new { alerta = ex.Message, titulo = "Oops! Problema ao realizar login..." });
}
}
public ActionResult Logout()
{
AutorizacaoProvider.Deslogar();
foreach (var cookieKey in Request.Cookies.AllKeys)
{
var deleteCookie = new HttpCookie(cookieKey);
deleteCookie.Expires = DateTime.Now;
Response.Cookies.Add(deleteCookie);
}
return RedirectToAction("Login", "Account");
}
[Autorizador]
[DadosUsuario]
public ActionResult Perfil()
{
return View(AutorizacaoProvider.UsuarioAutenticado);
}
[HttpPost]
[Autorizador]
[DadosUsuario]
public ActionResult AtualizarFoto(string imagemStringBase64)
{
try
{
UsuarioBusiness.SalvarAvatar(AutorizacaoProvider.UsuarioAutenticado.Login, imagemStringBase64, "jpg");
}
catch (Exception ex)
{
Extensions.GravaCookie("MensagemErro", ex.Message, 2);
}
return Json(new { url = Url.Action("Perfil") });
}
[OutputCache(Duration = 604800, Location = OutputCacheLocation.Client, VaryByParam = "login")]
public ActionResult FotoPerfil(string login)
{
byte[] avatar = null;
try
{
avatar = UsuarioBusiness.RecuperarAvatar(login);
}
catch { }
if (avatar == null || avatar.Length == 0)
avatar = System.IO.File.ReadAllBytes(Server.MapPath("~/Content/Ace/avatars/unknown.png"));
return File(avatar, "image/jpeg");
}
public ActionResult DefinirNovaSenha(string id)
{
try
{
if (string.IsNullOrEmpty(id))
{
TempData["MensagemErro"] = "Não foi possível recuperar a identificação do usuário.";
}
else
{
id = GISHelpers.Utils.Criptografador.Descriptografar(WebUtility.UrlDecode(id.Replace("_@", "%")), 1);
string numDiasExpiracao = ConfigurationManager.AppSettings["Web:ExpirarLinkAcesso"];
if (string.IsNullOrEmpty(numDiasExpiracao))
numDiasExpiracao = "1";
if (DateTime.Now.Subtract(DateTime.ParseExact(id.Substring(id.IndexOf("#") + 1), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)).Days > int.Parse(numDiasExpiracao))
{
TempData["MensagemErro"] = "Este link já expirou, solicite um outro link na opção abaixo.";
}
else
{
NovaSenhaViewModel oNovaSenhaViewModel = new NovaSenhaViewModel();
oNovaSenhaViewModel.IDUsuario = id.Substring(0, id.IndexOf("#"));
return View(oNovaSenhaViewModel);
}
}
}
catch (Exception ex)
{
if (ex.GetBaseException() == null)
{
TempData["MensagemErro"] = ex.Message;
}
else
{
TempData["MensagemErro"] = ex.GetBaseException().Message;
}
}
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult DefinirSenha(NovaSenhaViewModel novaSenhaViewModel)
{
if (ModelState.IsValid)
{
if (novaSenhaViewModel.NovaSenha.Equals(novaSenhaViewModel.ConfirmarNovaSenha))
{
try
{
if (string.IsNullOrEmpty(novaSenhaViewModel.IDUsuario))
return Json(new { resultado = new RetornoJSON() { Erro = "Não foi possível localizar o ID do usuário através de sua requisição. Solicite um novo acesso." } });
UsuarioBusiness.DefinirSenha(novaSenhaViewModel);
TempData["MensagemSucesso"] = "Senha alterada com sucesso.";
return Json(new { resultado = new RetornoJSON() { URL = Url.Action("Login", "Conta") } });
}
catch (Exception ex)
{
if (ex.GetBaseException() == null)
{
return Json(new { resultado = new RetornoJSON() { Erro = ex.Message } });
}
else
{
return Json(new { resultado = new RetornoJSON() { Erro = ex.GetBaseException().Message } });
}
}
}
else
{
return Json(new { resultado = new RetornoJSON() { Erro = "As duas senhas devem ser identicas." } });
}
}
else
{
return Json(new { resultado = TratarRetornoValidacaoToJSON() });
}
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult SolicitarAcesso(NovaSenhaViewModel novaSenhaViewModel)
{
if (!string.IsNullOrEmpty(novaSenhaViewModel.Email))
{
try
{
UsuarioBusiness.SolicitarAcesso(novaSenhaViewModel.Email);
TempData["MensagemSucesso"] = "Solicitação de acesso realizada com sucesso.";
return Json(new { resultado = new RetornoJSON() { URL = Url.Action("Login", "Conta") } });
}
catch (Exception ex)
{
if (ex.GetBaseException() == null)
{
return Json(new { resultado = new RetornoJSON() { Erro = ex.Message } });
}
else
{
return Json(new { resultado = new RetornoJSON() { Erro = ex.GetBaseException().Message } });
}
}
}
else
{
return Json(new { resultado = new RetornoJSON() { Erro = "Informe o e-mail cadastrado em sua conta." } });
}
}
}
} | 35.33452 | 200 | 0.510021 | [
"Apache-2.0"
] | tonihenriques/GestaoSST | SESTEC/GISWeb/Controllers/AccountController.cs | 9,948 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Sql.Models;
namespace Azure.ResourceManager.Sql
{
/// <summary>
/// A Class representing a ServerSecurityAlertPolicy along with the instance operations that can be performed on it.
/// If you have a <see cref="ResourceIdentifier" /> you can construct a <see cref="ServerSecurityAlertPolicyResource" />
/// from an instance of <see cref="ArmClient" /> using the GetServerSecurityAlertPolicyResource method.
/// Otherwise you can get one from its parent resource <see cref="SqlServerResource" /> using the GetServerSecurityAlertPolicy method.
/// </summary>
public partial class ServerSecurityAlertPolicyResource : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="ServerSecurityAlertPolicyResource"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string serverName, string securityAlertPolicyName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _serverSecurityAlertPolicyClientDiagnostics;
private readonly ServerSecurityAlertPoliciesRestOperations _serverSecurityAlertPolicyRestClient;
private readonly ServerSecurityAlertPolicyData _data;
/// <summary> Initializes a new instance of the <see cref="ServerSecurityAlertPolicyResource"/> class for mocking. </summary>
protected ServerSecurityAlertPolicyResource()
{
}
/// <summary> Initializes a new instance of the <see cref = "ServerSecurityAlertPolicyResource"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal ServerSecurityAlertPolicyResource(ArmClient client, ServerSecurityAlertPolicyData data) : this(client, data.Id)
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="ServerSecurityAlertPolicyResource"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal ServerSecurityAlertPolicyResource(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_serverSecurityAlertPolicyClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Sql", ResourceType.Namespace, Diagnostics);
TryGetApiVersion(ResourceType, out string serverSecurityAlertPolicyApiVersion);
_serverSecurityAlertPolicyRestClient = new ServerSecurityAlertPoliciesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, serverSecurityAlertPolicyApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Sql/servers/securityAlertPolicies";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual ServerSecurityAlertPolicyData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary>
/// Get a server's security alert policy.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}
/// Operation Id: ServerSecurityAlertPolicies_Get
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<ServerSecurityAlertPolicyResource>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyResource.Get");
scope.Start();
try
{
var response = await _serverSecurityAlertPolicyRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new ServerSecurityAlertPolicyResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Get a server's security alert policy.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}
/// Operation Id: ServerSecurityAlertPolicies_Get
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<ServerSecurityAlertPolicyResource> Get(CancellationToken cancellationToken = default)
{
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyResource.Get");
scope.Start();
try
{
var response = _serverSecurityAlertPolicyRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new ServerSecurityAlertPolicyResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 52.208633 | 192 | 0.688163 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/ServerSecurityAlertPolicyResource.cs | 7,257 | C# |
using System;
using Framework.Persistent;
using Framework.SecuritySystem;
namespace Framework.DomainDriven.BLL.Security
{
public struct FilterItemIdentity : IDefaultIdentityObject, IEquatable<FilterItemIdentity>
{
public FilterItemIdentity(FilterItemType entityType, string id)
: this(entityType.ToString(), id)
{
}
public FilterItemIdentity(string entityName, string id)
: this(entityName, new Guid(id))
{
}
public FilterItemIdentity(FilterItemType entityType, Guid id)
: this(entityType.ToString(), id)
{
}
public FilterItemIdentity(string entityName, Guid id)
: this()
{
this.EntityName = entityName;
this.Id = id;
}
public string EntityName { get; set; }
public Guid Id { get; set; }
public override string ToString()
{
return $"Id: {this.Id}, EntityType: {this.EntityName}";
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
public override bool Equals(object obj)
{
return obj is FilterItemIdentity && this.Equals((FilterItemIdentity)obj);
}
public bool Equals(FilterItemIdentity other)
{
return this.Id == other.Id && this.EntityName == other.EntityName;
}
}
public static class FilterItemIdentityExtensions
{
public static FilterItemIdentity ToFilterItemIdentity(this string typeName, Guid id)
{
if (typeName == null) throw new ArgumentNullException(nameof(typeName));
return new FilterItemIdentity(typeName, id);
}
public static FilterItemIdentity ToFilterItemIdentity(this Type type, Guid id)
{
if (type == null) throw new ArgumentNullException(nameof(type));
return type.Name.ToFilterItemIdentity(id);
}
public static FilterItemIdentity ToFilterItemIdentity<TDomainObject>(this TDomainObject domainObject)
where TDomainObject : class, ISecurityContext, IDefaultIdentityObject
{
if (domainObject == null) throw new ArgumentNullException(nameof(domainObject));
return new FilterItemIdentity(typeof(TDomainObject).Name, domainObject.Id);
}
}
public enum FilterItemType
{
Location,
BusinessUnit,
ManagementUnit,
Employee
}
}
| 26.565657 | 110 | 0.590114 | [
"MIT"
] | Luxoft/BSSFramework | src/_DomainDriven/Framework.DomainDriven.Core/FilterItemIdentity.cs | 2,534 | C# |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// Task.cs
//
// <OWNER>hyildiz</OWNER>
//
// A schedulable unit of work.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
// Disable the "reference to volatile field not treated as volatile" error.
#pragma warning disable 0420
namespace System.Threading.Tasks
{
/// <summary>
/// Represents the current stage in the lifecycle of a <see cref="Task"/>.
/// </summary>
public enum TaskStatus
{
/// <summary>
/// The task has been initialized but has not yet been scheduled.
/// </summary>
Created,
/// <summary>
/// The task is waiting to be activated and scheduled internally by the .NET Framework infrastructure.
/// </summary>
WaitingForActivation,
/// <summary>
/// The task has been scheduled for execution but has not yet begun executing.
/// </summary>
WaitingToRun,
/// <summary>
/// The task is running but has not yet completed.
/// </summary>
Running,
// /// <summary>
// /// The task is currently blocked in a wait state.
// /// </summary>
// Blocked,
/// <summary>
/// The task has finished executing and is implicitly waiting for
/// attached child tasks to complete.
/// </summary>
WaitingForChildrenToComplete,
/// <summary>
/// The task completed execution successfully.
/// </summary>
RanToCompletion,
/// <summary>
/// The task acknowledged cancellation by throwing an OperationCanceledException2 with its own CancellationToken
/// while the token was in signaled state, or the task's CancellationToken was already signaled before the
/// task started executing.
/// </summary>
Canceled,
/// <summary>
/// The task completed due to an unhandled exception.
/// </summary>
Faulted
}
/// <summary>
/// Represents an asynchronous operation.
/// </summary>
/// <remarks>
/// <para>
/// <see cref="Task"/> instances may be created in a variety of ways. The most common approach is by
/// using the Task type's <see cref="Factory"/> property to retrieve a <see
/// cref="System.Threading.Tasks.TaskFactory"/> instance that can be used to create tasks for several
/// purposes. For example, to create a <see cref="Task"/> that runs an action, the factory's StartNew
/// method may be used:
/// <code>
/// // C#
/// var t = Task.Factory.StartNew(() => DoAction());
///
/// ' Visual Basic
/// Dim t = Task.Factory.StartNew(Function() DoAction())
/// </code>
/// </para>
/// <para>
/// The <see cref="Task"/> class also provides constructors that initialize the Task but that do not
/// schedule it for execution. For performance reasons, TaskFactory's StartNew method should be the
/// preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation
/// and scheduling must be separated, the constructors may be used, and the task's <see cref="Start()"/>
/// method may then be used to schedule the task for execution at a later time.
/// </para>
/// <para>
/// All members of <see cref="Task"/>, except for <see cref="Dispose()"/>, are thread-safe
/// and may be used from multiple threads concurrently.
/// </para>
/// <para>
/// For operations that return values, the <see cref="System.Threading.Tasks.Task{TResult}"/> class
/// should be used.
/// </para>
/// <para>
/// For developers implementing custom debuggers, several internal and private members of Task may be
/// useful (these may change from release to release). The Int32 m_taskId field serves as the backing
/// store for the <see cref="Id"/> property, however accessing this field directly from a debugger may be
/// more efficient than accessing the same value through the property's getter method (the
/// s_taskIdCounter Int32 counter is used to retrieve the next available ID for a Task). Similarly, the
/// Int32 m_stateFlags field stores information about the current lifecycle stage of the Task,
/// information also accessible through the <see cref="Status"/> property. The m_action System.Object
/// field stores a reference to the Task's delegate, and the m_stateObject System.Object field stores the
/// async state passed to the Task by the developer. Finally, for debuggers that parse stack frames, the
/// InternalWait method serves a potential marker for when a Task is entering a wait operation.
/// </para>
/// </remarks>
[DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskDebugView))]
[DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")]
public partial class Task : IThreadPoolWorkItem, IAsyncResult //, IDisposable
{
// Accessing ThreadStatic variables on classes with class constructors is much slower than if the class
// has no class constructor. So we declasre s_currentTask inside a nested class with no constructor.
// Do not put any static variables with explicit initialization in this class, as it will regress performance.
private static class ThreadLocals
{
internal static ThreadStatic<Task> s_currentTask = new ThreadStatic<Task>(); // The currently executing task.
}
internal static int s_taskIdCounter; //static counter used to generate unique task IDs
private static TaskFactory s_factory = new TaskFactory();
private int m_taskId; // this task's unique ID. initialized only if it is ever requested
internal object m_action; // The body of the task. Might be Action<object>, Action<TState> or Action.
// If m_action is set to null it will indicate that we operate in the
// "externally triggered completion" mode, which is exclusively meant
// for the signalling Task<TResult> (aka. promise). In this mode,
// we don't call InnerInvoke() in response to a Wait(), but simply wait on
// the completion event which will be set when the Future class calls Finish().
// But the event would now be signalled if Cancel() is called
internal object m_stateObject; // A state object that can be optionally supplied, passed to action.
internal TaskScheduler m_taskScheduler; // The task scheduler this task runs under. @TODO: is this required?
internal readonly Task m_parent; // A task's parent, or null if parent-less.
internal ExecutionContextLightup m_capturedContext; // The context to run the task within, if any.
internal volatile int m_stateFlags;
// State constants for m_stateFlags;
// The bits of m_stateFlags are allocated as follows:
// 0x40000000 - TaskBase state flag
// 0x3FFF0000 - Task state flags
// 0x0000FF00 - internal TaskCreationOptions flags
// 0x000000FF - publicly exposed TaskCreationOptions flags
//
// See TaskCreationOptions for bit values associated with TaskCreationOptions
//
private const int OptionsMask = 0xFFFF; // signifies the Options portion of m_stateFlags
internal const int TASK_STATE_STARTED = 0x10000;
internal const int TASK_STATE_DELEGATE_INVOKED = 0x20000;
internal const int TASK_STATE_DISPOSED = 0x40000;
internal const int TASK_STATE_EXCEPTIONOBSERVEDBYPARENT = 0x80000;
internal const int TASK_STATE_CANCELLATIONACKNOWLEDGED = 0x100000;
internal const int TASK_STATE_FAULTED = 0x200000;
internal const int TASK_STATE_CANCELED = 0x400000;
internal const int TASK_STATE_WAITING_ON_CHILDREN = 0x800000;
internal const int TASK_STATE_RAN_TO_COMPLETION = 0x1000000;
internal const int TASK_STATE_WAITINGFORACTIVATION = 0x2000000;
internal const int TASK_STATE_COMPLETION_RESERVED = 0x4000000;
internal const int TASK_STATE_THREAD_WAS_ABORTED = 0x8000000;
// Values for ContingentProperties.m_internalCancellationRequested.
internal static int CANCELLATION_REQUESTED = 0x1;
private volatile ManualResetEventSlim m_completionEvent; // Lazily created if waiting is required.
// We moved a number of Task properties into this class. The idea is that in most cases, these properties never
// need to be accessed during the life cycle of a Task, so we don't want to instantiate them every time. Once
// one of these properties needs to be written, we will instantiate a ContingentProperties object and set
// the appropriate property.
internal class ContingentProperties
{
public volatile int m_internalCancellationRequested; // We keep canceled in its own field because threads legally race to set it.
internal volatile int m_completionCountdown = 1; // # of active children + 1 (for this task itself).
// Used for ensuring all children are done before this task can complete
// The extra count helps prevent the race for executing the final state transition
// (i.e. whether the last child or this task itself should call FinishStageTwo())
public volatile TaskExceptionHolder m_exceptionsHolder; // Tracks exceptions, if any have occurred
public volatile List<Task> m_exceptionalChildren; // A list of child tasks that threw an exception (TCEs don't count),
// but haven't yet been waited on by the parent, lazily initialized.
public volatile List<TaskContinuation> m_continuations; // A list of tasks or actions to be started upon completion, lazily initialized.
public CancellationToken m_cancellationToken;
public Shared<CancellationTokenRegistration> m_cancellationRegistration;
}
internal class Shared<T>
{
internal T Value;
internal Shared(T value) { Value = value; }
}
// This field will only be instantiated to some non-null value if any ContingentProperties need to be set.
internal volatile ContingentProperties m_contingentProperties;
/// <summary>
/// A type initializer that runs with the appropriate permissions.
/// </summary>
// // [SecuritySafeCritical]
static Task()
{
s_ecCallback = new Action<object>(ExecutionContextCallback);
}
// Special internal constructor to create an already-completed task.
// if canceled==true, create a Canceled task, or else create a RanToCompletion task.
internal Task(bool canceled, TaskCreationOptions creationOptions, CancellationToken ct)
{
int optionFlags = (int)creationOptions;
if (canceled)
{
m_stateFlags = TASK_STATE_CANCELED | TASK_STATE_CANCELLATIONACKNOWLEDGED | optionFlags;
m_contingentProperties = ContingentPropertyCreator();
m_contingentProperties.m_cancellationToken = ct;
m_contingentProperties.m_internalCancellationRequested = CANCELLATION_REQUESTED;
}
else
m_stateFlags = TASK_STATE_RAN_TO_COMPLETION | optionFlags;
}
// Special internal constructor to create an already-Faulted task.
// Break this out when we need it.
//
//internal Task(Exception exception, bool attached)
//{
// Task m_parent = attached ? Task.InternalCurrent : null;
//
// if(m_parent != null) m_parent.AddNewChild();
//
// m_contingentProperties = new ContingentProperties();
// m_contingentProperties.m_exceptionsHolder = new TaskExceptionHolder(this);
// m_contingentProperties.m_exceptionsHolder.Add(exception);
// m_stateFlags = TASK_STATE_FAULTED;
//
// if (m_parent != null) m_parent.ProcessChildCompletion(this);
//}
// Special constructor for use with promise-style tasks.
// Added promiseStyle parameter as an aid to the compiler to distinguish between (state,TCO) and
// (action,TCO). It should always be true.
internal Task(object state, CancellationToken cancelationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, bool promiseStyle)
{
Contract.Assert(promiseStyle, "Promise CTOR: promiseStyle was false");
// Check the creationOptions. We only allow the attached/detached option to be specified for promise tasks.
if ((creationOptions & ~(TaskCreationOptions.AttachedToParent)) != 0)
{
throw new ArgumentOutOfRangeException("creationOptions");
}
// Make sure that no illegal InternalTaskOptions are specified
Contract.Assert((internalOptions & ~(InternalTaskOptions.PromiseTask)) == 0, "Illegal internal options in Task(obj,ct,tco,ito,bool)");
// m_parent is readonly, and so must be set in the constructor.
// Only set a parent if AttachedToParent is specified.
if ((creationOptions & TaskCreationOptions.AttachedToParent) != 0)
m_parent = Task.InternalCurrent;
TaskConstructorCore(null, state, cancelationToken, creationOptions, internalOptions, TaskScheduler.Current);
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the Task.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="action"/> argument is null.</exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action action)
: this((object)action, null, Task.InternalCurrent, CancellationToken.None, TaskCreationOptions.None, InternalTaskOptions.None, null)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PossiblyCaptureContext(ref stackMark);
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action and <see cref="System.Threading.CancellationToken">CancellationToken</see>.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the Task.</param>
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// that will be assigned to the new Task.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="action"/> argument is null.</exception>
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action action, CancellationToken cancellationToken)
: this((object)action, null, Task.InternalCurrent, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PossiblyCaptureContext(ref stackMark);
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action and creation options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="creationOptions">
/// The <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used to
/// customize the Task's behavior.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskCreationOptions"/>.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action action, TaskCreationOptions creationOptions)
: this((object)action, null, Task.InternalCurrent, CancellationToken.None, creationOptions, InternalTaskOptions.None, null)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PossiblyCaptureContext(ref stackMark);
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action and creation options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
/// <param name="creationOptions">
/// The <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used to
/// customize the Task's behavior.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskCreationOptions"/>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this((object)action, null, Task.InternalCurrent, cancellationToken, creationOptions, InternalTaskOptions.None, null)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PossiblyCaptureContext(ref stackMark);
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action and state.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="state">An object representing data to be used by the action.</param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action<object> action, object state)
: this((object)action, state, Task.InternalCurrent, CancellationToken.None, TaskCreationOptions.None, InternalTaskOptions.None, null)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PossiblyCaptureContext(ref stackMark);
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action, state, snd options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="state">An object representing data to be used by the action.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action<object> action, object state, CancellationToken cancellationToken)
: this((object)action, state, Task.InternalCurrent, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PossiblyCaptureContext(ref stackMark);
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action, state, snd options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="state">An object representing data to be used by the action.</param>
/// <param name="creationOptions">
/// The <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used to
/// customize the Task's behavior.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskCreationOptions"/>.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action<object> action, object state, TaskCreationOptions creationOptions)
: this((object)action, state, Task.InternalCurrent, CancellationToken.None, creationOptions, InternalTaskOptions.None, null)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PossiblyCaptureContext(ref stackMark);
}
/// <summary>
/// Initializes a new <see cref="Task"/> with the specified action, state, snd options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="state">An object representing data to be used by the action.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
/// <param name="creationOptions">
/// The <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used to
/// customize the Task's behavior.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="action"/> argument is null.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskCreationOptions"/>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task(Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
: this((object)action, state, Task.InternalCurrent, cancellationToken, creationOptions, InternalTaskOptions.None, null)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PossiblyCaptureContext(ref stackMark);
}
// For Task.ContinueWith() and Future.ContinueWith()
internal Task(Action<object> action, object state, Task parent, CancellationToken cancellationToken,
TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler, ref StackCrawlMark stackMark)
: this((object)action, state, parent, cancellationToken, creationOptions, internalOptions, scheduler)
{
PossiblyCaptureContext(ref stackMark);
}
/// <summary>
/// An internal constructor used by the factory methods on task and its descendent(s).
/// This variant does not capture the ExecutionContext; it is up to the caller to do that.
/// </summary>
/// <param name="action">An action to execute.</param>
/// <param name="state">Optional state to pass to the action.</param>
/// <param name="parent">Parent of Task.</param>
/// <param name="cancellationToken">A CancellationToken for the task.</param>
/// <param name="scheduler">A task scheduler under which the task will run.</param>
/// <param name="creationOptions">Options to control its execution.</param>
/// <param name="internalOptions">Internal options to control its execution</param>
internal Task(object action, object state, Task parent, CancellationToken cancellationToken,
TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
Contract.Assert(action is Action || action is Action<object>);
// This is readonly, and so must be set in the constructor
// Keep a link to your parent if: (A) You are attached, or (B) you are self-replicating.
// TODO: the check in the second line seems unnecessary - we already explicitly wait for replicating tasks
if (((creationOptions & TaskCreationOptions.AttachedToParent) != 0) ||
((internalOptions & InternalTaskOptions.SelfReplicating) != 0)
)
{
m_parent = parent;
}
TaskConstructorCore(action, state, cancellationToken, creationOptions, internalOptions, scheduler);
}
/// <summary>
/// Common logic used by the following internal ctors:
/// Task()
/// Task(object action, object state, Task parent, TaskCreationOptions options, TaskScheduler taskScheduler)
///
/// ASSUMES THAT m_creatingTask IS ALREADY SET.
///
/// </summary>
/// <param name="action">Action for task to execute.</param>
/// <param name="state">Object to which to pass to action (may be null)</param>
/// <param name="scheduler">Task scheduler on which to run thread (only used by continuation tasks).</param>
/// <param name="cancellationToken">A CancellationToken for the Task.</param>
/// <param name="creationOptions">Options to customize behavior of Task.</param>
/// <param name="internalOptions">Internal options to customize behavior of Task.</param>
internal void TaskConstructorCore(object action, object state, CancellationToken cancellationToken,
TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
{
m_action = action;
m_stateObject = state;
m_taskScheduler = scheduler;
// Check for validity of options
if ((creationOptions &
~(TaskCreationOptions.AttachedToParent |
TaskCreationOptions.LongRunning |
TaskCreationOptions.PreferFairness)) != 0)
{
throw new ArgumentOutOfRangeException("creationOptions");
}
// Check the validity of internalOptions
int illegalInternalOptions =
(int)(internalOptions &
~(InternalTaskOptions.SelfReplicating |
InternalTaskOptions.ChildReplica |
InternalTaskOptions.PromiseTask |
InternalTaskOptions.ContinuationTask |
InternalTaskOptions.QueuedByRuntime));
Contract.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options");
// Throw exception if the user specifies both LongRunning and SelfReplicating
if (((creationOptions & TaskCreationOptions.LongRunning) != 0) &&
((internalOptions & InternalTaskOptions.SelfReplicating) != 0))
{
throw new InvalidOperationException(Strings.Task_ctor_LRandSR);
}
// Assign options to m_stateAndOptionsFlag.
Contract.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags");
Contract.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits");
m_stateFlags = (int)creationOptions | (int)internalOptions;
// For continuation tasks or TaskCompletionSource.Tasks, begin life in WaitingForActivation state
// rather than Created state.
if ((m_action == null) ||
((internalOptions & InternalTaskOptions.ContinuationTask) != 0))
{
m_stateFlags |= TASK_STATE_WAITINGFORACTIVATION;
}
// Now is the time to add the new task to the children list
// of the creating task if the options call for it.
// We can safely call the creator task's AddNewChild() method to register it,
// because at this point we are already on its thread of execution.
if (m_parent != null && (creationOptions & TaskCreationOptions.AttachedToParent) != 0)
{
m_parent.AddNewChild();
}
// if we have a non-null cancellationToken, allocate the contingent properties to save it
// we need to do this as the very last thing in the construction path, because the CT registration could modify m_stateFlags
if (cancellationToken.CanBeCanceled)
{
Contract.Assert((internalOptions & (InternalTaskOptions.ChildReplica | InternalTaskOptions.SelfReplicating)) == 0,
"TaskConstructorCore: Did not expect to see cancellable token for replica/replicating task.");
LazyInitializer.EnsureInitialized<ContingentProperties>(ref m_contingentProperties, s_contingentPropertyCreator);
m_contingentProperties.m_cancellationToken = cancellationToken;
try
{
cancellationToken.ThrowIfSourceDisposed();
// If an unstarted task has a valid CancellationToken that gets signalled while the task is still not queued
// we need to proactively cancel it, because it may never execute to transition itself.
// The only way to accomplish this is to register a callback on the CT.
// We exclude Promise tasks from this, because TasckCompletionSource needs to fully control the inner tasks's lifetime (i.e. not allow external cancellations)
if ((internalOptions &
(InternalTaskOptions.QueuedByRuntime | InternalTaskOptions.PromiseTask)) == 0)
{
CancellationTokenRegistration ctr = cancellationToken.InternalRegisterWithoutEC(s_taskCancelCallback, this);
m_contingentProperties.m_cancellationRegistration = new Shared<CancellationTokenRegistration>(ctr);
}
}
catch
{
// If we have an exception related to our CancellationToken, then we need to subtract ourselves
// from our parent before throwing it.
if ((m_parent != null) && ((creationOptions & TaskCreationOptions.AttachedToParent) != 0))
m_parent.DisregardChild();
throw;
}
}
}
/// <summary>
/// Checks if we registered a CT callback during construction, and deregisters it.
/// This should be called when we know the registration isn't useful anymore. Specifically from Finish() if the task has completed
/// successfully or with an exception.
/// </summary>
internal void DeregisterCancellationCallback()
{
if (m_contingentProperties != null &&
m_contingentProperties.m_cancellationRegistration != null)
{
// Harden against ODEs thrown from disposing of the CTR.
// Since the task has already been put into a final state by the time this
// is called, all we can do here is suppress the exception.
try
{
m_contingentProperties.m_cancellationRegistration.Value.Dispose();
}
catch (ObjectDisposedException) { }
m_contingentProperties.m_cancellationRegistration = null;
}
}
// Static delegate to be used as a cancellation callback on unstarted tasks that have a valid cancellation token.
// This is necessary to transition them into canceled state if their cancellation token is signalled while they are still not queued
internal static Action<Object> s_taskCancelCallback = new Action<Object>(TaskCancelCallback);
private static void TaskCancelCallback(Object o)
{
Task t = (Task)o;
t.InternalCancel(false);
}
// Debugger support
private string DebuggerDisplayMethodDescription
{
get
{
Delegate d = (Delegate)m_action;
return d != null ? d.Method.ToString() : "{null}";
}
}
/// <summary>
/// Captures the ExecutionContext so long as flow isn't suppressed.
/// </summary>
/// <param name="stackMark">A stack crawl mark pointing to the frame of the caller.</param>
internal void PossiblyCaptureContext(ref StackCrawlMark stackMark)
{
// In the legacy .NET 3.5 build, we don't have the optimized overload of Capture()
// available, so we call the parameterless overload.
//#if PFX_LEGACY_3_5
m_capturedContext = ExecutionContextLightup.Instance.Capture();
//#else
// m_capturedContext = ExecutionContext.Capture(
// ref stackMark,
// ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
//#endif
}
// Internal property to process TaskCreationOptions access and mutation.
internal TaskCreationOptions Options
{
get
{
Contract.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get");
return (TaskCreationOptions)(m_stateFlags & OptionsMask);
}
}
// Atomically OR-in newBits to m_stateFlags, while making sure that
// no illegalBits are set. Returns true on success, false on failure.
internal bool AtomicStateUpdate(int newBits, int illegalBits)
{
int oldFlags = 0;
return AtomicStateUpdate(newBits, illegalBits, ref oldFlags);
}
internal bool AtomicStateUpdate(int newBits, int illegalBits, ref int oldFlags)
{
SpinWait sw = new SpinWait();
do
{
oldFlags = m_stateFlags;
if ((oldFlags & illegalBits) != 0) return false;
if (Interlocked.CompareExchange(ref m_stateFlags, oldFlags | newBits, oldFlags) == oldFlags)
{
return true;
}
sw.SpinOnce();
} while (true);
}
// Atomically mark a Task as started while making sure that it is not canceled.
internal bool MarkStarted()
{
return AtomicStateUpdate(TASK_STATE_STARTED, TASK_STATE_CANCELED | TASK_STATE_STARTED);
}
/// <summary>
/// Internal function that will be called by a new child task to add itself to
/// the children list of the parent (this).
///
/// Since a child task can only be created from the thread executing the action delegate
/// of this task, reentrancy is neither required nor supported. This should not be called from
/// anywhere other than the task construction/initialization codepaths.
/// </summary>
internal void AddNewChild()
{
Contract.Assert(Task.InternalCurrent == this || this.IsSelfReplicatingRoot, "Task.AddNewChild(): Called from an external context");
LazyInitializer.EnsureInitialized<ContingentProperties>(ref m_contingentProperties, s_contingentPropertyCreator);
if (m_contingentProperties.m_completionCountdown == 1 && !IsSelfReplicatingRoot)
{
// A count of 1 indicates so far there was only the parent, and this is the first child task
// Single kid => no fuss about who else is accessing the count. Let's save ourselves 100 cycles
// We exclude self replicating root tasks from this optimization, because further child creation can take place on
// other cores and with bad enough timing this write may not be visible to them.
m_contingentProperties.m_completionCountdown++;
}
else
{
// otherwise do it safely
Interlocked.Increment(ref m_contingentProperties.m_completionCountdown);
}
}
// This is called in the case where a new child is added, but then encounters a CancellationToken-related exception.
// We need to subtract that child from m_completionCountdown, or the parent will never complete.
internal void DisregardChild()
{
Contract.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context");
Contract.Assert((m_contingentProperties != null) && (m_contingentProperties.m_completionCountdown >= 2), "Task.DisregardChild(): Expected parent count to be >= 2");
Interlocked.Decrement(ref m_contingentProperties.m_completionCountdown);
}
/// <summary>
/// Starts the <see cref="Task"/>, scheduling it for execution to the current <see
/// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>.
/// </summary>
/// <remarks>
/// A task may only be started and run only once. Any attempts to schedule a task a second time
/// will result in an exception.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// The <see cref="Task"/> is not in a valid state to be started. It may have already been started,
/// executed, or canceled, or it may have been created in a manner that doesn't support direct
/// scheduling.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="Task"/> instance has been disposed.
/// </exception>
public void Start()
{
Start(TaskScheduler.Current);
}
/// <summary>
/// Starts the <see cref="Task"/>, scheduling it for execution to the specified <see
/// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>.
/// </summary>
/// <remarks>
/// A task may only be started and run only once. Any attempts to schedule a task a second time will
/// result in an exception.
/// </remarks>
/// <param name="scheduler">
/// The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> with which to associate
/// and execute this task.
/// </param>
/// <exception cref="ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The <see cref="Task"/> is not in a valid state to be started. It may have already been started,
/// executed, or canceled, or it may have been created in a manner that doesn't support direct
/// scheduling.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="Task"/> instance has been disposed.
/// </exception>
public void Start(TaskScheduler scheduler)
{
// Throw an exception if the task has previously been disposed.
//ThrowIfDisposed();
// Need to check this before (m_action == null) because completed tasks will
// set m_action to null. We would want to know if this is the reason that m_action == null.
if (IsCompleted)
{
throw new InvalidOperationException(Strings.Task_Start_TaskCompleted);
}
if (m_action == null)
{
throw new InvalidOperationException(Strings.Task_Start_NullAction);
}
if (scheduler == null)
{
throw new ArgumentNullException("scheduler");
}
if ((Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) != 0)
{
throw new InvalidOperationException(Strings.Task_Start_ContinuationTask);
}
// Make sure that Task only gets started once. Or else throw an exception.
if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) != null)
{
throw new InvalidOperationException(Strings.Task_Start_AlreadyStarted);
}
ScheduleAndStart(true);
}
/// <summary>
/// Runs the <see cref="Task"/> synchronously on the current <see
/// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>.
/// </summary>
/// <remarks>
/// <para>
/// A task may only be started and run only once. Any attempts to schedule a task a second time will
/// result in an exception.
/// </para>
/// <para>
/// Tasks executed with <see cref="RunSynchronously()"/> will be associated with the current <see
/// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>.
/// </para>
/// <para>
/// If the target scheduler does not support running this Task on the current thread, the Task will
/// be scheduled for execution on the scheduler, and the current thread will block until the
/// Task has completed execution.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// The <see cref="Task"/> is not in a valid state to be started. It may have already been started,
/// executed, or canceled, or it may have been created in a manner that doesn't support direct
/// scheduling.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="Task"/> instance has been disposed.
/// </exception>
public void RunSynchronously()
{
InternalRunSynchronously(TaskScheduler.Current);
}
/// <summary>
/// Runs the <see cref="Task"/> synchronously on the <see
/// cref="System.Threading.Tasks.TaskScheduler">scheduler</see> provided.
/// </summary>
/// <remarks>
/// <para>
/// A task may only be started and run only once. Any attempts to schedule a task a second time will
/// result in an exception.
/// </para>
/// <para>
/// If the target scheduler does not support running this Task on the current thread, the Task will
/// be scheduled for execution on the scheduler, and the current thread will block until the
/// Task has completed execution.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// The <see cref="Task"/> is not in a valid state to be started. It may have already been started,
/// executed, or canceled, or it may have been created in a manner that doesn't support direct
/// scheduling.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="Task"/> instance has been disposed.
/// </exception>
/// <exception cref="ArgumentNullException">The <paramref name="scheduler"/> parameter
/// is null.</exception>
/// <param name="scheduler">The scheduler on which to attempt to run this task inline.</param>
public void RunSynchronously(TaskScheduler scheduler)
{
if (scheduler == null)
{
throw new ArgumentNullException("scheduler");
}
InternalRunSynchronously(scheduler);
}
//
// Internal version of RunSynchronously that allows a taskScheduler argument.
//
// // [SecuritySafeCritical] // Needed for QueueTask
internal void InternalRunSynchronously(TaskScheduler scheduler)
{
Contract.Assert(scheduler != null, "Task.InternalRunSynchronously(): null TaskScheduler");
//ThrowIfDisposed();
// Can't call this method on a continuation task
if ((Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) != 0)
{
throw new InvalidOperationException(Strings.Task_RunSynchronously_Continuation);
}
// Can't call this method on a task that has already completed
if (IsCompleted)
{
throw new InvalidOperationException(Strings.Task_RunSynchronously_TaskCompleted);
}
// Can't call this method on a promise-style task
if (m_action == null)
{
throw new InvalidOperationException(Strings.Task_RunSynchronously_Promise);
}
// Make sure that Task only gets started once. Or else throw an exception.
if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) != null)
{
throw new InvalidOperationException(Strings.Task_RunSynchronously_AlreadyStarted);
}
// execute only if we win the race against concurrent cancel attempts.
// otherwise throw an exception, because we've been canceled.
if (MarkStarted())
{
bool taskQueued = false;
try
{
// We wrap TryRunInline() in a try/catch block and move an excepted task to Faulted here,
// but not in Wait()/WaitAll()/FastWaitAll(). Here, we know for sure that the
// task will not be subsequently scheduled (assuming that the scheduler adheres
// to the guideline that an exception implies that no state change took place),
// so it is safe to catch the exception and move the task to a final state. The
// same cannot be said for Wait()/WaitAll()/FastWaitAll().
if (!scheduler.TryRunInline(this, false))
{
scheduler.QueueTask(this);
taskQueued = true; // only mark this after successfully queuing the task.
}
// A successful TryRunInline doesn't guarantee completion, as there may be unfinished children
// Also if we queued the task above, we need to wait.
if (!IsCompleted)
{
CompletedEvent.Wait();
}
}
catch (Exception e)
{
// we 1) either received an unexpected exception originating from a custom scheduler, which needs to be wrapped in a TSE and thrown
// 2) or a a ThreadAbortException, which we need to skip here, because it would already have been handled in Task.Execute
if (!taskQueued && !(ThreadingServices.IsThreadAbort(e)))
{
// We had a problem with TryRunInline() or QueueTask().
// Record the exception, marking ourselves as Completed/Faulted.
TaskSchedulerException tse = new TaskSchedulerException(e);
AddException(tse);
Finish(false);
// Mark ourselves as "handled" to avoid crashing the finalizer thread if the caller neglects to
// call Wait() on this task.
// m_contingentProperties.m_exceptionHolder *should* already exist after AddException()
Contract.Assert((m_contingentProperties != null) && (m_contingentProperties.m_exceptionsHolder != null),
"Task.InternalRunSynchronously(): Expected m_contingentProperties.m_exceptionsHolder to exist");
m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);
// And re-throw.
throw tse;
}
else
{
// We had a problem with CompletedEvent.Wait(). Just re-throw.
throw;
}
}
}
else
{
Contract.Assert((m_stateFlags & TASK_STATE_CANCELED) != 0, "Task.RunSynchronously: expected TASK_STATE_CANCELED to be set");
// Can't call this method on canceled task.
throw new InvalidOperationException(Strings.Task_RunSynchronously_TaskCompleted);
}
}
////
//// Helper methods for Factory StartNew methods.
////
// Implicitly converts action to object and handles the meat of the StartNew() logic.
internal static Task InternalStartNew(
Task creatingTask, object action, object state, CancellationToken cancellationToken, TaskScheduler scheduler,
TaskCreationOptions options, InternalTaskOptions internalOptions, ref StackCrawlMark stackMark)
{
// Validate arguments.
if (scheduler == null)
{
throw new ArgumentNullException("scheduler");
}
// Create and schedule the task. This throws an InvalidOperationException if already shut down.
// Here we add the InternalTaskOptions.QueuedByRuntime to the internalOptions, so that TaskConstructorCore can skip the cancellation token registration
Task t = new Task(action, state, creatingTask, cancellationToken, options, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler);
t.PossiblyCaptureContext(ref stackMark);
t.ScheduleAndStart(false);
return t;
}
/////////////
// properties
/// <summary>
/// Gets a unique ID for this <see cref="Task">Task</see> instance.
/// </summary>
/// <remarks>
/// Task IDs are assigned on-demand and do not necessarily represent the order in the which Task
/// instances were created.
/// </remarks>
public int Id
{
get
{
if (m_taskId == 0)
{
int newId = 0;
// We need to repeat if Interlocked.Increment wraps around and returns 0.
// Otherwise next time this task's Id is queried it will get a new value
do
{
newId = Interlocked.Increment(ref s_taskIdCounter);
}
while (newId == 0);
Interlocked.CompareExchange(ref m_taskId, newId, 0);
}
return m_taskId;
}
}
/// <summary>
/// Returns the unique ID of the currently executing <see cref="Task">Task</see>.
/// </summary>
public static int? CurrentId
{
get
{
Task currentTask = InternalCurrent;
if (currentTask != null)
return currentTask.Id;
else
return null;
}
}
/// <summary>
/// Gets the <see cref="Task">Task</see> instance currently executing, or
/// null if none exists.
/// </summary>
internal static Task InternalCurrent
{
get { return ThreadLocals.s_currentTask.Value; }
}
/// <summary>
/// Gets the <see cref="T:System.AggregateException">Exception</see> that caused the <see
/// cref="Task">Task</see> to end prematurely. If the <see
/// cref="Task">Task</see> completed successfully or has not yet thrown any
/// exceptions, this will return null.
/// </summary>
/// <remarks>
/// Tasks that throw unhandled exceptions store the resulting exception and propagate it wrapped in a
/// <see cref="System.AggregateException"/> in calls to <see cref="Wait()">Wait</see>
/// or in accesses to the <see cref="Exception"/> property. Any exceptions not observed by the time
/// the Task instance is garbage collected will be propagated on the finalizer thread.
/// </remarks>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task">Task</see>
/// has been disposed.
/// </exception>
public AggregateException Exception
{
get
{
AggregateException e = null;
// If you're faulted, retrieve the exception(s)
if (IsFaulted) e = GetExceptions(false);
// Only return an exception in faulted state (skip manufactured exceptions)
// A "benevolent" race condition makes it possible to return null when IsFaulted is
// true (i.e., if IsFaulted is set just after the check to IsFaulted above).
Contract.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted");
return e;
}
}
/// <summary>
/// Gets the <see cref="T:System.Threading.Tasks.TaskStatus">TaskStatus</see> of this Task.
/// </summary>
public TaskStatus Status
{
get
{
TaskStatus rval;
// get a cached copy of the state flags. This should help us
// to get a consistent view of the flags if they are changing during the
// execution of this method.
int sf = m_stateFlags;
if ((sf & TASK_STATE_FAULTED) != 0) rval = TaskStatus.Faulted;
else if ((sf & TASK_STATE_CANCELED) != 0) rval = TaskStatus.Canceled;
else if ((sf & TASK_STATE_RAN_TO_COMPLETION) != 0) rval = TaskStatus.RanToCompletion;
else if ((sf & TASK_STATE_WAITING_ON_CHILDREN) != 0) rval = TaskStatus.WaitingForChildrenToComplete;
else if ((sf & TASK_STATE_DELEGATE_INVOKED) != 0) rval = TaskStatus.Running;
else if ((sf & TASK_STATE_STARTED) != 0) rval = TaskStatus.WaitingToRun;
else if ((sf & TASK_STATE_WAITINGFORACTIVATION) != 0) rval = TaskStatus.WaitingForActivation;
else rval = TaskStatus.Created;
return rval;
}
}
/// <summary>
/// Gets whether this <see cref="Task">Task</see> instance has completed
/// execution due to being canceled.
/// </summary>
/// <remarks>
/// A <see cref="Task">Task</see> will complete in Canceled state either if its <see cref="CancellationToken">CancellationToken</see>
/// was marked for cancellation before the task started executing, or if the task acknowledged the cancellation request on
/// its already signaled CancellationToken by throwing an
/// <see cref="System.OperationCanceledException">OperationCanceledException2</see> that bears the same
/// <see cref="System.Threading.CancellationToken">CancellationToken</see>.
/// </remarks>
public bool IsCanceled
{
get
{
// Return true if canceled bit is set and faulted bit is not set
return (m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_FAULTED)) == TASK_STATE_CANCELED;
}
}
/// <summary>
/// Returns true if this task has a cancellation token and it was signaled.
/// To be used internally in execute entry codepaths.
/// </summary>
internal bool IsCancellationRequested
{
get
{
// check both the internal cancellation request flag and the CancellationToken attached to this task
return ((m_contingentProperties != null) && (m_contingentProperties.m_internalCancellationRequested == CANCELLATION_REQUESTED)) ||
CancellationToken.IsCancellationRequested;
}
}
// Static delegate used for creating a ContingentProperties object from LazyInitializer.
internal static Func<ContingentProperties> s_contingentPropertyCreator = new Func<ContingentProperties>(ContingentPropertyCreator);
private static ContingentProperties ContingentPropertyCreator()
{
return new ContingentProperties();
}
/// <summary>
/// This internal property provides access to the CancellationToken that was set on the task
/// when it was constructed.
/// </summary>
internal CancellationToken CancellationToken
{
get
{
return (m_contingentProperties == null) ? CancellationToken.None :
m_contingentProperties.m_cancellationToken;
}
}
/// <summary>
/// Gets whether this <see cref="Task"/> threw an OperationCanceledException2 while its CancellationToken was signaled.
/// </summary>
internal bool IsCancellationAcknowledged
{
get { return (m_stateFlags & TASK_STATE_CANCELLATIONACKNOWLEDGED) != 0; }
}
/// <summary>
/// Gets whether this <see cref="Task">Task</see> has completed.
/// </summary>
/// <remarks>
/// <see cref="IsCompleted"/> will return true when the Task is in one of the three
/// final states: <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
/// </remarks>
public bool IsCompleted
{
get
{
return ((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_FAULTED | TASK_STATE_RAN_TO_COMPLETION)) != 0);
}
}
// For use in InternalWait -- marginally faster than (Task.Status == TaskStatus.RanToCompletion)
internal bool CompletedSuccessfully
{
get
{
int completedMask = TASK_STATE_CANCELED | TASK_STATE_FAULTED | TASK_STATE_RAN_TO_COMPLETION;
return (m_stateFlags & completedMask) == TASK_STATE_RAN_TO_COMPLETION;
}
}
/// <summary>
/// Checks whether this task has been disposed.
/// </summary>
internal bool IsDisposed
{
get { return (m_stateFlags & TASK_STATE_DISPOSED) != 0; }
}
/// <summary>
/// Throws an exception if the task has been disposed, and hence can no longer be accessed.
/// </summary>
/// <exception cref="T:System.ObjectDisposedException">The task has been disposed.</exception>
internal void ThrowIfDisposed()
{
if (IsDisposed)
{
throw new ObjectDisposedException(null, Strings.Task_ThrowIfDisposed);
}
}
/// <summary>
/// Gets the <see cref="T:System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used
/// to create this task.
/// </summary>
public TaskCreationOptions CreationOptions
{
get { return Options & (TaskCreationOptions)(~InternalTaskOptions.InternalOptionsMask); }
}
/// <summary>
/// Gets a <see cref="T:System.Threading.WaitHandle"/> that can be used to wait for the task to
/// complete.
/// </summary>
/// <remarks>
/// Using the wait functionality provided by <see cref="Wait()"/>
/// should be preferred over using <see cref="IAsyncResult.AsyncWaitHandle"/> for similar
/// functionality.
/// </remarks>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
WaitHandle IAsyncResult.AsyncWaitHandle
{
// Although a slim event is used internally to avoid kernel resource allocation, this function
// forces allocation of a true WaitHandle when called.
get
{
ThrowIfDisposed();
return CompletedEvent.WaitHandle;
}
}
// Overridden by Task<TResult> to return m_futureState
internal virtual object InternalAsyncState
{
get { return m_stateObject; }
}
/// <summary>
/// Gets the state object supplied when the <see cref="Task">Task</see> was created,
/// or null if none was supplied.
/// </summary>
public object AsyncState
{
get { return InternalAsyncState; }
}
/// <summary>
/// Gets an indication of whether the asynchronous operation completed synchronously.
/// </summary>
/// <value>true if the asynchronous operation completed synchronously; otherwise, false.</value>
bool IAsyncResult.CompletedSynchronously
{
get
{
// @TODO: do we want to faithfully return 'true' if the task ran on the same
// thread which created it? Probably not, but we need to think about it.
return false;
}
}
// @TODO: can this be retrieved from TLS instead of storing it?
/// <summary>
/// Provides access to the TaskScheduler responsible for executing this Task.
/// </summary>
internal TaskScheduler ExecutingTaskScheduler
{
get { return m_taskScheduler; }
}
/// <summary>
/// Provides access to factory methods for creating <see cref="Task"/> and <see cref="Task{TResult}"/> instances.
/// </summary>
/// <remarks>
/// The factory returned from <see cref="Factory"/> is a default instance
/// of <see cref="System.Threading.Tasks.TaskFactory"/>, as would result from using
/// the default constructor on TaskFactory.
/// </remarks>
public static TaskFactory Factory { get { return s_factory; } }
/// <summary>
/// Provides an event that can be used to wait for completion.
/// Only called by Wait*(), which means that we really do need to instantiate a completion event.
/// </summary>
internal ManualResetEventSlim CompletedEvent
{
get
{
if (m_completionEvent == null)
{
bool wasCompleted = IsCompleted;
ManualResetEventSlim newMre = new ManualResetEventSlim(wasCompleted);
if (Interlocked.CompareExchange(ref m_completionEvent, newMre, null) != null)
{
// We lost the race, so we will just close the event right away.
newMre.Dispose();
}
else if (!wasCompleted && IsCompleted)
{
// We published the event as unset, but the task has subsequently completed.
// Set the event's state properly so that callers don't deadlock.
newMre.Set();
}
}
return m_completionEvent;
}
}
/// <summary>
/// Sets the internal completion event.
/// </summary>
private void SetCompleted()
{
ManualResetEventSlim mres = m_completionEvent;
if (mres != null)
{
mres.Set();
}
}
/// <summary>
/// Determines whether this is the root task of a self replicating group.
/// </summary>
internal bool IsSelfReplicatingRoot
{
get
{
return ((Options & (TaskCreationOptions)InternalTaskOptions.SelfReplicating) != 0) &&
((Options & (TaskCreationOptions)InternalTaskOptions.ChildReplica) == 0);
}
}
/// <summary>
/// Determines whether the task is a replica itself.
/// </summary>
internal bool IsChildReplica
{
get { return (Options & (TaskCreationOptions)InternalTaskOptions.ChildReplica) != 0; }
}
internal int ActiveChildCount
{
get { return m_contingentProperties != null ? m_contingentProperties.m_completionCountdown - 1 : 0; }
}
/// <summary>
/// The property formerly known as IsFaulted.
/// </summary>
internal bool ExceptionRecorded
{
get { return (m_contingentProperties != null) && (m_contingentProperties.m_exceptionsHolder != null); }
}
/// <summary>
/// Gets whether the <see cref="Task"/> completed due to an unhandled exception.
/// </summary>
/// <remarks>
/// If <see cref="IsFaulted"/> is true, the Task's <see cref="Status"/> will be equal to
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">TaskStatus.Faulted</see>, and its
/// <see cref="Exception"/> property will be non-null.
/// </remarks>
public bool IsFaulted
{
get
{
// Faulted is "king" -- if that bit is present (regardless of other bits), we are faulted.
return ((m_stateFlags & TASK_STATE_FAULTED) != 0);
}
}
#if DEBUG
/// <summary>
/// Retrieves an identifier for the task.
/// </summary>
internal int InternalId
{
get { return GetHashCode(); }
}
#endif
/////////////
// methods
/// <summary>
/// Disposes the <see cref="Task"/>, releasing all of its unmanaged resources.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="Task"/>, this method is not thread-safe.
/// Also, <see cref="Dispose()"/> may only be called on a <see cref="Task"/> that is in one of
/// the final states: <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
/// </remarks>
/// <exception cref="T:System.InvalidOperationException">
/// The exception that is thrown if the <see cref="Task"/> is not in
/// one of the final states: <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
/// </exception>
internal void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the <see cref="Task"/>, releasing all of its unmanaged resources.
/// </summary>
/// <param name="disposing">
/// A Boolean value that indicates whether this method is being called due to a call to <see
/// cref="Dispose()"/>.
/// </param>
/// <remarks>
/// Unlike most of the members of <see cref="Task"/>, this method is not thread-safe.
/// </remarks>
internal virtual void Dispose(bool disposing)
{
if (disposing)
{
// Task must be completed to dispose
if (!IsCompleted)
{
throw new InvalidOperationException(Strings.Task_Dispose_NotCompleted);
}
var tmp = m_completionEvent; // make a copy to protect against racing Disposes.
// Dispose of the underlying completion event
if (tmp != null)
{
// In the unlikely event that our completion event is inflated but not yet signaled,
// go ahead and signal the event. If you dispose of an unsignaled MRES, then any waiters
// will deadlock; an ensuing Set() will not wake them up. In the event of an AppDomainUnload,
// there is no guarantee that anyone else is going to signal the event, and it does no harm to
// call Set() twice on m_completionEvent.
if (!tmp.IsSet) tmp.Set();
tmp.Dispose();
m_completionEvent = null;
}
}
// We OR the flags to indicate the object has been disposed. This is not
// thread-safe -- trying to dispose while a task is running can lead to corruption.
// Do this regardless of the value of "disposing".
m_stateFlags |= TASK_STATE_DISPOSED;
}
/////////////
// internal helpers
/// <summary>
/// Schedules the task for execution.
/// </summary>
/// <param name="needsProtection">If true, TASK_STATE_STARTED bit is turned on in
/// an atomic fashion, making sure that TASK_STATE_CANCELED does not get set
/// underneath us. If false, TASK_STATE_STARTED bit is OR-ed right in. This
/// allows us to streamline things a bit for StartNew(), where competing cancellations
/// are not a problem.</param>
internal void ScheduleAndStart(bool needsProtection)
{
Contract.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected");
Contract.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started");
// Set the TASK_STATE_STARTED bit
if (needsProtection)
{
if (!MarkStarted())
{
// A cancel has snuck in before we could get started. Quietly exit.
return;
}
}
else
{
m_stateFlags |= TASK_STATE_STARTED;
}
try
{
// Queue to the indicated scheduler.
m_taskScheduler.QueueTask(this);
}
catch (Exception e)
{
if (ThreadingServices.IsThreadAbort(e))
{
AddException(e);
FinishThreadAbortedTask(true, false);
}
else
{
// The scheduler had a problem queueing this task. Record the exception, leaving this task in
// a Faulted state.
TaskSchedulerException tse = new TaskSchedulerException(e);
AddException(tse);
Finish(false);
// Now we need to mark ourselves as "handled" to avoid crashing the finalizer thread if we are called from StartNew()
// or from the self replicating logic, because in both cases the exception is either propagated outside directly, or added
// to an enclosing parent. However we won't do this for continuation tasks, because in that case we internally eat the exception
// and therefore we need to make sure the user does later observe it explicitly or see it on the finalizer.
if ((Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0)
{
// m_contingentProperties.m_exceptionHolder *should* already exist after AddException()
Contract.Assert((m_contingentProperties != null) && (m_contingentProperties.m_exceptionsHolder != null),
"Task.InternalRunSynchronously(): Expected m_contingentProperties.m_exceptionsHolder to exist");
m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);
}
// re-throw the exception wrapped as a TaskSchedulerException.
throw tse;
}
}
}
/// <summary>
/// Adds an exception to the list of exceptions this task has thrown.
/// </summary>
/// <param name="exceptionObject">An object representing either an Exception or a collection of Exceptions.</param>
internal void AddException(object exceptionObject)
{
//
// WARNING: A great deal of care went into insuring that
// AddException() and GetExceptions() are never called
// simultaneously. See comment at start of GetExceptions().
//
// Lazily initialize the list, ensuring only one thread wins.
LazyInitializer.EnsureInitialized<ContingentProperties>(ref m_contingentProperties, s_contingentPropertyCreator);
if (m_contingentProperties.m_exceptionsHolder == null)
{
TaskExceptionHolder holder = new TaskExceptionHolder(this);
if (Interlocked.CompareExchange(
ref m_contingentProperties.m_exceptionsHolder, holder, null) != null)
{
// If we lost the race, suppress finalization.
holder.MarkAsHandled(false);
}
}
// Figure this out before your enter the lock.
Contract.Assert((exceptionObject is Exception) || (exceptionObject is IEnumerable<Exception>),
"Task.AddException: Expected an Exception or an IEnumerable<Exception>");
lock (m_contingentProperties)
{
m_contingentProperties.m_exceptionsHolder.Add(exceptionObject);
}
}
/// <summary>
/// Returns a list of exceptions by aggregating the holder's contents. Or null if
/// no exceptions have been thrown.
/// </summary>
/// <param name="includeTaskCanceledExceptions">Whether to include a TCE if cancelled.</param>
/// <returns>An aggregate exception, or null if no exceptions have been caught.</returns>
private AggregateException GetExceptions(bool includeTaskCanceledExceptions)
{
//
// WARNING: The Task/Task<TResult>/TaskCompletionSource classes
// have all been carefully crafted to insure that GetExceptions()
// is never called while AddException() is being called. There
// are locks taken on m_contingentProperties in several places:
//
// -- Task<TResult>.TrySetException(): The lock allows the
// task to be set to Faulted state, and all exceptions to
// be recorded, in one atomic action.
//
// -- Task.Exception_get(): The lock ensures that Task<TResult>.TrySetException()
// is allowed to complete its operation before Task.Exception_get()
// can access GetExceptions().
//
// -- Task.ThrowIfExceptional(): The lock insures that Wait() will
// not attempt to call GetExceptions() while Task<TResult>.TrySetException()
// is in the process of calling AddException().
//
// For "regular" tasks, we effectively keep AddException() and GetException()
// from being called concurrently by the way that the state flows. Until
// a Task is marked Faulted, Task.Exception_get() returns null. And
// a Task is not marked Faulted until it and all of its children have
// completed, which means that all exceptions have been recorded.
//
// It might be a lot easier to follow all of this if we just required
// that all calls to GetExceptions() and AddExceptions() were made
// under a lock on m_contingentProperties. But that would also
// increase our lock occupancy time and the frequency with which we
// would need to take the lock.
//
// If you add a call to GetExceptions() anywhere in the code,
// please continue to maintain the invariant that it can't be
// called when AddException() is being called.
//
// We'll lazily create a TCE if the task has been canceled.
Exception canceledException = null;
if (includeTaskCanceledExceptions && IsCanceled)
{
canceledException = new TaskCanceledException(this);
}
if (ExceptionRecorded)
{
// There are exceptions; get the aggregate and optionally add the canceled
// exception to the aggregate (if applicable).
Contract.Assert(m_contingentProperties != null); // ExceptionRecorded ==> m_contingentProperties != null
// No need to lock around this, as other logic prevents the consumption of exceptions
// before they have been completely processed.
return m_contingentProperties.m_exceptionsHolder.CreateExceptionObject(false, canceledException);
}
else if (canceledException != null)
{
// No exceptions, but there was a cancelation. Aggregate and return it.
return new AggregateException(canceledException);
}
return null;
}
/// <summary>
/// Throws an aggregate exception if the task contains exceptions.
/// </summary>
internal void ThrowIfExceptional(bool includeTaskCanceledExceptions)
{
Contract.Assert(IsCompleted, "ThrowIfExceptional(): Expected IsCompleted == true");
Exception exception = GetExceptions(includeTaskCanceledExceptions);
if (exception != null)
{
UpdateExceptionObservedStatus();
throw exception;
}
}
/// <summary>
/// Checks whether this is an attached task, and whether we are being called by the parent task.
/// And sets the TASK_STATE_EXCEPTIONOBSERVEDBYPARENT status flag based on that.
///
/// This is meant to be used internally when throwing an exception, and when WaitAll is gathering
/// exceptions for tasks it waited on. If this flag gets set, the implicit wait on children
/// will skip exceptions to prevent duplication.
///
/// This should only be called when this task has completed with an exception
///
/// </summary>
internal void UpdateExceptionObservedStatus()
{
if ((Options & TaskCreationOptions.AttachedToParent) != 0 &&
Task.InternalCurrent == m_parent)
{
m_stateFlags |= TASK_STATE_EXCEPTIONOBSERVEDBYPARENT;
}
}
/// <summary>
/// Checks whether the TASK_STATE_EXCEPTIONOBSERVEDBYPARENT status flag is set,
/// This will only be used by the implicit wait to prevent double throws
///
/// </summary>
internal bool IsExceptionObservedByParent
{
get
{
return (m_stateFlags & TASK_STATE_EXCEPTIONOBSERVEDBYPARENT) != 0;
}
}
/// <summary>
/// Checks whether the body was ever invoked. Used by task scheduler code to verify custom schedulers actually ran the task.
/// </summary>
internal bool IsDelegateInvoked
{
get
{
return (m_stateFlags & TASK_STATE_DELEGATE_INVOKED) != 0;
}
}
/// <summary>
/// Signals completion of this particular task.
///
/// The bUserDelegateExecuted parameter indicates whether this Finish() call comes following the
/// full execution of the user delegate.
///
/// If bUserDelegateExecuted is false, it mean user delegate wasn't invoked at all (either due to
/// a cancellation request, or because this task is a promise style Task). In this case, the steps
/// involving child tasks (i.e. WaitForChildren) will be skipped.
///
/// </summary>
internal void Finish(bool bUserDelegateExecuted)
{
if (!bUserDelegateExecuted)
{
// delegate didn't execute => no children. We can safely call the remaining finish stages
FinishStageTwo();
}
else
{
ContingentProperties properties = m_contingentProperties;
if (properties == null || // no contingent properties, no children. Safe to complete ourselves
(properties.m_completionCountdown == 1 && !IsSelfReplicatingRoot) ||
// Count of 1 => either all children finished, or there were none. Safe to complete ourselves
// without paying the price of an Interlocked.Decrement.
// However we need to exclude self replicating root tasks from this optimization, because
// they can have children joining in, or finishing even after the root task delegate is done.
Interlocked.Decrement(ref properties.m_completionCountdown) == 0) // Reaching this sub clause means there may be remaining active children,
// and we could be racing with one of them to call FinishStageTwo().
// So whoever does the final Interlocked.Dec is responsible to finish.
{
FinishStageTwo();
}
else
{
// Apparently some children still remain. It will be up to the last one to process the completion of this task on their own thread.
// We will now yield the thread back to ThreadPool. Mark our state appropriately before getting out.
// We have to use an atomic update for this and make sure not to overwrite a final state,
// because at this very moment the last child's thread may be concurrently completing us.
// Otherwise we risk overwriting the TASK_STATE_RAN_TO_COMPLETION, _CANCELED or _FAULTED bit which may have been set by that child task.
// Note that the concurrent update by the last child happening in FinishStageTwo could still wipe out the TASK_STATE_WAITING_ON_CHILDREN flag,
// but it is not critical to maintain, therefore we dont' need to intruduce a full atomic update into FinishStageTwo
AtomicStateUpdate(TASK_STATE_WAITING_ON_CHILDREN, TASK_STATE_FAULTED | TASK_STATE_CANCELED | TASK_STATE_RAN_TO_COMPLETION);
}
}
// Now is the time to prune exceptional children. We'll walk the list and removes the ones whose exceptions we might have observed after they threw.
// we use a local variable for exceptional children here because some other thread may be nulling out m_contingentProperties.m_exceptionalChildren
List<Task> exceptionalChildren = m_contingentProperties != null ? m_contingentProperties.m_exceptionalChildren : null;
if (exceptionalChildren != null)
{
lock (exceptionalChildren)
{
// RemoveAll is not available in S3 - we have to use our own implementation
//exceptionalChildren.RemoveAll(s_IsExceptionObservedByParentPredicate); // RemoveAll has better performance than doing it ourselves
List<Task> exceptionalChildrenNext = new List<Task>();
foreach (var t in exceptionalChildren)
{
if (!s_IsExceptionObservedByParentPredicate(t)) exceptionalChildrenNext.Add(t);
}
exceptionalChildren.Clear();
exceptionalChildren.AddRange(exceptionalChildrenNext);
}
}
}
// statically allocated delegate for the removeall expression in Finish()
private static Predicate<Task> s_IsExceptionObservedByParentPredicate = new Predicate<Task>((t) => { return t.IsExceptionObservedByParent; });
/// <summary>
/// FinishStageTwo is to be executed as soon as we known there are no more children to complete.
/// It can happen i) either on the thread that originally executed this task (if no children were spawned, or they all completed by the time this task's delegate quit)
/// ii) or on the thread that executed the last child.
/// </summary>
internal void FinishStageTwo()
{
AddExceptionsFromChildren();
// At this point, the task is done executing and waiting for its children,
// we can transition our task to a completion state.
int completionState;
if (ExceptionRecorded)
{
completionState = TASK_STATE_FAULTED;
}
else if (IsCancellationRequested && IsCancellationAcknowledged)
{
// We transition into the TASK_STATE_CANCELED final state if the task's CT was signalled for cancellation,
// and the user delegate acknowledged the cancellation request by throwing an OCE,
// and the task hasn't otherwise transitioned into faulted state. (TASK_STATE_FAULTED trumps TASK_STATE_CANCELED)
//
// If the task threw an OCE without cancellation being requestsed (while the CT not being in signaled state),
// then we regard it as a regular exception
completionState = TASK_STATE_CANCELED;
}
else
{
completionState = TASK_STATE_RAN_TO_COMPLETION;
}
// Use Interlocked.Exchange() to effect a memory fence, preventing
// any SetCompleted() (or later) instructions from sneak back before it.
Interlocked.Exchange(ref m_stateFlags, m_stateFlags | completionState);
// Set the completion event if it's been lazy allocated.
SetCompleted();
// if we made a cancellation registration, it's now unnecessary.
DeregisterCancellationCallback();
// ready to run continuations and notify parent.
FinishStageThree();
}
/// <summary>
/// Final stage of the task completion code path. Notifies the parent (if any) that another of its childre are done, and runs continuations.
/// This function is only separated out from FinishStageTwo because these two operations are also needed to be called from CancellationCleanupLogic()
/// </summary>
private void FinishStageThree()
{
// Notify parent if this was an attached task
if (m_parent != null
&& (((TaskCreationOptions)(m_stateFlags & OptionsMask)) & TaskCreationOptions.AttachedToParent) != 0)
{
m_parent.ProcessChildCompletion(this);
}
// Activate continuations (if any).
FinishContinuations();
// Need this to bound the memory usage on long/infinite continuation chains
m_action = null;
}
/// <summary>
/// This is called by children of this task when they are completed.
/// </summary>
internal void ProcessChildCompletion(Task childTask)
{
Contract.Assert(childTask.m_parent == this, "ProcessChildCompletion should only be called for a child of this task");
Contract.Assert(childTask.IsCompleted, "ProcessChildCompletion was called for an uncompleted task");
// if the child threw and we haven't observed it we need to save it for future reference
if (childTask.IsFaulted && !childTask.IsExceptionObservedByParent)
{
// Lazily initialize the child exception list
if (m_contingentProperties.m_exceptionalChildren == null)
{
Interlocked.CompareExchange(ref m_contingentProperties.m_exceptionalChildren, new List<Task>(), null);
}
// In rare situations involving AppDomainUnload, it's possible (though unlikely) for FinishStageTwo() to be called
// multiple times for the same task. In that case, AddExceptionsFromChildren() could be nulling m_exceptionalChildren
// out at the same time that we're processing it, resulting in a NullReferenceException here. We'll protect
// ourselves by caching m_exceptionChildren in a local variable.
List<Task> tmp = m_contingentProperties.m_exceptionalChildren;
if (tmp != null)
{
lock (tmp)
{
tmp.Add(childTask);
}
}
}
if (Interlocked.Decrement(ref m_contingentProperties.m_completionCountdown) == 0)
{
// This call came from the final child to complete, and apparently we have previously given up this task's right to complete itself.
// So we need to invoke the final finish stage.
FinishStageTwo();
}
}
/// <summary>
/// This is to be called just before the task does its final state transition.
/// It traverses the list of exceptional children, and appends their aggregate exceptions into this one's exception list
/// </summary>
internal void AddExceptionsFromChildren()
{
// In rare occurences during AppDomainUnload() processing, it is possible for this method to be called
// simultaneously on the same task from two different contexts. This can result in m_exceptionalChildren
// being nulled out while it is being processed, which could lead to a NullReferenceException. To
// protect ourselves, we'll cache m_exceptionalChildren in a local variable.
List<Task> tmp = (m_contingentProperties != null) ? m_contingentProperties.m_exceptionalChildren : null;
if (tmp != null)
{
// This lock is necessary because even though AddExceptionsFromChildren is last to execute, it may still
// be racing with the code segment at the bottom of Finish() that prunes the exceptional child array.
lock (tmp)
{
foreach (Task task in tmp)
{
// Ensure any exceptions thrown by children are added to the parent.
// In doing this, we are implicitly marking children as being "handled".
Contract.Assert(task.IsCompleted, "Expected all tasks in list to be completed");
if (task.IsFaulted && !task.IsExceptionObservedByParent)
{
TaskExceptionHolder exceptionHolder = task.m_contingentProperties.m_exceptionsHolder;
Contract.Assert(exceptionHolder != null);
// No locking necessary since child task is finished adding exceptions
// and concurrent CreateExceptionObject() calls do not constitute
// a concurrency hazard.
AddException(exceptionHolder.CreateExceptionObject(false, null));
}
}
}
// Reduce memory pressure by getting rid of the array
m_contingentProperties.m_exceptionalChildren = null;
}
}
/// <summary>
/// Special purpose Finish() entry point to be used when the task delegate throws a ThreadAbortedException
/// This makes a note in the state flags so that we avoid any costly synchronous operations in the finish codepath
/// such as inlined continuations
/// </summary>
/// <param name="bTAEAddedToExceptionHolder">
/// Indicates whether the ThreadAbortException was added to this task's exception holder.
/// This should always be true except for the case of non-root self replicating task copies.
/// </param>
/// <param name="delegateRan">Whether the delegate was executed.</param>
internal void FinishThreadAbortedTask(bool bTAEAddedToExceptionHolder, bool delegateRan)
{
Contract.Assert(!bTAEAddedToExceptionHolder || (m_contingentProperties != null && m_contingentProperties.m_exceptionsHolder != null),
"FinishThreadAbortedTask() called on a task whose exception holder wasn't initialized");
// this will only be false for non-root self replicating task copies, because all of their exceptions go to the root task.
if (bTAEAddedToExceptionHolder)
m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);
// If this method has already been called for this task, or if this task has already completed, then
// return before actually calling Finish().
if (!AtomicStateUpdate(TASK_STATE_THREAD_WAS_ABORTED,
TASK_STATE_THREAD_WAS_ABORTED | TASK_STATE_RAN_TO_COMPLETION | TASK_STATE_FAULTED | TASK_STATE_CANCELED))
{
return;
}
Finish(delegateRan);
}
/// <summary>
/// Executes the task. This method will only be called once, and handles bookeeping associated with
/// self-replicating tasks, in addition to performing necessary exception marshaling.
/// </summary>
/// <exception cref="T:System.ObjectDisposedException">The task has already been disposed.</exception>
private void Execute()
{
if (IsSelfReplicatingRoot)
{
ExecuteSelfReplicating(this);
}
else
{
try
{
InnerInvoke();
}
catch (Exception exn)
{
if (ThreadingServices.IsThreadAbort(exn))
{
// Don't record the TAE or call FinishThreadAbortedTask for a child replica task --
// it's already been done downstream.
if (!IsChildReplica)
{
// Record this exception in the task's exception list
HandleException(exn);
// This is a ThreadAbortException and it will be rethrown from this catch clause, causing us to
// skip the regular Finish codepath. In order not to leave the task unfinished, we now call
// FinishThreadAbortedTask here.
FinishThreadAbortedTask(true, true);
}
}
else
{
// Record this exception in the task's exception list
HandleException(exn);
}
}
}
}
// Allows (internal) deriving classes to support limited replication.
// (By default, replication is basically unlimited).
internal virtual bool ShouldReplicate()
{
return true;
}
// Allows (internal) deriving classes to instantiate the task replica as a Task super class of their choice
// (By default, we create a regular Task instance)
internal virtual Task CreateReplicaTask(Action<object> taskReplicaDelegate, Object stateObject, Task parentTask, TaskScheduler taskScheduler,
TaskCreationOptions creationOptionsForReplica, InternalTaskOptions internalOptionsForReplica)
{
return new Task(taskReplicaDelegate, stateObject, parentTask, CancellationToken.None,
creationOptionsForReplica, internalOptionsForReplica, parentTask.ExecutingTaskScheduler);
}
// Allows internal deriving classes to support replicas that exit prematurely and want to pass on state to the next replica
internal virtual Object SavedStateForNextReplica
{
get { return null; }
set { /*do nothing*/ }
}
// Allows internal deriving classes to support replicas that exit prematurely and want to pass on state to the next replica
internal virtual Object SavedStateFromPreviousReplica
{
get { return null; }
set { /*do nothing*/ }
}
// Allows internal deriving classes to support replicas that exit prematurely and want to hand over the child replica that they
// had queued, so that the replacement replica can work with that child task instead of queuing up yet another one
internal virtual Task HandedOverChildReplica
{
get { return null; }
set { /* do nothing*/ }
}
private static void ExecuteSelfReplicating(Task root)
{
TaskCreationOptions creationOptionsForReplicas = root.CreationOptions | TaskCreationOptions.AttachedToParent;
InternalTaskOptions internalOptionsForReplicas =
InternalTaskOptions.ChildReplica | // child replica flag disables self replication for the replicas themselves.
InternalTaskOptions.SelfReplicating | // we still want to identify this as part of a self replicating group
InternalTaskOptions.QueuedByRuntime; // we queue and cancel these tasks internally, so don't allow CT registration to take place
// Important Note: The child replicas we launch from here will be attached the root replica (by virtue of the root.CreateReplicaTask call)
// because we need the root task to receive all their exceptions, and to block until all of them return
// This variable is captured in a closure and shared among all replicas.
bool replicasAreQuitting = false;
// Set up a delegate that will form the body of the root and all recursively created replicas.
Action<object> taskReplicaDelegate = null;
taskReplicaDelegate = delegate
{
Task currentTask = Task.InternalCurrent;
// Check if a child task has been handed over by a prematurely quiting replica that we might be a replacement for.
Task childTask = currentTask.HandedOverChildReplica;
if (childTask == null)
{
// Apparently we are not a replacement task. This means we need to queue up a child task for replication to progress
// Down-counts a counter in the root task.
if (!root.ShouldReplicate()) return;
// If any of the replicas have quit, we will do so ourselves.
if (replicasAreQuitting)
{
return;
}
// Propagate a copy of the context from the root task. It may be null if flow was suppressed.
ExecutionContextLightup creatorContext = root.m_capturedContext;
childTask = root.CreateReplicaTask(taskReplicaDelegate, root.m_stateObject, root, root.ExecutingTaskScheduler,
creationOptionsForReplicas, internalOptionsForReplicas);
childTask.m_capturedContext = (creatorContext == null ? null : creatorContext.CreateCopy());
childTask.ScheduleAndStart(false);
}
// Finally invoke the meat of the task.
// Note that we are directly calling root.InnerInvoke() even though we are currently be in the action delegate of a child replica
// This is because the actual work was passed down in that delegate, and the action delegate of the child replica simply contains this
// replication control logic.
try
{
// passing in currentTask only so that the parallel debugger can find it
root.InnerInvokeWithArg(currentTask);
}
catch (Exception exn)
{
// Record this exception in the root task's exception list
root.HandleException(exn);
if (ThreadingServices.IsThreadAbort(exn))
{
// If this is a ThreadAbortException it will escape this catch clause, causing us to skip the regular Finish codepath
// In order not to leave the task unfinished, we now call FinishThreadAbortedTask here
currentTask.FinishThreadAbortedTask(false, true);
}
}
Object savedState = currentTask.SavedStateForNextReplica;
// check for premature exit
if (savedState != null)
{
// the replica decided to exit early
// we need to queue up a replacement, attach the saved state, and yield the thread right away
Task replacementReplica = root.CreateReplicaTask(taskReplicaDelegate, root.m_stateObject, root, root.ExecutingTaskScheduler,
creationOptionsForReplicas, internalOptionsForReplicas);
// Propagate a copy of the context from the root task to the replacement task
ExecutionContextLightup creatorContext = root.m_capturedContext;
replacementReplica.m_capturedContext = (creatorContext == null ? null : creatorContext.CreateCopy());
replacementReplica.HandedOverChildReplica = childTask;
replacementReplica.SavedStateFromPreviousReplica = savedState;
replacementReplica.ScheduleAndStart(false);
}
else
{
// The replica finished normally, which means it can't find more work to grab.
// Time to mark replicas quitting
replicasAreQuitting = true;
// InternalCancel() could conceivably throw in the underlying scheduler's TryDequeue() method.
// If it does, then make sure that we record it.
try
{
childTask.InternalCancel(true);
}
catch (Exception e)
{
// Apparently TryDequeue threw an exception. Before propagating that exception, InternalCancel should have
// attempted an atomic state transition and a call to CancellationCleanupLogic() on this task. So we know
// the task was properly cleaned up if it was possible.
//
// Now all we need to do is to Record the exception in the root task.
root.HandleException(e);
}
// No specific action needed if the child could not be canceled
// because we attached it to the root task, which should therefore be receiving any exceptions from the child,
// and root.wait will not return before this child finishes anyway.
}
};
//
// Now we execute as the root task
//
taskReplicaDelegate(null);
}
/// <summary>
/// IThreadPoolWorkItem override, which is the entry function for this task when the TP scheduler decides to run it.
///
/// </summary>
// [SecurityCritical]
void IThreadPoolWorkItem.ExecuteWorkItem()
{
ExecuteEntry(false);
}
///// <summary>
///// The ThreadPool calls this if a ThreadAbortException is thrown while trying to execute this workitem. This may occur
///// before Task would otherwise be able to observe it.
///// </summary>
//[SecurityCritical]
//void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
//{
// // If the task has marked itself as Completed, then it either a) already observed this exception (so we shouldn't handle it here)
// // or b) completed before the exception ocurred (in which case it shouldn't count against this Task).
// if (!IsCompleted)
// {
// HandleException(tae);
// FinishThreadAbortedTask(true, false);
// }
//}
/// <summary>
/// Outermost entry function to execute this task. Handles all aspects of executing a task on the caller thread.
/// Currently this is called by IThreadPoolWorkItem.ExecuteWorkItem(), and TaskManager.TryExecuteInline.
///
/// </summary>
/// <param name="bPreventDoubleExecution"> Performs atomic updates to prevent double execution. Should only be set to true
/// in codepaths servicing user provided TaskSchedulers. The ConcRT or ThreadPool schedulers don't need this. </param>
// // [SecuritySafeCritical]
internal bool ExecuteEntry(bool bPreventDoubleExecution)
{
if (bPreventDoubleExecution || ((Options & (TaskCreationOptions)InternalTaskOptions.SelfReplicating) != 0))
{
int previousState = 0;
// Do atomic state transition from queued to invoked. If we observe a task that's already invoked,
// we will return false so that TaskScheduler.ExecuteTask can throw an exception back to the custom scheduler.
// However we don't want this exception to be throw if the task was already canceled, because it's a
// legitimate scenario for custom schedulers to dequeue a task and mark it as canceled (example: throttling scheduler)
if (!AtomicStateUpdate(TASK_STATE_DELEGATE_INVOKED, TASK_STATE_DELEGATE_INVOKED, ref previousState)
&& (previousState & TASK_STATE_CANCELED) == 0)
{
// This task has already been invoked. Don't invoke it again.
return false;
}
}
else
{
// Remember that we started running the task delegate.
m_stateFlags |= TASK_STATE_DELEGATE_INVOKED;
}
if (!IsCancellationRequested && !IsCanceled)
{
ExecuteWithThreadLocal();
}
else if (!IsCanceled)
{
int prevState = Interlocked.Exchange(ref m_stateFlags, m_stateFlags | TASK_STATE_CANCELED);
if ((prevState & TASK_STATE_CANCELED) == 0)
{
CancellationCleanupLogic();
}
}
return true;
}
// A trick so we can refer to the TLS slot with a byref.
// [SecurityCritical]
private void ExecuteWithThreadLocal()
{
// Remember the current task so we can restore it after running, and then
Task previousTask = ThreadLocals.s_currentTask.Value;
#if ETW_EVENTING // PAL doesn't support eventing
// ETW event for Task Started
if (TplEtwProvider.Log.IsEnabled(EventLevel.Verbose, ((EventKeywords)(-1))))
{
// previousTask holds the actual "current task" we want to report in the event
if (previousTask != null)
TplEtwProvider.Log.TaskStarted(previousTask.m_taskScheduler.Id, previousTask.Id, this.Id);
else
TplEtwProvider.Log.TaskStarted(TaskScheduler.Current.Id, 0, this.Id);
}
#endif
try
{
// place the current task into TLS.
ThreadLocals.s_currentTask.Value = this;
if (m_capturedContext == null)
{
// No context, just run the task directly.
Execute();
}
else
{
if (IsSelfReplicatingRoot || IsChildReplica)
{
m_capturedContext = m_capturedContext.CreateCopy();
}
// Run the task. We need a simple shim that converts the
// object back into a Task object, so that we can Execute it.
//#if PFX_LEGACY_3_5
// s_ecCallback(this);
//#else
ExecutionContextLightup.Instance.Run(m_capturedContext, s_ecCallback, this);
//#endif
}
Finish(true);
}
finally
{
ThreadLocals.s_currentTask.Value = previousTask;
}
#if ETW_EVENTING // PAL doesn't support eventing
// ETW event for Task Completed
if (TplEtwProvider.Log.IsEnabled(EventLevel.Verbose, ((EventKeywords)(-1))))
{
// previousTask holds the actual "current task" we want to report in the event
if (previousTask != null)
TplEtwProvider.Log.TaskCompleted(previousTask.m_taskScheduler.Id, previousTask.Id, this.Id, IsFaulted);
else
TplEtwProvider.Log.TaskCompleted(TaskScheduler.Current.Id, 0, this.Id, IsFaulted);
}
#endif
}
// [SecurityCritical]
private static Action<object> s_ecCallback;
// [SecurityCritical]
private static void ExecutionContextCallback(object obj)
{
Task task = obj as Task;
Contract.Assert(task != null, "expected a task object");
task.Execute();
}
/// <summary>
/// The actual code which invokes the body of the task. This can be overriden in derived types.
/// </summary>
internal void InnerInvoke()
{
Contract.Assert(m_action != null, "Null action in InnerInvoke()");
Action funcA = m_action as Action;
if (funcA != null)
{
funcA();
}
else
{
Action<object> funcB = m_action as Action<object>;
funcB(m_stateObject);
}
}
/// <summary>
/// Alternate InnerInvoke prototype to be called from ExecuteSelfReplicating() so that
/// the Parallel Debugger can discover the actual task being invoked.
/// Details: Here, InnerInvoke is actually being called on the rootTask object while we are actually executing the
/// childTask. And the debugger needs to discover the childTask, so we pass that down as an argument.
/// The NoOptimization and NoInlining flags ensure that the childTask pointer is retained, and that this
/// function appears on the callstack.
/// </summary>
/// <param name="childTask"></param>
[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
internal void InnerInvokeWithArg(Task childTask)
{
InnerInvoke();
}
/// <summary>
/// Performs whatever handling is necessary for an unhandled exception. Normally
/// this just entails adding the exception to the holder object.
/// </summary>
/// <param name="unhandledException">The exception that went unhandled.</param>
private void HandleException(Exception unhandledException)
{
Contract.Assert(unhandledException != null);
OperationCanceledException exceptionAsOce = unhandledException as OperationCanceledException;
if (exceptionAsOce != null && IsCancellationRequested &&
m_contingentProperties.m_cancellationToken == exceptionAsOce.CancellationToken)
{
// All conditions are satisfied for us to go into canceled state in Finish().
// Mark the acknowledgement, and return without adding the exception.
//
// However any OCE from the task that doesn't match the tasks' own CT,
// or that gets thrown without the CT being set will be treated as an ordinary exception and added to the aggreagate
SetCancellationAcknowledged();
}
else
{
AddException(unhandledException);
}
}
/// <summary>
/// Waits for the <see cref="Task"/> to complete execution.
/// </summary>
/// <exception cref="T:System.AggregateException">
/// The <see cref="Task"/> was canceled -or- an exception was thrown during
/// the execution of the <see cref="Task"/>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
public void Wait()
{
#if DEBUG
bool waitResult =
#endif
Wait(Timeout.Infinite, CancellationToken.None);
#if DEBUG
Contract.Assert(waitResult, "expected wait to succeed");
#endif
}
/// <summary>
/// Waits for the <see cref="Task"/> to complete execution.
/// </summary>
/// <param name="timeout">
/// A <see cref="System.TimeSpan"/> that represents the number of milliseconds to wait, or a <see
/// cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <returns>
/// true if the <see cref="Task"/> completed execution within the allotted time; otherwise, false.
/// </returns>
/// <exception cref="T:System.AggregateException">
/// The <see cref="Task"/> was canceled -or- an exception was thrown during the execution of the <see
/// cref="Task"/>.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="timeout"/> is a negative number other than -1 milliseconds, which represents an
/// infinite time-out -or- timeout is greater than
/// <see cref="System.Int32.MaxValue"/>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
public bool Wait(TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > 0x7fffffff)
{
throw new ArgumentOutOfRangeException("timeout");
}
return Wait((int)totalMilliseconds, CancellationToken.None);
}
/// <summary>
/// Waits for the <see cref="Task"/> to complete execution.
/// </summary>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to observe while waiting for the task to complete.
/// </param>
/// <exception cref="T:System.OperationCanceledException2">
/// The <paramref name="cancellationToken"/> was canceled.
/// </exception>
/// <exception cref="T:System.AggregateException">
/// The <see cref="Task"/> was canceled -or- an exception was thrown during the execution of the <see
/// cref="Task"/>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/>
/// has been disposed.
/// </exception>
public void Wait(CancellationToken cancellationToken)
{
Wait(Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Waits for the <see cref="Task"/> to complete execution.
/// </summary>
/// <param name="millisecondsTimeout">
/// The number of milliseconds to wait, or <see cref="System.Threading.Timeout.Infinite"/> (-1) to
/// wait indefinitely.</param>
/// <returns>true if the <see cref="Task"/> completed execution within the allotted time; otherwise,
/// false.
/// </returns>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="millisecondsTimeout"/> is a negative number other than -1, which represents an
/// infinite time-out.
/// </exception>
/// <exception cref="T:System.AggregateException">
/// The <see cref="Task"/> was canceled -or- an exception was thrown during the execution of the <see
/// cref="Task"/>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/>
/// has been disposed.
/// </exception>
public bool Wait(int millisecondsTimeout)
{
return Wait(millisecondsTimeout, CancellationToken.None);
}
/// <summary>
/// Waits for the <see cref="Task"/> to complete execution.
/// </summary>
/// <param name="millisecondsTimeout">
/// The number of milliseconds to wait, or <see cref="System.Threading.Timeout.Infinite"/> (-1) to
/// wait indefinitely.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to observe while waiting for the task to complete.
/// </param>
/// <returns>
/// true if the <see cref="Task"/> completed execution within the allotted time; otherwise, false.
/// </returns>
/// <exception cref="T:System.AggregateException">
/// The <see cref="Task"/> was canceled -or- an exception was thrown during the execution of the <see
/// cref="Task"/>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/>
/// has been disposed.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="millisecondsTimeout"/> is a negative number other than -1, which represents an
/// infinite time-out.
/// </exception>
/// <exception cref="T:System.OperationCanceledException2">
/// The <paramref name="cancellationToken"/> was canceled.
/// </exception>
public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
{
//ThrowIfDisposed();
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException("millisecondsTimeout");
}
// Return immediately if we know that we've completed "clean" -- no exceptions, no cancellations
if (CompletedSuccessfully) return true;
if (!InternalWait(millisecondsTimeout, cancellationToken))
return false;
// If an exception occurred, or the task was cancelled, throw an exception.
ThrowIfExceptional(true);
Contract.Assert((m_stateFlags & TASK_STATE_FAULTED) == 0, "Task.Wait() completing when in Faulted state.");
return true;
}
// Convenience method that wraps any scheduler exception in a TaskSchedulerException
// and rethrows it.
private bool WrappedTryRunInline()
{
if (m_taskScheduler == null)
return false;
try
{
return m_taskScheduler.TryRunInline(this, true);
}
catch (Exception e)
{
// we 1) either received an unexpected exception originating from a custom scheduler, which needs to be wrapped in a TSE and thrown
// 2) or a a ThreadAbortException, which we need to skip here, because it would already have been handled in Task.Execute
if (!(ThreadingServices.IsThreadAbort(e)))
{
TaskSchedulerException tse = new TaskSchedulerException(e);
throw tse;
}
else
{
throw;
}
}
}
// This overload takes advantage of known values for current scheduler & statics.
// It looks a LOT like the version above, but perf considerations prevented me
// from having the one above call this one.
private bool WrappedTryRunInline(TaskScheduler currentScheduler, object currentSchedulerStatics)
{
if (m_taskScheduler == null)
return false;
try
{
if (currentScheduler == m_taskScheduler)
{
return currentScheduler.TryRunInline(this, true, currentSchedulerStatics);
}
else
{
return m_taskScheduler.TryRunInline(this, true);
}
}
catch (Exception e)
{
// we 1) either received an unexpected exception originating from a custom scheduler, which needs to be wrapped in a TSE and thrown
// 2) or a a ThreadAbortException, which we need to skip here, because it would already have been handled in Task.Execute
if (!(ThreadingServices.IsThreadAbort(e)))
{
TaskSchedulerException tse = new TaskSchedulerException(e);
throw tse;
}
else
{
throw;
}
}
}
/// <summary>
/// The core wait function, which is only accesible internally. It's meant to be used in places in TPL code where
/// the current context is known or cached.
/// </summary>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
internal bool InternalWait(int millisecondsTimeout, CancellationToken cancellationToken)
{
#if ETW_EVENTING // PAL doesn't support eventing
// ETW event for Task Wait Begin
if (TplEtwProvider.Log.IsEnabled(EventLevel.Verbose, ((EventKeywords)(-1))))
{
Task currentTask = Task.InternalCurrent;
TplEtwProvider.Log.TaskWaitBegin((currentTask != null ? currentTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (currentTask != null ? currentTask.Id : 0),
this.Id);
}
#endif
bool returnValue = IsCompleted;
// If the event hasn't already been set, we will wait.
if (!returnValue)
{
//
// we will attempt inline execution only if an infinite wait was requested
// Inline execution doesn't make sense for finite timeouts and if a cancellation token was specified
// because we don't know how long the task delegate will take.
//
TaskScheduler tm = m_taskScheduler;
if (millisecondsTimeout == Timeout.Infinite && !cancellationToken.CanBeCanceled &&
WrappedTryRunInline() && IsCompleted) // TryRunInline doesn't guarantee completion, as there may be unfinished children.
{
returnValue = true;
}
else
{
returnValue = CompletedEvent.Wait(millisecondsTimeout, cancellationToken);
}
}
Contract.Assert(IsCompleted || millisecondsTimeout != Timeout.Infinite);
#if ETW_EVENTING // PAL doesn't support eventing
// ETW event for Task Wait End
if (TplEtwProvider.Log.IsEnabled(EventLevel.Verbose, ((EventKeywords)(-1))))
{
Task currentTask = Task.InternalCurrent;
TplEtwProvider.Log.TaskWaitEnd((currentTask != null ? currentTask.m_taskScheduler.Id : TaskScheduler.Current.Id), (currentTask != null ? currentTask.Id : 0),
this.Id);
}
#endif
return returnValue;
}
/// <summary>
/// Cancels the <see cref="Task"/>.
/// </summary>
/// <param name="bCancelNonExecutingOnly"> Indiactes whether we should only cancel non-invoked tasks.
/// For the default scheduler this option will only be serviced through TryDequeue.
/// For custom schedulers we also attempt an atomic state transition.</param>
/// <returns>true if the task was successfully canceled; otherwise, false.</returns>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="Task"/>
/// has been disposed.</exception>
internal bool InternalCancel(bool bCancelNonExecutingOnly)
{
Contract.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) == 0, "Task.InternalCancel() did not expect promise-style task");
//ThrowIfDisposed();
bool bPopSucceeded = false;
bool mustCleanup = false;
TaskSchedulerException tse = null;
// If started, and running in a task context, we can try to pop the chore.
if ((m_stateFlags & TASK_STATE_STARTED) != 0)
{
TaskScheduler ts = m_taskScheduler;
try
{
bPopSucceeded = (ts != null) && ts.TryDequeue(this);
}
catch (Exception e)
{
// TryDequeue threw. We don't know whether the task was properly dequeued or not. So we must let the rest of
// the cancellation logic run its course (record the request, attempt atomic state transition and do cleanup where appropriate)
// Here we will only record a TaskSchedulerException, which will later be thrown at function exit.
if (!(ThreadingServices.IsThreadAbort(e)))
{
tse = new TaskSchedulerException(e);
}
}
bool bRequiresAtomicStartTransition = (ts != null && ts.RequiresAtomicStartTransition) || ((Options & (TaskCreationOptions)InternalTaskOptions.SelfReplicating) != 0);
if (!bPopSucceeded && bCancelNonExecutingOnly && bRequiresAtomicStartTransition)
{
// The caller requested cancellation of non-invoked tasks only, and TryDequeue was one way of doing it...
// Since that seems to have failed, we should now try an atomic state transition (from non-invoked state to canceled)
// An atomic transition here is only safe if we know we're on a custom task scheduler, which also forces a CAS on ExecuteEntry
// Even though this task can't have any children, we should be ready for handling any continuations that
// may be attached to it (although currently
// So we need to remeber whether we actually did the flip, so we can do clean up (finish continuations etc)
mustCleanup = AtomicStateUpdate(TASK_STATE_CANCELED, TASK_STATE_DELEGATE_INVOKED | TASK_STATE_CANCELED);
// PS: This is slightly different from the regular cancellation codepath
// since we record the cancellation request *after* doing the state transition.
// However that shouldn't matter too much because the task was never invoked, thus can't have children
}
}
if (!bCancelNonExecutingOnly || bPopSucceeded || mustCleanup)
{
// Record the cancellation request.
RecordInternalCancellationRequest();
// Determine whether we need to clean up
// This will be the case
// 1) if we were able to pop, and we win the race to update task state to TASK_STATE_CANCELED
// 2) if the task seems to be yet unstarted, and we win the race to transition to
// TASK_STATE_CANCELED before anyone else can transition into _STARTED or _CANCELED or
// _RAN_TO_COMPLETION or _FAULTED
// Note that we do not check for TASK_STATE_COMPLETION_RESERVED. That only applies to promise-style
// tasks, and a promise-style task should not enter into this codepath.
if (bPopSucceeded)
{
// hitting this would mean something wrong with the AtomicStateUpdate above
Contract.Assert(!mustCleanup, "Possibly an invalid state transition call was made in InternalCancel()");
// Include TASK_STATE_DELEGATE_INVOKED in "illegal" bits to protect against the situation where
// TS.TryDequeue() returns true but the task is still left on the queue.
mustCleanup = AtomicStateUpdate(TASK_STATE_CANCELED, TASK_STATE_CANCELED | TASK_STATE_DELEGATE_INVOKED);
}
else if (!mustCleanup && (m_stateFlags & TASK_STATE_STARTED) == 0)
{
mustCleanup = AtomicStateUpdate(TASK_STATE_CANCELED,
TASK_STATE_CANCELED | TASK_STATE_STARTED | TASK_STATE_RAN_TO_COMPLETION |
TASK_STATE_FAULTED | TASK_STATE_DELEGATE_INVOKED);
}
// do the cleanup (i.e. set completion event and finish continuations)
if (mustCleanup)
{
CancellationCleanupLogic();
}
}
if (tse != null)
throw tse;
else
return (mustCleanup);
}
// Breaks out logic for recording a cancellation request
internal void RecordInternalCancellationRequest()
{
// Record the cancellation request.
LazyInitializer.EnsureInitialized<ContingentProperties>(ref m_contingentProperties, s_contingentPropertyCreator);
m_contingentProperties.m_internalCancellationRequested = CANCELLATION_REQUESTED;
}
// ASSUMES THAT A SUCCESSFUL CANCELLATION HAS JUST OCCURRED ON THIS TASK!!!
// And this method should be called at most once per task.
internal void CancellationCleanupLogic()
{
Contract.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved.");
// I'd like to do this, but there is a small window for a race condition. If someone calls Wait() between InternalCancel() and
// here, that will set m_completionEvent, leading to a meaningless/harmless assertion.
//Contract.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set.");
// This may have been set already, but we need to make sure.
Interlocked.Exchange(ref m_stateFlags, m_stateFlags | TASK_STATE_CANCELED);
// Fire completion event if it has been lazily initialized
SetCompleted();
// Notify parents, fire continuations, other cleanup.
FinishStageThree();
}
/// <summary>
/// Sets the task's cancellation acknowledged flag.
/// </summary>
private void SetCancellationAcknowledged()
{
Contract.Assert(this == Task.InternalCurrent, "SetCancellationAcknowledged() should only be called while this is still the current task");
Contract.Assert(IsCancellationRequested, "SetCancellationAcknowledged() should not be called if the task's CT wasn't signaled");
m_stateFlags |= TASK_STATE_CANCELLATIONACKNOWLEDGED;
}
//
// Continuation passing functionality (aka ContinueWith)
//
/// <summary>
/// A structure to hold continuation information.
/// </summary>
internal struct TaskContinuation
{
internal object m_task; // The delegate OR unstarted continuation task.
internal TaskScheduler m_taskScheduler; // The TaskScheduler with which to associate the continuation task.
internal TaskContinuationOptions m_options; // What kind of continuation.
/// <summary>
/// Constructs a new continuation structure.
/// </summary>
/// <param name="task">The task to be activated.</param>
/// <param name="options">The continuation options.</param>
/// <param name="scheduler">The scheduler to use for the continuation.</param>
internal TaskContinuation(Task task, TaskScheduler scheduler, TaskContinuationOptions options)
{
Contract.Assert(task != null, "TaskContinuation ctor: task is null");
m_task = task;
m_taskScheduler = scheduler;
m_options = options;
}
internal TaskContinuation(Action<Task> action)
{
m_task = action;
m_taskScheduler = null;
m_options = TaskContinuationOptions.None;
}
/// <summary>
/// Invokes the continuation for the target completion task.
/// </summary>
/// <param name="completedTask">The completed task.</param>
/// <param name="bCanInlineContinuationTask">Whether the continuation can be inlined.</param>
internal void Run(Task completedTask, bool bCanInlineContinuationTask)
{
Contract.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed");
Task task = m_task as Task;
if (task != null)
{
if (completedTask.ContinueWithIsRightKind(m_options))
{
task.m_taskScheduler = m_taskScheduler;
// Either run directly or just queue it up for execution, depending
// on whether synchronous or asynchronous execution is wanted.
if (bCanInlineContinuationTask && (m_options & TaskContinuationOptions.ExecuteSynchronously) != 0)
{
// Execute() won't set the TASK_STATE_STARTED flag, so we'll do it here.
if (!task.MarkStarted())
{
// task has been canceled. Abort this continuation thread.
return;
}
try
{
if (!m_taskScheduler.TryRunInline(task, false))
{
m_taskScheduler.QueueTask(task);
}
}
catch (Exception e)
{
// Either TryRunInline() or QueueTask() threw an exception. Record the exception, marking the task as Faulted.
// However if it was a ThreadAbortException coming from TryRunInline we need to skip here,
// because it would already have been handled in Task.Execute()
if (!(ThreadingServices.IsThreadAbort(e) &&
(task.m_stateFlags & TASK_STATE_THREAD_WAS_ABORTED) != 0)) // this ensures TAEs from QueueTask will be wrapped in TSE
{
TaskSchedulerException tse = new TaskSchedulerException(e);
task.AddException(tse);
task.Finish(false);
}
// Don't re-throw.
}
}
else
{
try
{
task.ScheduleAndStart(true);
}
catch (TaskSchedulerException)
{
// No further action is necessary -- ScheduleAndStart() already transitioned
// the task to faulted. But we want to make sure that no exception is thrown
// from here.
}
}
}
else
{
// The final state of this task does not match the desired
// continuation activation criteria; cancel it to denote this.
task.InternalCancel(false);
}
}
else
{
// Note for the future: ContinuationAction still run synchronously regardless of ThreadAbortException handling.
// This is probably not too importnat right now, because the internal use of continuationActions only involve short actions.
// However if we ever make these public, we need to turn them into tasks if the antecedent threw a ThreadAbortException.
Action<Task> action = m_task as Action<Task>;
Contract.Assert(action != null, "TaskContinuation.Run(): Unknown m_task type.");
action(completedTask);
}
}
}
/// <summary>
/// Runs all of the continuations, as appropriate.
/// </summary>
private void FinishContinuations()
{
// Grab the list of continuations, and lock it to contend with concurrent adds.
// At this point, IsCompleted == true, so those adding will either come before
// that and add a continuation under the lock (serializing before this), so we
// will run it; or they will attempt to acquire the lock, get it, and then see the
// task is completed (serializing after this), and run it on their own.
List<TaskContinuation> continuations = (m_contingentProperties == null) ? null : m_contingentProperties.m_continuations;
if (continuations != null)
{
lock (m_contingentProperties)
{
// Ensure that all concurrent adds have completed.
}
// skip synchronous execution of continuations if this tasks thread was aborted
bool bCanInlineContinuations = !(((m_stateFlags & TASK_STATE_THREAD_WAS_ABORTED) != 0) ||
(ThreadLightup.Current.ThreadState == ThreadState.AbortRequested));
// Records earliest index of synchronous continuation.
// A value of -1 means that no synchronous continuations were found.
int firstSynchronousContinuation = -1;
// Fire the asynchronous continuations first ...
// Go back-to-front to make the "firstSynchronousContinuation" logic simpler.
for (int i = continuations.Count - 1; i >= 0; i--)
{
TaskContinuation tc = continuations[i];
// ContinuationActions, which execute synchronously, have a null scheduler
// Synchronous continuation tasks will have the ExecuteSynchronously option
if ((tc.m_taskScheduler != null) && ((tc.m_options & TaskContinuationOptions.ExecuteSynchronously) == 0))
{
tc.Run(this, bCanInlineContinuations);
}
else firstSynchronousContinuation = i;
}
// ... and then fire the synchronous continuations (if there are any)
if (firstSynchronousContinuation > -1)
{
for (int i = firstSynchronousContinuation; i < continuations.Count; i++)
{
TaskContinuation tc = continuations[i];
// ContinuationActions, which execute synchronously, have a null scheduler
// Synchronous continuation tasks will have the ExecuteSynchronously option
if ((tc.m_taskScheduler == null) || ((tc.m_options & TaskContinuationOptions.ExecuteSynchronously) != 0))
tc.Run(this, bCanInlineContinuations);
}
}
// Don't keep references to "spent" continuations
m_contingentProperties.m_continuations = null;
}
}
/// <summary>
/// Helper function to determine whether the current task is in the state desired by the
/// continuation kind under evaluation. Three possibilities exist: the task failed with
/// an unhandled exception (OnFailed), the task was canceled before running (OnAborted),
/// or the task completed successfully (OnCompletedSuccessfully). Note that the last
/// one includes completing due to cancellation.
/// </summary>
/// <param name="options">The continuation options under evaluation.</param>
/// <returns>True if the continuation should be run given the task's current state.</returns>
internal bool ContinueWithIsRightKind(TaskContinuationOptions options)
{
Contract.Assert(IsCompleted);
if (IsFaulted)
{
return (options & TaskContinuationOptions.NotOnFaulted) == 0;
}
else if (IsCanceled)
{
return (options & TaskContinuationOptions.NotOnCanceled) == 0;
}
else
{
return (options & TaskContinuationOptions.NotOnRanToCompletion) == 0;
}
}
/// <summary>
/// Creates a continuation that executes when the target <see cref="Task"/> completes.
/// </summary>
/// <param name="continuationAction">
/// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
/// passed the completed task as an argument.
/// </param>
/// <returns>A new continuation <see cref="Task"/>.</returns>
/// <remarks>
/// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
/// completed, whether it completes due to running to completion successfully, faulting due to an
/// unhandled exception, or exiting out early due to being canceled.
/// </remarks>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationAction"/> argument is null.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task> continuationAction)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWith(continuationAction, TaskScheduler.Current, CancellationToken.None, TaskContinuationOptions.None, ref stackMark);
}
/// <summary>
/// Creates a continuation that executes when the target <see cref="Task"/> completes.
/// </summary>
/// <param name="continuationAction">
/// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
/// passed the completed task as an argument.
/// </param>
/// <param name="cancellationToken"> The <see cref="CancellationToken"/> that will be assigned to the new continuation task.</param>
/// <returns>A new continuation <see cref="Task"/>.</returns>
/// <remarks>
/// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
/// completed, whether it completes due to running to completion successfully, faulting due to an
/// unhandled exception, or exiting out early due to being canceled.
/// </remarks>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationAction"/> argument is null.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task> continuationAction, CancellationToken cancellationToken)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWith(continuationAction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
}
/// <summary>
/// Creates a continuation that executes when the target <see cref="Task"/> completes.
/// </summary>
/// <param name="continuationAction">
/// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
/// passed the completed task as an argument.
/// </param>
/// <param name="scheduler">
/// The <see cref="TaskScheduler"/> to associate with the continuation task and to use for its execution.
/// </param>
/// <returns>A new continuation <see cref="Task"/>.</returns>
/// <remarks>
/// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
/// completed, whether it completes due to running to completion successfully, faulting due to an
/// unhandled exception, or exiting out early due to being canceled.
/// </remarks>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationAction"/> argument is null.
/// </exception>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task> continuationAction, TaskScheduler scheduler)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWith(continuationAction, scheduler, CancellationToken.None, TaskContinuationOptions.None, ref stackMark);
}
/// <summary>
/// Creates a continuation that executes when the target <see cref="Task"/> completes.
/// </summary>
/// <param name="continuationAction">
/// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
/// passed the completed task as an argument.
/// </param>
/// <param name="continuationOptions">
/// Options for when the continuation is scheduled and how it behaves. This includes criteria, such
/// as <see
/// cref="System.Threading.Tasks.TaskContinuationOptions.OnlyOnCanceled">OnlyOnCanceled</see>, as
/// well as execution options, such as <see
/// cref="System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously">ExecuteSynchronously</see>.
/// </param>
/// <returns>A new continuation <see cref="Task"/>.</returns>
/// <remarks>
/// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
/// completed. If the continuation criteria specified through the <paramref
/// name="continuationOptions"/> parameter are not met, the continuation task will be canceled
/// instead of scheduled.
/// </remarks>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationAction"/> argument is null.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWith(continuationAction, TaskScheduler.Current, CancellationToken.None, continuationOptions, ref stackMark);
}
/// <summary>
/// Creates a continuation that executes when the target <see cref="Task"/> completes.
/// </summary>
/// <param name="continuationAction">
/// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
/// passed the completed task as an argument.
/// </param>
/// <param name="continuationOptions">
/// Options for when the continuation is scheduled and how it behaves. This includes criteria, such
/// as <see
/// cref="System.Threading.Tasks.TaskContinuationOptions.OnlyOnCanceled">OnlyOnCanceled</see>, as
/// well as execution options, such as <see
/// cref="System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously">ExecuteSynchronously</see>.
/// </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new continuation task.</param>
/// <param name="scheduler">
/// The <see cref="TaskScheduler"/> to associate with the continuation task and to use for its
/// execution.
/// </param>
/// <returns>A new continuation <see cref="Task"/>.</returns>
/// <remarks>
/// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
/// completed. If the criteria specified through the <paramref name="continuationOptions"/> parameter
/// are not met, the continuation task will be canceled instead of scheduled.
/// </remarks>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationAction"/> argument is null.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task ContinueWith(Action<Task> continuationAction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWith(continuationAction, scheduler, cancellationToken, continuationOptions, ref stackMark);
}
// Same as the above overload, just with a stack mark parameter.
private Task ContinueWith(Action<Task> continuationAction, TaskScheduler scheduler,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
{
//ThrowIfDisposed();
// Throw on continuation with null action
if (continuationAction == null)
{
throw new ArgumentNullException("continuationAction");
}
// Throw on continuation with null TaskScheduler
if (scheduler == null)
{
throw new ArgumentNullException("scheduler");
}
TaskCreationOptions creationOptions;
InternalTaskOptions internalOptions;
CreationOptionsFromContinuationOptions(continuationOptions, out creationOptions, out internalOptions);
Task thisTask = this;
Task continuationTask = new Task(
delegate(object obj) { continuationAction(thisTask); },
null,
Task.InternalCurrent,
cancellationToken,
creationOptions,
internalOptions,
null, // leave taskScheduler null until TaskContinuation.Run() is called
ref stackMark
);
// Register the continuation. If synchronous execution is requested, this may
// actually invoke the continuation before returning.
ContinueWithCore(continuationTask, scheduler, continuationOptions);
return continuationTask;
}
/// <summary>
/// Creates a continuation that executes when the target <see cref="Task"/> completes.
/// </summary>
/// <typeparam name="TResult">
/// The type of the result produced by the continuation.
/// </typeparam>
/// <param name="continuationFunction">
/// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
/// passed the completed task as an argument.
/// </param>
/// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
/// <remarks>
/// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
/// completed, whether it completes due to running to completion successfully, faulting due to an
/// unhandled exception, or exiting out early due to being canceled.
/// </remarks>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationFunction"/> argument is null.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWith<TResult>(continuationFunction, TaskScheduler.Current, CancellationToken.None,
TaskContinuationOptions.None, ref stackMark);
}
/// <summary>
/// Creates a continuation that executes when the target <see cref="Task"/> completes.
/// </summary>
/// <typeparam name="TResult">
/// The type of the result produced by the continuation.
/// </typeparam>
/// <param name="continuationFunction">
/// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
/// passed the completed task as an argument.
/// </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new continuation task.</param>
/// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
/// <remarks>
/// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
/// completed, whether it completes due to running to completion successfully, faulting due to an
/// unhandled exception, or exiting out early due to being canceled.
/// </remarks>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationFunction"/> argument is null.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWith<TResult>(continuationFunction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None, ref stackMark);
}
/// <summary>
/// Creates a continuation that executes when the target <see cref="Task"/> completes.
/// </summary>
/// <typeparam name="TResult">
/// The type of the result produced by the continuation.
/// </typeparam>
/// <param name="continuationFunction">
/// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
/// passed the completed task as an argument.
/// </param>
/// <param name="scheduler">
/// The <see cref="TaskScheduler"/> to associate with the continuation task and to use for its execution.
/// </param>
/// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
/// <remarks>
/// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
/// completed, whether it completes due to running to completion successfully, faulting due to an
/// unhandled exception, or exiting out early due to being canceled.
/// </remarks>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationFunction"/> argument is null.
/// </exception>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, TaskScheduler scheduler)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWith<TResult>(continuationFunction, scheduler, CancellationToken.None, TaskContinuationOptions.None, ref stackMark);
}
/// <summary>
/// Creates a continuation that executes when the target <see cref="Task"/> completes.
/// </summary>
/// <typeparam name="TResult">
/// The type of the result produced by the continuation.
/// </typeparam>
/// <param name="continuationFunction">
/// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
/// passed the completed task as an argument.
/// </param>
/// <param name="continuationOptions">
/// Options for when the continuation is scheduled and how it behaves. This includes criteria, such
/// as <see
/// cref="System.Threading.Tasks.TaskContinuationOptions.OnlyOnCanceled">OnlyOnCanceled</see>, as
/// well as execution options, such as <see
/// cref="System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously">ExecuteSynchronously</see>.
/// </param>
/// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
/// <remarks>
/// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
/// completed. If the continuation criteria specified through the <paramref
/// name="continuationOptions"/> parameter are not met, the continuation task will be canceled
/// instead of scheduled.
/// </remarks>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationFunction"/> argument is null.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWith<TResult>(continuationFunction, TaskScheduler.Current, CancellationToken.None, continuationOptions, ref stackMark);
}
/// <summary>
/// Creates a continuation that executes when the target <see cref="Task"/> completes.
/// </summary>
/// <typeparam name="TResult">
/// The type of the result produced by the continuation.
/// </typeparam>
/// <param name="continuationFunction">
/// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
/// passed the completed task as an argument.
/// </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new continuation task.</param>
/// <param name="continuationOptions">
/// Options for when the continuation is scheduled and how it behaves. This includes criteria, such
/// as <see
/// cref="System.Threading.Tasks.TaskContinuationOptions.OnlyOnCanceled">OnlyOnCanceled</see>, as
/// well as execution options, such as <see
/// cref="System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously">ExecuteSynchronously</see>.
/// </param>
/// <param name="scheduler">
/// The <see cref="TaskScheduler"/> to associate with the continuation task and to use for its
/// execution.
/// </param>
/// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
/// <remarks>
/// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
/// completed. If the criteria specified through the <paramref name="continuationOptions"/> parameter
/// are not met, the continuation task will be canceled instead of scheduled.
/// </remarks>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="continuationFunction"/> argument is null.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="scheduler"/> argument is null.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, CancellationToken cancellationToken,
TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWith<TResult>(continuationFunction, scheduler, cancellationToken, continuationOptions, ref stackMark);
}
// Same as the above overload, just with a stack mark parameter.
private Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, TaskScheduler scheduler,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, ref StackCrawlMark stackMark)
{
//ThrowIfDisposed();
// Throw on continuation with null function
if (continuationFunction == null)
{
throw new ArgumentNullException("continuationFunction");
}
// Throw on continuation with null task scheduler
if (scheduler == null)
{
throw new ArgumentNullException("scheduler");
}
TaskCreationOptions creationOptions;
InternalTaskOptions internalOptions;
CreationOptionsFromContinuationOptions(continuationOptions, out creationOptions, out internalOptions);
Task thisTask = this;
Task<TResult> continuationTask = new Task<TResult>(
delegate() { return continuationFunction(thisTask); },
Task.InternalCurrent,
cancellationToken,
creationOptions,
internalOptions,
null, // leave taskScheduler null until TaskContinuation.Run() is called
ref stackMark
);
// Register the continuation. If synchronous execution is requested, this may
// actually invoke the continuation before returning.
ContinueWithCore(continuationTask, scheduler, continuationOptions);
return continuationTask;
}
/// <summary>
/// Converts TaskContinuationOptions to TaskCreationOptions, and also does
/// some validity checking along the way.
/// </summary>
/// <param name="continuationOptions">Incoming TaskContinuationOptions</param>
/// <param name="creationOptions">Outgoing TaskCreationOptions</param>
/// <param name="internalOptions">Outgoing InternalTaskOptions</param>
internal static void CreationOptionsFromContinuationOptions(
TaskContinuationOptions continuationOptions,
out TaskCreationOptions creationOptions,
out InternalTaskOptions internalOptions)
{
// This is used a couple of times below
TaskContinuationOptions NotOnAnything =
TaskContinuationOptions.NotOnCanceled |
TaskContinuationOptions.NotOnFaulted |
TaskContinuationOptions.NotOnRanToCompletion;
TaskContinuationOptions creationOptionsMask =
TaskContinuationOptions.PreferFairness |
TaskContinuationOptions.LongRunning |
TaskContinuationOptions.AttachedToParent;
// Check that LongRunning and ExecuteSynchronously are not specified together
TaskContinuationOptions illegalMask = TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.LongRunning;
if ((continuationOptions & illegalMask) == illegalMask)
{
throw new ArgumentOutOfRangeException("continuationOptions", Strings.Task_ContinueWith_ESandLR);
}
// Check that no illegal options were specified
if ((continuationOptions &
~(creationOptionsMask | NotOnAnything |
TaskContinuationOptions.ExecuteSynchronously)) != 0)
{
throw new ArgumentOutOfRangeException("continuationOptions");
}
// Check that we didn't specify "not on anything"
if ((continuationOptions & NotOnAnything) == NotOnAnything)
{
throw new ArgumentOutOfRangeException("continuationOptions", Strings.Task_ContinueWith_NotOnAnything);
}
creationOptions = (TaskCreationOptions)(continuationOptions & creationOptionsMask);
internalOptions = InternalTaskOptions.ContinuationTask;
}
/// <summary>
/// Registers the continuation and possibly runs it (if the task is already finished).
/// </summary>
/// <param name="continuationTask">The continuation task itself.</param>
/// <param name="scheduler">TaskScheduler with which to associate continuation task.</param>
/// <param name="options">Restrictions on when the continuation becomes active.</param>
internal void ContinueWithCore(Task continuationTask, TaskScheduler scheduler, TaskContinuationOptions options)
{
Contract.Assert(continuationTask != null, "Task.ContinueWithCore(): null continuationTask");
Contract.Assert((!continuationTask.IsCompleted) || continuationTask.CancellationToken.IsCancellationRequested,
"Task.ContinueWithCore(): continuationTask is completed and its CT is not signaled");
// It doesn't really do any harm to queue up an already-completed continuation, but it's
// a little wasteful. So we'll make an attempt at avoiding it (although the race condition
// here could still result in a completed continuation task being queued.)
if (continuationTask.IsCompleted) return;
TaskContinuation continuation = new TaskContinuation(continuationTask, scheduler, options);
// If the task has not finished, we will enqueue the continuation to fire when completed.
if (!IsCompleted)
{
// If not created yet, we will atomically initialize the queue of actions.
LazyInitializer.EnsureInitialized<ContingentProperties>(ref m_contingentProperties, s_contingentPropertyCreator);
if (m_contingentProperties.m_continuations == null)
{
Interlocked.CompareExchange(ref m_contingentProperties.m_continuations, new List<TaskContinuation>(), null);
}
// Now we must serialize access to the list itself.
lock (m_contingentProperties)
{
// We have to check IsCompleted again here, since the task may have
// finished before we got around to acquiring the lock on the actions.
// There is a race condition here, but it's OK. If the thread that
// finishes the task notices a non-null actions queue it will try to
// acquire a lock on it. Thus it will have to wait for the current
// thread to exit the critical region we're currently in.
if (!IsCompleted)
{
m_contingentProperties.m_continuations.Add(continuation);
return;
}
}
}
// If we fell through, the task has already completed. We'll invoke the action inline.
// Only start the continuation if the right kind was established.
continuation.Run(this, true);
}
// Adds a lightweight completion action to a task. This is similar to a continuation
// task except that it is stored as an action, and thus does not require the allocation/
// execution resources of a continuation task.
//
// Used internally by ContinueWhenAll() and ContinueWhenAny().
internal void AddCompletionAction(Action<Task> action)
{
if (!IsCompleted)
{
LazyInitializer.EnsureInitialized<ContingentProperties>(ref m_contingentProperties, s_contingentPropertyCreator);
TaskContinuation tc = new TaskContinuation(action);
if (m_contingentProperties.m_continuations == null)
{
Interlocked.CompareExchange(ref m_contingentProperties.m_continuations, new List<TaskContinuation>(), null);
}
// Serialize access to the continuations list
lock (m_contingentProperties)
{
// We have to check IsCompleted again here, since the task may have
// finished before we got around to acquiring the lock on the actions.
// There is a race condition here, but it's OK. If the thread that
// finishes the task notices a non-null actions queue it will try to
// acquire a lock on it. Thus it will have to wait for the current
// thread to exit the critical region we're currently in.
if (!IsCompleted)
{
m_contingentProperties.m_continuations.Add(tc);
return;
}
}
}
// If we got this far, we've already completed
action(this);
}
//
// Wait methods
//
/// <summary>
/// Waits for all of the provided <see cref="Task"/> objects to complete execution.
/// </summary>
/// <param name="tasks">
/// An array of <see cref="Task"/> instances on which to wait.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="tasks"/> argument is null.
/// </exception>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="tasks"/> argument contains a null element.
/// </exception>
/// <exception cref="T:System.AggregateException">
/// At least one of the <see cref="Task"/> instances was canceled -or- an exception was thrown during
/// the execution of at least one of the <see cref="Task"/> instances.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static void WaitAll(params Task[] tasks)
{
#if DEBUG
bool waitResult =
#endif
WaitAll(tasks, Timeout.Infinite);
#if DEBUG
Contract.Assert(waitResult, "expected wait to succeed");
#endif
}
/// <summary>
/// Waits for all of the provided <see cref="Task"/> objects to complete execution.
/// </summary>
/// <returns>
/// true if all of the <see cref="Task"/> instances completed execution within the allotted time;
/// otherwise, false.
/// </returns>
/// <param name="tasks">
/// An array of <see cref="Task"/> instances on which to wait.
/// </param>
/// <param name="timeout">
/// A <see cref="System.TimeSpan"/> that represents the number of milliseconds to wait, or a <see
/// cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="tasks"/> argument is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// The <paramref name="tasks"/> argument contains a null element.
/// </exception>
/// <exception cref="T:System.AggregateException">
/// At least one of the <see cref="Task"/> instances was canceled -or- an exception was thrown during
/// the execution of at least one of the <see cref="Task"/> instances.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="timeout"/> is a negative number other than -1 milliseconds, which represents an
/// infinite time-out -or- timeout is greater than
/// <see cref="System.Int32.MaxValue"/>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static bool WaitAll(Task[] tasks, TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > 0x7fffffff)
{
throw new ArgumentOutOfRangeException("timeout");
}
return WaitAll(tasks, (int)totalMilliseconds);
}
/// <summary>
/// Waits for all of the provided <see cref="Task"/> objects to complete execution.
/// </summary>
/// <returns>
/// true if all of the <see cref="Task"/> instances completed execution within the allotted time;
/// otherwise, false.
/// </returns>
/// <param name="millisecondsTimeout">
/// The number of milliseconds to wait, or <see cref="System.Threading.Timeout.Infinite"/> (-1) to
/// wait indefinitely.</param>
/// <param name="tasks">An array of <see cref="Task"/> instances on which to wait.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="tasks"/> argument is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// The <paramref name="tasks"/> argument contains a null element.
/// </exception>
/// <exception cref="T:System.AggregateException">
/// At least one of the <see cref="Task"/> instances was canceled -or- an exception was thrown during
/// the execution of at least one of the <see cref="Task"/> instances.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="millisecondsTimeout"/> is a negative number other than -1, which represents an
/// infinite time-out.
/// </exception>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static bool WaitAll(Task[] tasks, int millisecondsTimeout)
{
return WaitAll(tasks, millisecondsTimeout, CancellationToken.None);
}
/// <summary>
/// Waits for all of the provided <see cref="Task"/> objects to complete execution.
/// </summary>
/// <returns>
/// true if all of the <see cref="Task"/> instances completed execution within the allotted time;
/// otherwise, false.
/// </returns>
/// <param name="tasks">
/// An array of <see cref="Task"/> instances on which to wait.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to observe while waiting for the tasks to complete.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="tasks"/> argument is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// The <paramref name="tasks"/> argument contains a null element.
/// </exception>
/// <exception cref="T:System.AggregateException">
/// At least one of the <see cref="Task"/> instances was canceled -or- an exception was thrown during
/// the execution of at least one of the <see cref="Task"/> instances.
/// </exception>
/// <exception cref="T:System.OperationCanceledException2">
/// The <paramref name="cancellationToken"/> was canceled.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static void WaitAll(Task[] tasks, CancellationToken cancellationToken)
{
WaitAll(tasks, Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Waits for all of the provided <see cref="Task"/> objects to complete execution.
/// </summary>
/// <returns>
/// true if all of the <see cref="Task"/> instances completed execution within the allotted time;
/// otherwise, false.
/// </returns>
/// <param name="tasks">
/// An array of <see cref="Task"/> instances on which to wait.
/// </param>
/// <param name="millisecondsTimeout">
/// The number of milliseconds to wait, or <see cref="System.Threading.Timeout.Infinite"/> (-1) to
/// wait indefinitely.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to observe while waiting for the tasks to complete.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="tasks"/> argument is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// The <paramref name="tasks"/> argument contains a null element.
/// </exception>
/// <exception cref="T:System.AggregateException">
/// At least one of the <see cref="Task"/> instances was canceled -or- an exception was thrown during
/// the execution of at least one of the <see cref="Task"/> instances.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="millisecondsTimeout"/> is a negative number other than -1, which represents an
/// infinite time-out.
/// </exception>
/// <exception cref="T:System.OperationCanceledException2">
/// The <paramref name="cancellationToken"/> was canceled.
/// </exception>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
{
if (tasks == null)
{
throw new ArgumentNullException("tasks");
}
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException("timeout");
}
#if DEBUG
Contract.Assert(tasks != null && millisecondsTimeout >= -1, "invalid arguments passed to WaitAll");
#endif
cancellationToken.ThrowIfCancellationRequested(); // early check before we make any allocations
//
// In this WaitAll() implementation we have 2 alternate code paths for a task to be handled:
// CODEPATH1: skip an already completed task, CODEPATH2: actually wait on task's handle
// We make sure that the exception behavior of Task.Wait() is replicated the same for tasks handled in either of these codepaths
//
List<Exception> exceptions = null;
List<Task> waitedOnTaskList = null; // tasks whose async handles we actually grabbed
bool returnValue = true;
Task currentTask = Task.InternalCurrent;
TaskScheduler currentTm = (currentTask == null) ? TaskScheduler.Default : currentTask.ExecutingTaskScheduler;
object currentTmStatics = currentTm.GetThreadStatics();
// Collects incomplete tasks in "waitedOnTaskList"
for (int i = tasks.Length - 1; i >= 0; i--)
{
Task task = tasks[i];
if (task == null)
{
throw new ArgumentException(Strings.Task_WaitMulti_NullTask,"tasks");
}
//task.ThrowIfDisposed();
bool taskIsCompleted = task.IsCompleted;
if (!taskIsCompleted)
{
// try inlining the task only if we have an infinite timeout and an empty cancellation token
if (millisecondsTimeout != Timeout.Infinite || cancellationToken.CanBeCanceled)
{
// We either didn't attempt inline execution because we had a non-infinite timeout or we had a cancellable token.
// In all cases we need to do a full wait on the task (=> add its event into the list.)
if (waitedOnTaskList == null)
{
waitedOnTaskList = new List<Task>(tasks.Length);
}
waitedOnTaskList.Add(task);
}
else
{
// We are eligible for inlining.
taskIsCompleted = task.WrappedTryRunInline(currentTm, currentTmStatics) &&
task.IsCompleted; // A successful TryRunInline doesn't guarantee completion
if (!taskIsCompleted)
{
// Inlining didn't work.
// Do a full wait on the task (=> add its event into the list.)
if (waitedOnTaskList == null)
{
waitedOnTaskList = new List<Task>(tasks.Length);
}
waitedOnTaskList.Add(task);
}
}
}
if (taskIsCompleted)
{
// The task has finished. Make sure we aggregate its exceptions.
AddExceptionsForCompletedTask(ref exceptions, task);
}
}
if (waitedOnTaskList != null)
{
Contract.Assert(waitedOnTaskList.Count > 0);
WaitHandle[] waitHandles = new WaitHandle[waitedOnTaskList.Count];
for (int i = 0; i < waitHandles.Length; i++)
{
waitHandles[i] = waitedOnTaskList[i].CompletedEvent.WaitHandle;
}
returnValue = WaitAllSTAAnd64Aware(waitHandles, millisecondsTimeout, cancellationToken);
// If the wait didn't time out, ensure exceptions are propagated.
if (returnValue)
{
for (int i = 0; i < waitedOnTaskList.Count; i++)
{
AddExceptionsForCompletedTask(ref exceptions, waitedOnTaskList[i]);
}
}
// We need to prevent the tasks array from being GC'ed until we come out of the wait.
// This is necessary so that the Parallel Debugger can traverse it during the long wait and deduce waiter/waitee relationships
GC.KeepAlive(tasks);
}
// If one or more threw exceptions, aggregate them.
if (exceptions != null)
{
throw new AggregateException(exceptions);
}
return returnValue;
}
/// <summary>
/// Waits for a set of handles in a STA-aware way. In other words, it will wait for each
/// of the events individually if we're on a STA thread, because MsgWaitForMultipleObjectsEx
/// can't do a true wait-all due to its hidden message queue event. This is not atomic,
/// of course, but we only wait on one-way (MRE) events anyway so this is OK.
/// </summary>
/// <param name="waitHandles">An array of wait handles to wait on.</param>
/// <param name="millisecondsTimeout">The timeout to use during waits.</param>
/// <param name="cancellationToken">The cancellationToken that enables a wait to be canceled.</param>
/// <returns>True if all waits succeeded, false if a timeout occurred.</returns>
private static bool WaitAllSTAAnd64Aware(WaitHandle[] waitHandles, int millisecondsTimeout, CancellationToken cancellationToken)
{
// We're on an STA thread, so we can't use the real Win32 wait-all.
// We instead walk the list, and wait on each individually. Perf will
// be poor because we'll incur O(N) context switches as we wake up.
// CancellationToken enabled waits will also choose this codepath regardless of apartment state.
// The ability to use WaitAny to probe for cancellation during one by one waits makes it easy to support CT without introducing racy code paths.
WaitHandle[] cancelableWHPair = null; // to be used with WaitAny if we have a CancellationToken
if (cancellationToken.CanBeCanceled)
{
cancelableWHPair = new WaitHandle[2]; // one for the actual wait handle, other for the cancellation event
cancelableWHPair[1] = cancellationToken.WaitHandle;
}
for (int i = 0; i < waitHandles.Length; i++)
{
long startTicks = (millisecondsTimeout == Timeout.Infinite) ? 0 : DateTime.UtcNow.Ticks;
if (cancellationToken.CanBeCanceled)
{
// do a WaitAny on the WH of interest and the cancellation event.
cancelableWHPair[0] = waitHandles[i];
int waitRetCode = WaitHandle.WaitAny(cancelableWHPair, millisecondsTimeout);
if (waitRetCode == WaitHandle.WaitTimeout)
return false;
// we could have come out of the wait due to index 1 (i.e. cancellationToken.WaitHandle), check and throw
cancellationToken.ThrowIfCancellationRequested();
// the wait should have returned 0, otherwise we have a bug in CT or the code above
Contract.Assert(waitRetCode == 0, "Unexpected waitcode from WaitAny with cancellation event");
}
else
{
if (!waitHandles[i].WaitOne(millisecondsTimeout))
return false;
}
// Adjust the timeout.
if (millisecondsTimeout != Timeout.Infinite)
{
long elapsedMilliseconds = (DateTime.UtcNow.Ticks - startTicks) / TimeSpan.TicksPerMillisecond;
if (elapsedMilliseconds > int.MaxValue || elapsedMilliseconds > millisecondsTimeout)
return false;
millisecondsTimeout -= (int)elapsedMilliseconds;
}
}
return true;
}
/// <summary>
/// Internal WaitAll implementation which is meant to be used with small number of tasks,
/// optimized for Parallel.Invoke and other structured primitives.
/// </summary>
internal static void FastWaitAll(Task[] tasks)
{
#if DEBUG
Contract.Assert(tasks != null);
#endif
List<Exception> exceptions = null;
TaskScheduler currentTm = TaskScheduler.Current;
object currentTmStatics = currentTm.GetThreadStatics();
// Collects incomplete tasks in "waitedOnTaskList" and their cooperative events in "cooperativeEventList"
for (int i = tasks.Length - 1; i >= 0; i--)
{
if (!tasks[i].IsCompleted)
{
// Just attempting to inline here... result doesn't matter.
// We'll do a second pass to do actual wait on each task, and to aggregate their exceptions.
// If the task is inlined here, it will register as IsCompleted in the second pass
// and will just give us the exception.
tasks[i].WrappedTryRunInline(currentTm, currentTmStatics);
}
}
// Wait on the tasks.
for (int i = tasks.Length - 1; i >= 0; i--)
{
tasks[i].CompletedEvent.Wait(); // Just a boolean check if the task is already done.
AddExceptionsForCompletedTask(ref exceptions, tasks[i]);
}
// If one or more threw exceptions, aggregate them.
if (exceptions != null)
{
throw new AggregateException(exceptions);
}
}
/// <summary>
/// This internal function is only meant to be called by WaitAll()
/// If the completed task is canceled or it has other exceptions, here we will add those
/// into the passed in exception list (which will be lazily initialized here).
/// </summary>
internal static void AddExceptionsForCompletedTask(ref List<Exception> exceptions, Task t)
{
AggregateException ex = t.GetExceptions(true);
if (ex != null)
{
// make sure the task's exception observed status is set appropriately
// it's possible that WaitAll was called by the parent of an attached child,
// this will make sure it won't throw again in the implicit wait
t.UpdateExceptionObservedStatus();
if (exceptions == null)
{
exceptions = new List<Exception>(ex.InnerExceptions.Count);
}
exceptions.AddRange(ex.InnerExceptions);
}
}
/// <summary>
/// Waits for any of the provided <see cref="Task"/> objects to complete execution.
/// </summary>
/// <param name="tasks">
/// An array of <see cref="Task"/> instances on which to wait.
/// </param>
/// <returns>The index of the completed task in the <paramref name="tasks"/> array argument.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="tasks"/> argument is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// The <paramref name="tasks"/> argument contains a null element.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static int WaitAny(params Task[] tasks)
{
int waitResult = WaitAny(tasks, Timeout.Infinite);
Contract.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed");
return waitResult;
}
/// <summary>
/// Waits for any of the provided <see cref="Task"/> objects to complete execution.
/// </summary>
/// <param name="tasks">
/// An array of <see cref="Task"/> instances on which to wait.
/// </param>
/// <param name="timeout">
/// A <see cref="System.TimeSpan"/> that represents the number of milliseconds to wait, or a <see
/// cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <returns>
/// The index of the completed task in the <paramref name="tasks"/> array argument, or -1 if the
/// timeout occurred.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="tasks"/> argument is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// The <paramref name="tasks"/> argument contains a null element.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="timeout"/> is a negative number other than -1 milliseconds, which represents an
/// infinite time-out -or- timeout is greater than
/// <see cref="System.Int32.MaxValue"/>.
/// </exception>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static int WaitAny(Task[] tasks, TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > 0x7fffffff)
{
throw new ArgumentOutOfRangeException("timeout");
}
return WaitAny(tasks, (int)totalMilliseconds);
}
/// <summary>
/// Waits for any of the provided <see cref="Task"/> objects to complete execution.
/// </summary>
/// <param name="tasks">
/// An array of <see cref="Task"/> instances on which to wait.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to observe while waiting for a task to complete.
/// </param>
/// <returns>
/// The index of the completed task in the <paramref name="tasks"/> array argument.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="tasks"/> argument is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// The <paramref name="tasks"/> argument contains a null element.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
/// <exception cref="T:System.OperationCanceledException2">
/// The <paramref name="cancellationToken"/> was canceled.
/// </exception>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static int WaitAny(Task[] tasks, CancellationToken cancellationToken)
{
return WaitAny(tasks, Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Waits for any of the provided <see cref="Task"/> objects to complete execution.
/// </summary>
/// <param name="tasks">
/// An array of <see cref="Task"/> instances on which to wait.
/// </param>
/// <param name="millisecondsTimeout">
/// The number of milliseconds to wait, or <see cref="System.Threading.Timeout.Infinite"/> (-1) to
/// wait indefinitely.
/// </param>
/// <returns>
/// The index of the completed task in the <paramref name="tasks"/> array argument, or -1 if the
/// timeout occurred.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="tasks"/> argument is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// The <paramref name="tasks"/> argument contains a null element.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="millisecondsTimeout"/> is a negative number other than -1, which represents an
/// infinite time-out.
/// </exception>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static int WaitAny(Task[] tasks, int millisecondsTimeout)
{
return WaitAny(tasks, millisecondsTimeout, CancellationToken.None);
}
/// <summary>
/// Waits for any of the provided <see cref="Task"/> objects to complete execution.
/// </summary>
/// <param name="tasks">
/// An array of <see cref="Task"/> instances on which to wait.
/// </param>
/// <param name="millisecondsTimeout">
/// The number of milliseconds to wait, or <see cref="System.Threading.Timeout.Infinite"/> (-1) to
/// wait indefinitely.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to observe while waiting for a task to complete.
/// </param>
/// <returns>
/// The index of the completed task in the <paramref name="tasks"/> array argument, or -1 if the
/// timeout occurred.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// The <paramref name="tasks"/> argument is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// The <paramref name="tasks"/> argument contains a null element.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="Task"/> has been disposed.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="millisecondsTimeout"/> is a negative number other than -1, which represents an
/// infinite time-out.
/// </exception>
/// <exception cref="T:System.OperationCanceledException2">
/// The <paramref name="cancellationToken"/> was canceled.
/// </exception>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static int WaitAny(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
{
if (tasks == null)
{
throw new ArgumentNullException("tasks");
}
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException("millisecondsTimeout");
}
if (tasks.Length > 0)
{
var tcs = new TaskCompletionSource<Task>();
Task.Factory.ContinueWhenAny(tasks, completed => tcs.TrySetResult(completed),
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
if (tcs.Task.Wait(millisecondsTimeout, cancellationToken))
{
var resultTask = tcs.Task.Result;
for (int i = 0; i < tasks.Length; i++)
{
if (tasks[i] == resultTask)
return i;
}
}
}
// We need to prevent the tasks array from being GC'ed until we come out of the wait.
// This is necessary so that the Parallel Debugger can traverse it during the long wait and deduce waiter/waitee relationships
GC.KeepAlive(tasks);
return -1;
}
}
// Proxy class for better debugging experience
internal class SystemThreadingTasks_TaskDebugView
{
private Task m_task;
public SystemThreadingTasks_TaskDebugView(Task task)
{
m_task = task;
}
public object AsyncState { get { return m_task.AsyncState; } }
public TaskCreationOptions CreationOptions { get { return m_task.CreationOptions; } }
public Exception Exception { get { return m_task.Exception; } }
public int Id { get { return m_task.Id; } }
public bool CancellationPending { get { return (m_task.Status == TaskStatus.WaitingToRun) && m_task.CancellationToken.IsCancellationRequested; } }
public TaskStatus Status { get { return m_task.Status; } }
}
/// <summary>
/// Specifies flags that control optional behavior for the creation and execution of tasks.
/// </summary>
[Flags]
public enum TaskCreationOptions
{
/// <summary>
/// Specifies that the default behavior should be used.
/// </summary>
None = 0x0,
/// <summary>
/// A hint to a <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> to schedule a
/// task in as fair a manner as possible, meaning that tasks scheduled sooner will be more likely to
/// be run sooner, and tasks scheduled later will be more likely to be run later.
/// </summary>
PreferFairness = 0x01,
/// <summary>
/// Specifies that a task will be a long-running, course-grained operation. It provides a hint to the
/// <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> that oversubscription may be
/// warranted.
/// </summary>
LongRunning = 0x02,
/// <summary>
/// Specifies that a task is attached to a parent in the task hierarchy.
/// </summary>
AttachedToParent = 0x04,
}
/// <summary>
/// Task creation flags which are only used internally.
/// </summary>
[Flags]
internal enum InternalTaskOptions
{
/// <summary> Specifies "No internal task options" </summary>
None,
/// <summary>Used to filter out internal vs. public task creation options.</summary>
InternalOptionsMask = 0x0000FF00,
ChildReplica = 0x0100,
ContinuationTask = 0x0200,
PromiseTask = 0x0400,
SelfReplicating = 0x0800,
/// <summary>Specifies that the task will be queued by the runtime before handing it over to the user.
/// This flag will be used to skip the cancellationtoken registration step, which is only meant for unstarted tasks.</summary>
QueuedByRuntime = 0x2000
}
/// <summary>
/// Specifies flags that control optional behavior for the creation and execution of continuation tasks.
/// </summary>
[Flags]
public enum TaskContinuationOptions
{
/// <summary>
/// Default = "Continue on any, no task options, run asynchronously"
/// Specifies that the default behavior should be used. Continuations, by default, will
/// be scheduled when the antecedent task completes, regardless of the task's final <see
/// cref="System.Threading.Tasks.TaskStatus">TaskStatus</see>.
/// </summary>
None = 0,
// These are identical to their meanings and values in TaskCreationOptions
/// <summary>
/// A hint to a <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> to schedule a
/// task in as fair a manner as possible, meaning that tasks scheduled sooner will be more likely to
/// be run sooner, and tasks scheduled later will be more likely to be run later.
/// </summary>
PreferFairness = 0x01,
/// <summary>
/// Specifies that a task will be a long-running, course-grained operation. It provides
/// a hint to the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> that
/// oversubscription may be warranted.
/// </summary>
LongRunning = 0x02,
/// <summary>
/// Specifies that a task is attached to a parent in the task hierarchy.
/// </summary>
AttachedToParent = 0x04,
// These are specific to continuations
/// <summary>
/// Specifies that the continuation task should not be scheduled if its antecedent ran to completion.
/// This option is not valid for multi-task continuations.
/// </summary>
NotOnRanToCompletion = 0x10000,
/// <summary>
/// Specifies that the continuation task should not be scheduled if its antecedent threw an unhandled
/// exception. This option is not valid for multi-task continuations.
/// </summary>
NotOnFaulted = 0x20000,
/// <summary>
/// Specifies that the continuation task should not be scheduled if its antecedent was canceled. This
/// option is not valid for multi-task continuations.
/// </summary>
NotOnCanceled = 0x40000,
/// <summary>
/// Specifies that the continuation task should be scheduled only if its antecedent ran to
/// completion. This option is not valid for multi-task continuations.
/// </summary>
OnlyOnRanToCompletion = NotOnFaulted | NotOnCanceled,
/// <summary>
/// Specifies that the continuation task should be scheduled only if its antecedent threw an
/// unhandled exception. This option is not valid for multi-task continuations.
/// </summary>
OnlyOnFaulted = NotOnRanToCompletion | NotOnCanceled,
/// <summary>
/// Specifies that the continuation task should be scheduled only if its antecedent was canceled.
/// This option is not valid for multi-task continuations.
/// </summary>
OnlyOnCanceled = NotOnRanToCompletion | NotOnFaulted,
/// <summary>
/// Specifies that the continuation task should be executed synchronously. With this option
/// specified, the continuation will be run on the same thread that causes the antecedent task to
/// transition into its final state. If the antecedent is already complete when the continuation is
/// created, the continuation will run on the thread creating the continuation. Only very
/// short-running continuations should be executed synchronously.
/// </summary>
ExecuteSynchronously = 0x80000
}
}
| 48.725322 | 194 | 0.597658 | [
"MIT"
] | Abdalla-rabie/referencesource | Microsoft.Bcl/System.Threading.Tasks.v1.5/System/Threading/Tasks/Task.cs | 215,709 | C# |
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Transactions.Abstractions;
using Newtonsoft.Json;
using Orleans.Transactions.Abstractions.Extensions;
using Orleans.Transactions.State;
using System;
using System.Collections.Generic;
using Orleans.Configuration;
using Microsoft.Extensions.Options;
namespace Orleans.Transactions
{
/// <summary>
/// Stateful facet that respects Orleans transaction semantics
/// </summary>
public class TransactionalState<TState> : ITransactionalState<TState>, ITransactionParticipant, ILifecycleParticipant<IGrainLifecycle>
where TState : class, new()
{
private readonly ITransactionalStateConfiguration config;
private readonly IGrainActivationContext context;
private readonly ITransactionDataCopier<TState> copier;
private readonly IProviderRuntime runtime;
private readonly IGrainRuntime grainRuntime;
private readonly ILoggerFactory loggerFactory;
private readonly JsonSerializerSettings serializerSettings;
private ILogger logger;
private ITransactionParticipant thisParticipant;
private TransactionQueue<TState> queue;
private TransactionalResource<TState> resource;
private TransactionManager<TState> transactionManager;
public string CurrentTransactionId => TransactionContext.GetRequiredTransactionInfo<TransactionInfo>().Id;
private bool detectReentrancy;
public TransactionalState(
ITransactionalStateConfiguration transactionalStateConfiguration,
IGrainActivationContext context,
ITransactionDataCopier<TState> copier,
IProviderRuntime runtime,
IGrainRuntime grainRuntime,
ILoggerFactory loggerFactory,
JsonSerializerSettings serializerSettings
)
{
this.config = transactionalStateConfiguration;
this.context = context;
this.copier = copier;
this.runtime = runtime;
this.grainRuntime = grainRuntime;
this.loggerFactory = loggerFactory;
this.serializerSettings = serializerSettings;
}
public Task Prepare(Guid transactionId, AccessCounter accessCount, DateTime timeStamp, ITransactionParticipant transactionManager)
{
return this.resource.Prepare(transactionId, accessCount, timeStamp, transactionManager);
}
public Task Abort(Guid transactionId)
{
return this.resource.Abort(transactionId);
}
public Task Cancel(Guid transactionId, DateTime timeStamp, TransactionalStatus status)
{
return this.resource.Cancel(transactionId, timeStamp, status);
}
public Task Confirm(Guid transactionId, DateTime timeStamp)
{
return this.resource.Confirm(transactionId, timeStamp);
}
public Task<TransactionalStatus> CommitReadOnly(Guid transactionId, AccessCounter accessCount, DateTime timeStamp)
{
return this.transactionManager.CommitReadOnly(transactionId, accessCount, timeStamp);
}
public Task<TransactionalStatus> PrepareAndCommit(Guid transactionId, AccessCounter accessCount, DateTime timeStamp, List<ITransactionParticipant> writeParticipants, int totalParticipants)
{
return this.transactionManager.PrepareAndCommit(transactionId, accessCount, timeStamp, writeParticipants, totalParticipants);
}
public Task Prepared(Guid transactionId, DateTime timeStamp, ITransactionParticipant participant, TransactionalStatus status)
{
return this.transactionManager.Prepared(transactionId, timeStamp, participant, status);
}
public Task Ping(Guid transactionId, DateTime timeStamp, ITransactionParticipant participant)
{
return this.transactionManager.Ping(transactionId, timeStamp, participant);
}
/// <summary>
/// Read the current state.
/// </summary>
public Task<TResult> PerformRead<TResult>(Func<TState, TResult> operation)
{
if (detectReentrancy)
{
throw new LockRecursionException("cannot perform a read operation from within another operation");
}
var info = (TransactionInfo)TransactionContext.GetRequiredTransactionInfo<TransactionInfo>();
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace($"StartRead {info}");
info.Participants.TryGetValue(this.thisParticipant, out var recordedaccesses);
// schedule read access to happen under the lock
return this.queue.RWLock.EnterLock<TResult>(info.TransactionId, info.Priority, recordedaccesses, true,
new Task<TResult>(() =>
{
// check if our record is gone because we expired while waiting
if (!this.queue.RWLock.TryGetRecord(info.TransactionId, out TransactionRecord<TState> record))
{
throw new OrleansTransactionLockAcquireTimeoutException(info.TransactionId.ToString());
}
// merge the current clock into the transaction time stamp
record.Timestamp = this.queue.Clock.MergeUtcNow(info.TimeStamp);
if (record.State == null)
{
this.queue.GetMostRecentState(out record.State, out record.SequenceNumber);
}
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug($"update-lock read v{record.SequenceNumber} {record.TransactionId} {record.Timestamp:o}");
// record this read in the transaction info data structure
info.RecordRead(this.thisParticipant, record.Timestamp);
// perform the read
TResult result = default(TResult);
try
{
detectReentrancy = true;
result = operation(record.State);
}
finally
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace($"EndRead {info} {result} {record.State}");
detectReentrancy = false;
}
return result;
}));
}
/// <inheritdoc/>
public Task<TResult> PerformUpdate<TResult>(Func<TState, TResult> updateAction)
{
if (updateAction == null) throw new ArgumentNullException(nameof(updateAction));
if (detectReentrancy)
{
throw new LockRecursionException("cannot perform an update operation from within another operation");
}
var info = (TransactionInfo)TransactionContext.GetRequiredTransactionInfo<TransactionInfo>();
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace($"StartWrite {info}");
if (info.IsReadOnly)
{
throw new OrleansReadOnlyViolatedException(info.Id);
}
info.Participants.TryGetValue(this.thisParticipant, out var recordedaccesses);
return this.queue.RWLock.EnterLock<TResult>(info.TransactionId, info.Priority, recordedaccesses, false,
new Task<TResult>(() =>
{
// check if we expired while waiting
if (!this.queue.RWLock.TryGetRecord(info.TransactionId, out TransactionRecord<TState> record))
{
throw new OrleansTransactionLockAcquireTimeoutException(info.TransactionId.ToString());
}
// merge the current clock into the transaction time stamp
record.Timestamp = this.queue.Clock.MergeUtcNow(info.TimeStamp);
// link to the latest state
if (record.State == null)
{
this.queue.GetMostRecentState(out record.State, out record.SequenceNumber);
}
// if this is the first write, make a deep copy of the state
if (!record.HasCopiedState)
{
record.State = this.copier.DeepCopy(record.State);
record.SequenceNumber++;
record.HasCopiedState = true;
}
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug($"update-lock write v{record.SequenceNumber} {record.TransactionId} {record.Timestamp:o}");
// record this write in the transaction info data structure
info.RecordWrite(this.thisParticipant, record.Timestamp);
// record this participant as a TM candidate
if (info.TMCandidate == null || !info.TMCandidate.Equals(this.thisParticipant))
{
int batchsize = this.queue.BatchableOperationsCount();
if (info.TMCandidate == null || batchsize > info.TMBatchSize)
{
info.TMCandidate = this.thisParticipant;
info.TMBatchSize = batchsize;
}
}
// perform the write
try
{
detectReentrancy = true;
return updateAction(record.State);
}
finally
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace($"EndWrite {info} {record.State}");
detectReentrancy = false;
}
}
));
}
public void Participate(IGrainLifecycle lifecycle)
{
lifecycle.Subscribe<TransactionalState<TState>>(GrainLifecycleStage.SetupState, OnSetupState);
}
public bool Equals(ITransactionParticipant other)
{
return thisParticipant.Equals(other);
}
public override string ToString()
{
return $"{this.context.GrainInstance}.{this.config.StateName}";
}
private async Task OnSetupState(CancellationToken ct)
{
if (ct.IsCancellationRequested) return;
var boundExtension = await this.runtime.BindExtension<TransactionParticipantExtension, ITransactionParticipantExtension>(() => new TransactionParticipantExtension());
boundExtension.Item1.Register(this.config.StateName, this);
this.thisParticipant = boundExtension.Item2.AsTransactionParticipant(this.config.StateName);
this.logger = loggerFactory.CreateLogger($"{context.GrainType.Name}.{this.config.StateName}.{this.thisParticipant.ToShortString()}");
var storageFactory = this.context.ActivationServices.GetRequiredService<INamedTransactionalStateStorageFactory>();
ITransactionalStateStorage<TState> storage = storageFactory.Create<TState>(this.config.StorageName, this.config.StateName);
Action deactivate = () => grainRuntime.DeactivateOnIdle(context.GrainInstance);
var options = this.context.ActivationServices.GetRequiredService<IOptions<TransactionalStateOptions>>();
var clock = this.context.ActivationServices.GetRequiredService<IClock>();
this.queue = new TransactionQueue<TState>(options, this.thisParticipant, deactivate, storage, this.serializerSettings, clock, logger);
this.resource = new TransactionalResource<TState>(this.queue);
this.transactionManager = new TransactionManager<TState>(this.queue);
// recover state
await this.queue.NotifyOfRestore();
}
private string StoredName()
{
return $"{this.context.GrainInstance.GetType().FullName}-{this.config.StateName}";
}
}
}
| 43.00692 | 196 | 0.609462 | [
"MIT"
] | brhinescot/orleans | src/Orleans.Transactions/State/TransactionalState.cs | 12,431 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using InsuranceCalc.Data;
namespace InsuranceCalc
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<InsuranceCalcContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
}
}
| 32.657534 | 145 | 0.590185 | [
"MIT"
] | jsaparco-ueno/jsu-contents-limit-insurance-calculator | Startup.cs | 2,384 | C# |
using System.Text.Json;
using Enclave.Sdk.Api.Clients;
using Enclave.Sdk.Api.Data;
using Enclave.Sdk.Api.Data.Account;
using Enclave.Sdk.Api.Data.Organisations;
using Enclave.Sdk.Api.Data.PatchModel;
using FluentAssertions;
using NUnit.Framework;
using WireMock.FluentAssertions;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
namespace Enclave.Sdk.Api.Tests.Clients;
public class OrganisationClientTests
{
private OrganisationClient _organisationClient;
private WireMockServer _server;
private string _orgRoute;
private readonly JsonSerializerOptions _serializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
[SetUp]
public void Setup()
{
_server = WireMockServer.Start();
var httpClient = new HttpClient
{
BaseAddress = new Uri(_server.Urls[0]),
};
var currentOrganisation = new AccountOrganisation
{
OrgId = OrganisationId.New(),
OrgName = "TestName",
Role = UserOrganisationRole.Admin,
};
_orgRoute = $"/org/{currentOrganisation.OrgId}";
_organisationClient = new OrganisationClient(httpClient, currentOrganisation);
}
[Test]
public async Task Should_return_a_detailed_organisation_model_when_calling_GetAsync()
{
// Arrange
var org = new Organisation
{
Id = OrganisationId.New(),
};
_server
.Given(Request.Create().WithPath(_orgRoute).UsingGet())
.RespondWith(
Response.Create()
.WithSuccess()
.WithHeader("Content-Type", "application/json")
.WithBody(JsonSerializer.Serialize(org, _serializerOptions)));
// Act
var result = await _organisationClient.GetAsync();
// Assert
result.Should().NotBeNull();
result.Id.Should().Be(org.Id);
}
[Test]
public async Task Should_return_a_detailed_organisation_model_when_updating_with_UpdateAsync()
{
// Arrange
var org = new Organisation
{
Id = OrganisationId.New(),
Website = "newWebsite",
};
_server
.Given(Request.Create().WithPath(_orgRoute).UsingPatch())
.RespondWith(
Response.Create()
.WithSuccess()
.WithHeader("Content-Type", "application/json")
.WithBody(JsonSerializer.Serialize(org, _serializerOptions)));
// Act
var result = await _organisationClient.Update().Set(x => x.Website, "newWebsite").ApplyAsync();
// Assert
result.Should().NotBeNull();
result.Website.Should().Be(org.Website);
}
[Test]
public async Task Should_make_a_call_to_api_when_updating_with_UpdateAsync()
{
// Arrange
var org = new Organisation
{
Id = OrganisationId.New(),
Website = "newWebsite",
};
_server
.Given(Request.Create().WithPath(_orgRoute).UsingPatch())
.RespondWith(
Response.Create()
.WithSuccess()
.WithHeader("Content-Type", "application/json")
.WithBody(JsonSerializer.Serialize(org, _serializerOptions)));
// Act
var result = await _organisationClient.Update().Set(x => x.Website, "newWebsite").ApplyAsync();
// Assert
_server.Should().HaveReceivedACall().AtUrl($"{_server.Urls[0]}{_orgRoute}");
}
[Test]
public async Task Should_return_a_list_of_organisation_users_when_calling_GetOrganisationUsersAsync()
{
// Arrange
var orgUsers = new OrganisationUsersTopLevel
{
Users = new List<OrganisationUser>()
{
new OrganisationUser
{
Id = AccountId.New(),
FirstName = "testUser1",
LastName = "lastName1",
},
new OrganisationUser
{
Id = AccountId.New(),
FirstName = "testUser2",
LastName = "lastName2",
},
},
};
_server
.Given(Request.Create().WithPath($"{_orgRoute}/users").UsingGet())
.RespondWith(
Response.Create()
.WithSuccess()
.WithHeader("Content-Type", "application/json")
.WithBody(JsonSerializer.Serialize(orgUsers, _serializerOptions)));
// Act
var result = await _organisationClient.GetOrganisationUsersAsync();
// Assert
result.Count.Should().Be(2);
}
[Test]
public async Task Should_make_a_call_to_api_when_calling_GetOrganisationUsersAsync()
{
// Arrange
var orgUsers = new OrganisationUsersTopLevel
{
Users = new List<OrganisationUser>(),
};
_server
.Given(Request.Create().WithPath($"{_orgRoute}/users").UsingGet())
.RespondWith(
Response.Create()
.WithSuccess()
.WithHeader("Content-Type", "application/json")
.WithBody(JsonSerializer.Serialize(orgUsers, _serializerOptions)));
// Act
var result = await _organisationClient.GetOrganisationUsersAsync();
// Assert
_server.Should().HaveReceivedACall().AtUrl($"{_server.Urls[0]}{_orgRoute}/users");
}
[Test]
public async Task Should_make_a_call_to_api_when_calling_RemoveUserAsync()
{
// Arrange
var accountId = "test";
_server
.Given(Request.Create().WithPath($"{_orgRoute}/users/{accountId}").UsingDelete())
.RespondWith(
Response.Create()
.WithSuccess());
// Act
await _organisationClient.RemoveUserAsync(accountId);
// Assert
_server.Should().HaveReceivedACall().AtUrl($"{_server.Urls[0]}{_orgRoute}/users/{accountId}");
}
[Test]
public async Task Should_return_list_of_pending_invites_when_calling_GetPendingInvitesAsync()
{
// Arrange
var invites = new OrganisationPendingInvites()
{
Invites = new List<OrganisationInvite>
{
new OrganisationInvite { EmailAddress = "testEmail1" },
new OrganisationInvite { EmailAddress = "testEmail2" },
},
};
_server
.Given(Request.Create().WithPath($"{_orgRoute}/invites").UsingGet())
.RespondWith(
Response.Create()
.WithSuccess()
.WithHeader("Content-Type", "application/json")
.WithBody(JsonSerializer.Serialize(invites, _serializerOptions)));
// Act
var result = await _organisationClient.GetPendingInvitesAsync();
// Assert
result.Should().NotBeNull();
result.Count.Should().Be(2);
}
[Test]
public async Task Should_make_a_call_to_api_when_calling_GetPendingInvitesAsync()
{
// Arrange
var invites = new OrganisationPendingInvites()
{
Invites = new List<OrganisationInvite>(),
};
_server
.Given(Request.Create().WithPath($"{_orgRoute}/invites").UsingGet())
.RespondWith(
Response.Create()
.WithSuccess()
.WithHeader("Content-Type", "application/json")
.WithBody(JsonSerializer.Serialize(invites, _serializerOptions)));
// Act
var result = await _organisationClient.GetPendingInvitesAsync();
// Assert
_server.Should().HaveReceivedACall().AtUrl($"{_server.Urls[0]}{_orgRoute}/invites");
}
[Test]
public async Task Should_make_a_call_to_api_when_calling_InviteUserAsync()
{
// Arrange
_server
.Given(Request.Create().WithPath($"{_orgRoute}/invites").UsingPost())
.RespondWith(
Response.Create()
.WithSuccess());
// Act
await _organisationClient.InviteUserAsync("testEmailAddress");
// Assert
_server.Should().HaveReceivedACall().AtUrl($"{_server.Urls[0]}{_orgRoute}/invites");
}
[Test]
public async Task Should_make_a_call_to_api_when_calling_CancelInviteAync()
{
// Arrange
_server
.Given(Request.Create().WithPath($"{_orgRoute}/invites").UsingDelete())
.RespondWith(
Response.Create()
.WithSuccess());
// Act
await _organisationClient.CancelInviteAync("testEmailAddress");
// Assert
_server.Should().HaveReceivedACall().AtUrl($"{_server.Urls[0]}{_orgRoute}/invites");
}
}
| 30.316151 | 105 | 0.591589 | [
"MIT"
] | enclave-networks/Enclave.Sdk.Api | tests/Enclave.Sdk.Api.Tests/Clients/OrganisationClientTests.cs | 8,824 | C# |
using System;
using System.Linq;
namespace _04._Character_Multiplier
{
class Program
{
static void Main(string[] args)
{
string[] input = Console.ReadLine().Split().ToArray();
string firstText = input[0];
string secondText = input[1];
int result = Multiply(firstText, secondText);
Console.WriteLine(result);
}
static int Multiply(string firstText, string secondText)
{
int minLength = Math.Min(firstText.Length, secondText.Length);
int maxLength = Math.Max(firstText.Length, secondText.Length);
int result = 0;
for (int index = 0; index < minLength; index++)
{
result += firstText[index] * secondText[index];
}
for (int index = minLength; index < maxLength; index++)
{
result += firstText.Length > secondText.Length ? firstText[index] : secondText[index];
}
return result;
}
}
}
| 27.153846 | 102 | 0.542965 | [
"MIT"
] | DanielBankov/SoftUni | Programming Fundamentals/Strings and Text Processing - Exercise/04. Character Multiplier/Program.cs | 1,061 | 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void CompareEqual_Vector64_Single()
{
var test = new SimpleBinaryOpTest__CompareEqual_Vector64_Single();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareEqual_Vector64_Single
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Single> _fld1;
public Vector64<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqual_Vector64_Single testClass)
{
var result = AdvSimd.CompareEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareEqual_Vector64_Single testClass)
{
fixed (Vector64<Single>* pFld1 = &_fld1)
fixed (Vector64<Single>* pFld2 = &_fld2)
{
var result = AdvSimd.CompareEqual(
AdvSimd.LoadVector64((Single*)(pFld1)),
AdvSimd.LoadVector64((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector64<Single> _clsVar1;
private static Vector64<Single> _clsVar2;
private Vector64<Single> _fld1;
private Vector64<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareEqual_Vector64_Single()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
}
public SimpleBinaryOpTest__CompareEqual_Vector64_Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.CompareEqual(
Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.CompareEqual(
AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.CompareEqual), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.CompareEqual), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.CompareEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Single>* pClsVar1 = &_clsVar1)
fixed (Vector64<Single>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.CompareEqual(
AdvSimd.LoadVector64((Single*)(pClsVar1)),
AdvSimd.LoadVector64((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr);
var result = AdvSimd.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr));
var result = AdvSimd.CompareEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareEqual_Vector64_Single();
var result = AdvSimd.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareEqual_Vector64_Single();
fixed (Vector64<Single>* pFld1 = &test._fld1)
fixed (Vector64<Single>* pFld2 = &test._fld2)
{
var result = AdvSimd.CompareEqual(
AdvSimd.LoadVector64((Single*)(pFld1)),
AdvSimd.LoadVector64((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.CompareEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Single>* pFld1 = &_fld1)
fixed (Vector64<Single>* pFld2 = &_fld2)
{
var result = AdvSimd.CompareEqual(
AdvSimd.LoadVector64((Single*)(pFld1)),
AdvSimd.LoadVector64((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.CompareEqual(
AdvSimd.LoadVector64((Single*)(&test._fld1)),
AdvSimd.LoadVector64((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Single> op1, Vector64<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(Helpers.CompareEqual(left[i], right[i])) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.CompareEqual)}<Single>(Vector64<Single>, Vector64<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 42.403013 | 188 | 0.587449 | [
"MIT"
] | Davilink/runtime | src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/CompareEqual.Vector64.Single.cs | 22,516 | C# |
namespace Interapp.Web.Infrastructure.Mapping
{
using AutoMapper;
public interface IHaveCustomMappings
{
void CreateMappings(IMapperConfiguration configuration);
}
}
| 19.2 | 64 | 0.734375 | [
"MIT"
] | shunobaka/Interapp | Source/Web/Interapp.Web.Infrastructure/Mapping/IHaveCustomMappings.cs | 194 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _06.Filter_Base
{
class Program
{
static void Main()
{
var input = Console.ReadLine();
var listOfEmployees = new Dictionary<string, List<string>>();
while (input != "filter base")
{
var inputStrings = input.Split(new[] {'-', '>'}, StringSplitOptions.RemoveEmptyEntries);
var key = inputStrings[0].Trim();
var dataToBeSorted = inputStrings[1].Trim();
if (!listOfEmployees.ContainsKey(key))
{
var listOfEmployeeData = MakeList();
listOfEmployees.Add(key, listOfEmployeeData);
}
var newList = NewListOfData(listOfEmployees[key], dataToBeSorted);
listOfEmployees[key] = newList;
input = Console.ReadLine();
}
var filterBase = Console.ReadLine();
PrintData(listOfEmployees, filterBase);
}
private static void PrintData(Dictionary<string, List<string>> listOfEmployees, string filterBase)
{
//0 - age, 1 - salary, 2 - position
if (filterBase == "Age")
{
foreach (var employee in listOfEmployees)
{
if (employee.Value[0] != "-1")
{
Console.WriteLine($"Name: {employee.Key}");
Console.WriteLine($"Age: {employee.Value[0]}");
Console.WriteLine(new string('=', 20));
}
}
}
else if (filterBase == "Salary")
{
foreach (var employee in listOfEmployees)
{
if (employee.Value[1] != "-1")
{
Console.WriteLine($"Name: {employee.Key}");
Console.WriteLine($"Salary: {double.Parse(employee.Value[1]):f2}");
Console.WriteLine(new string('=', 20));
}
}
}
else if (filterBase == "Position")
{
foreach (var employee in listOfEmployees)
{
if (!String.IsNullOrEmpty(employee.Value[2]))
{
Console.WriteLine($"Name: {employee.Key}");
Console.WriteLine($"Position: {employee.Value[2]}");
Console.WriteLine(new string('=', 20));
}
}
}
}
private static List<string> NewListOfData(List<string> employeeData, string dataToBeSorted)
{
var resultedList = new List<string>();
//0 - age, 1 - salary, 2 - position
if (int.TryParse(dataToBeSorted, out var intNumber))
{
resultedList.Add($"{intNumber}");
resultedList.Add(employeeData[1]);
resultedList.Add(employeeData[2]);
}
else if (double.TryParse(dataToBeSorted, out var doubleNumber))
{
resultedList.Add(employeeData[0]);
resultedList.Add($"{doubleNumber}");
resultedList.Add(employeeData[2]);
}
else
{
resultedList.Add(employeeData[0]);
resultedList.Add(employeeData[1]);
resultedList.Add(dataToBeSorted);
}
return resultedList;
}
private static List<string> MakeList()
{
var resultedList = new List<string>();
//0 - age, 1 - salary, 2 - position
resultedList.Add("-1");
resultedList.Add("-1");
resultedList.Add(string.Empty);
return resultedList;
}
}
}
| 34.517241 | 106 | 0.472777 | [
"MIT"
] | pirocorp/CSharp-Fundamentals | 09. Dictionaries - Exercises/06. Filter Base/Filter Base.cs | 4,006 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CrewChiefV3
{
public partial class BooleanPropertyControl : UserControl
{
public String propertyId;
public Boolean defaultValue;
public Boolean originalValue;
public BooleanPropertyControl(String propertyId, String label, Boolean value, Boolean defaultValue, String helpText)
{
InitializeComponent();
this.propertyId = propertyId;
this.originalValue = value;
this.checkBox1.Text = label;
this.checkBox1.Checked = value;
this.defaultValue = defaultValue;
this.toolTip1.SetToolTip(this.checkBox1, helpText);
}
public Boolean getValue()
{
return this.checkBox1.Checked;
}
private void button1_Click(object sender, EventArgs e)
{
this.checkBox1.Checked = defaultValue;
if (this.originalValue != this.checkBox1.Checked)
{
PropertiesForm.hasChanges = true;
}
}
private void checkedChanged(object sender, EventArgs e)
{
if (this.originalValue != this.checkBox1.Checked)
{
PropertiesForm.hasChanges = true;
}
}
}
}
| 29.46 | 124 | 0.600136 | [
"MIT"
] | mrbelowski/r3e_crewchief_v3 | CrewChiefV3/UserInterface/BooleanPropertyControl.cs | 1,475 | C# |
using CovidSafe.Entities.Validation;
using CovidSafe.Entities.Validation.Resources;
namespace CovidSafe.Entities.Protos
{
/// <summary>
/// <see cref="Region"/> partial from generated Protobuf class
/// </summary>
public partial class Region : global::ProtoBuf.IExtensible, IValidatable
{
/// <summary>
/// Maximum allowed precision value;
/// </summary>
public const int MAX_PRECISION = 4;
/// <summary>
/// Minimum allowed precision value
/// </summary>
public const int MIN_PRECISION = 0;
/// <inheritdoc/>
public RequestValidationResult Validate()
{
RequestValidationResult result = new RequestValidationResult();
// Check if lat/lng are in expected values
result.Combine(Validator.ValidateLatitude(this.LatitudePrefix, nameof(this.LatitudePrefix)));
result.Combine(Validator.ValidateLongitude(this.LongitudePrefix, nameof(this.LongitudePrefix)));
// Validate precision
if(this.Precision < MIN_PRECISION || this.Precision > MAX_PRECISION)
{
result.Fail(
RequestValidationIssue.InputInvalid,
nameof(this.Precision),
ValidationMessages.InvalidPrecision,
this.Precision.ToString(),
MIN_PRECISION.ToString(),
MAX_PRECISION.ToString()
);
}
return result;
}
}
}
| 33.608696 | 108 | 0.586028 | [
"MIT"
] | broknfutr/Backend | CovidSafe/CovidSafe.Entities/Protos/Region.cs | 1,548 | C# |
using DCL.Configuration;
using NSubstitute;
using NUnit.Framework;
using UnityEngine.EventSystems;
namespace Tests.BuildModeHUDControllers
{
public class TopActionsButtonsControllerShould
{
private TopActionsButtonsController topActionsButtonsController;
[SetUp]
public void SetUp()
{
topActionsButtonsController = new TopActionsButtonsController();
topActionsButtonsController.Initialize(
Substitute.For<ITopActionsButtonsView>(),
Substitute.For<ITooltipController>());
}
[TearDown]
public void TearDown() { topActionsButtonsController.Dispose(); }
[Test]
public void ClickOnChangeModeCorrectly()
{
// Arrange
bool clicked = false;
topActionsButtonsController.OnChangeModeClick += () => { clicked = true; };
// Act
topActionsButtonsController.ChangeModeClicked();
// Assert
Assert.IsTrue(clicked, "The clicked is false!");
}
[Test]
public void ClickOnExtraCorrectly()
{
// Arrange
bool clicked = false;
topActionsButtonsController.OnExtraClick += () => { clicked = true; };
// Act
topActionsButtonsController.ExtraClicked();
// Assert
Assert.IsTrue(clicked, "The clicked is false!");
}
[Test]
public void ClickOnTranslateCorrectly()
{
// Arrange
bool clicked = false;
topActionsButtonsController.OnTranslateClick += () => { clicked = true; };
// Act
topActionsButtonsController.TranslateClicked();
// Assert
Assert.IsTrue(clicked, "The clicked is false!");
}
[Test]
public void ClickOnRotateCorrectly()
{
// Arrange
bool clicked = false;
topActionsButtonsController.OnRotateClick += () => { clicked = true; };
// Act
topActionsButtonsController.RotateClicked();
// Assert
Assert.IsTrue(clicked, "The clicked is false!");
}
[Test]
public void ClickOnScaleCorrectly()
{
// Arrange
bool clicked = false;
topActionsButtonsController.OnScaleClick += () => { clicked = true; };
// Act
topActionsButtonsController.ScaleClicked();
// Assert
Assert.IsTrue(clicked, "The clicked is false!");
}
[Test]
public void ClickOnUndoCorrectly()
{
// Arrange
bool clicked = false;
topActionsButtonsController.OnUndoClick += () => { clicked = true; };
// Act
topActionsButtonsController.UndoClicked();
// Assert
Assert.IsTrue(clicked, "The clicked is false!");
}
[Test]
public void ClickOnRedoCorrectly()
{
// Arrange
bool clicked = false;
topActionsButtonsController.OnRedoClick += () => { clicked = true; };
// Act
topActionsButtonsController.RedoClicked();
// Assert
Assert.IsTrue(clicked, "The clicked is false!");
}
[Test]
public void ClickOnDuplicateCorrectly()
{
// Arrange
bool clicked = false;
topActionsButtonsController.OnDuplicateClick += () => { clicked = true; };
// Act
topActionsButtonsController.DuplicateClicked();
// Assert
Assert.IsTrue(clicked, "The clicked is false!");
}
[Test]
public void ClickOnDeleteCorrectly()
{
// Arrange
bool clicked = false;
topActionsButtonsController.OnDeleteClick += () => { clicked = true; };
// Act
topActionsButtonsController.DeleteClicked();
// Assert
Assert.IsTrue(clicked, "The clicked is false!");
}
[Test]
public void ShowLogoutConfirmationCorrectly()
{
// Arrange
bool clicked = false;
topActionsButtonsController.OnLogOutClick += () => { clicked = true; };
// Act
topActionsButtonsController.LogoutClicked();
// Assert
Assert.IsTrue(clicked, "The clicked is false!");
}
[Test]
public void ConfirmLogoutCorrectly()
{
// Arrange
bool clicked = false;
topActionsButtonsController.OnLogOutClick += () => { clicked = true; };
// Act
topActionsButtonsController.ConfirmLogout(BuildModeModalType.EXIT);
// Assert
Assert.IsTrue(clicked, "The clicked is false!");
}
[Test]
public void TooltipPointerEnteredCorrectly()
{
// Arrange
BaseEventData testEventData = new BaseEventData(null);
string testText = "Test text";
// Act
topActionsButtonsController.TooltipPointerEntered(testEventData, testText);
// Assert
topActionsButtonsController.tooltipController.Received(1).ShowTooltip(testEventData);
topActionsButtonsController.tooltipController.Received(1).SetTooltipText(testText);
}
[Test]
public void TooltipPointerExitedCorrectly()
{
// Act
topActionsButtonsController.TooltipPointerExited();
// Assert
topActionsButtonsController.tooltipController.Received(1).HideTooltip();
}
[Test]
public void TestSetGizmosActivetedCorrectly()
{
//Arrange
string gizmosActive = BuilderInWorldSettings.TRANSLATE_GIZMO_NAME;
// Act
topActionsButtonsController.SetGizmosActive(gizmosActive);
// Assert
topActionsButtonsController.topActionsButtonsView.Received(1).SetGizmosActive(gizmosActive);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void TestSeActionsInteractable(bool isInteractable)
{
//Act
topActionsButtonsController.SetActionsInteractable(isInteractable);
//Assert
topActionsButtonsController.topActionsButtonsView.Received(1).SetActionsInteractable(isInteractable);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void TestSnapModeChange(bool isActive)
{
//Act
topActionsButtonsController.SetSnapActive(isActive);
//Assert
topActionsButtonsController.topActionsButtonsView.Received(1).SetSnapActive(isActive);
}
}
} | 28.7875 | 113 | 0.561007 | [
"Apache-2.0"
] | 0xBlockchainx0/unity-renderer | unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/HUD/BuildModeHUD/Tests/TopActionsButtonsControllerShould.cs | 6,909 | C# |
using System.Data;
using Shuttle.Core.Data;
namespace Shuttle.Recall.Sql
{
public class ProjectionPositionColumns
{
public static readonly MappedColumn<string> Name = new MappedColumn<string>("Name", DbType.AnsiString, 65);
public static readonly MappedColumn<long> SequenceNumber = new MappedColumn<long>("SequenceNumber", DbType.Int64);
}
} | 31.909091 | 116 | 0.783476 | [
"BSD-3-Clause"
] | Shuttle/Shuttle.Recall.Sql | Shuttle.Recall.Sql/DataAccess/ProjectionPositionColumns.cs | 353 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Leeroy.Json;
using Logos.Git;
using Logos.Git.GitHub;
using Logos.Utility.Logging;
namespace Leeroy
{
public sealed class Overseer
{
public Overseer(CancellationToken token, BuildServerClient buildServerClient, GitHubClient gitHubClient, string user, string repo, string branch)
{
m_token = token;
m_buildServerClient = buildServerClient;
m_gitHubClient = gitHubClient;
m_user = user;
m_repo = repo;
m_branch = branch;
}
public void Run(object obj)
{
m_token.ThrowIfCancellationRequested();
// keep checking for updates
while (!m_token.IsCancellationRequested)
{
if (m_watchers == null)
{
List<BuildProject> projects = LoadConfiguration();
CreateWatchers(projects);
}
string commitId = m_gitHubClient.GetLatestCommitId(m_user, m_repo, m_branch);
if (commitId != m_lastConfigurationCommitId)
{
Log.Info("Configuration repo commit ID has changed from {0} to {1}; reloading configuration.", m_lastConfigurationCommitId, commitId);
// cancel existing work
m_currentConfigurationTokenSource.Cancel();
try
{
Task.WaitAll(m_watchers.ToArray());
}
catch (AggregateException)
{
}
m_currentConfigurationTokenSource.Dispose();
// force configuration to be reloaded
m_watchers = null;
continue;
}
m_token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));
}
}
private List<BuildProject> LoadConfiguration()
{
Log.Info("Getting latest commit for {0}/{1}/{2}.", m_user, m_repo, m_branch);
m_lastConfigurationCommitId = m_gitHubClient.GetLatestCommitId(m_user, m_repo, m_branch);
m_token.ThrowIfCancellationRequested();
Log.Info("Latest commit is {0}; getting details.", m_lastConfigurationCommitId);
GitCommit gitCommit = m_gitHubClient.GetGitCommit(m_user, m_repo, m_lastConfigurationCommitId);
m_token.ThrowIfCancellationRequested();
Log.Debug("Fetching commit tree ({0}).", gitCommit.Tree.Sha);
GitTree tree = m_gitHubClient.GetTree(gitCommit);
m_token.ThrowIfCancellationRequested();
Log.Debug("Tree has {0} items:", tree.Items.Length);
foreach (GitTreeItem item in tree.Items)
Log.Debug(item.Path);
object buildProjectsLock = new object();
List<BuildProject> buildProjects = new List<BuildProject>();
Dictionary<string, string> buildRepoBranches = new Dictionary<string, string>();
Parallel.ForEach(tree.Items.Where(x => x.Type == "blob" && x.Path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)), item =>
{
GitBlob blob = m_gitHubClient.GetBlob(item);
BuildProject buildProject;
try
{
buildProject = JsonUtility.FromJson<BuildProject>(blob.GetContent());
}
catch (FormatException ex)
{
Log.Error("Couldn't parse '{0}': {1}", ex, item.Path, ex.Message);
return;
}
buildProject.Name = Path.GetFileNameWithoutExtension(item.Path);
if (buildProject.Disabled)
{
Log.Info("Ignoring disabled build project: {0}", buildProject.Name);
return;
}
if (buildProject.Submodules != null && buildProject.SubmoduleBranches != null)
{
Log.Error("Cannot specify both 'submodules' and 'submoduleBranches' in {0}.", buildProject.Name);
return;
}
string existingProjectName;
lock (buildProjectsLock)
{
string buildRepoBranch = buildProject.RepoUrl + "/" + buildProject.Branch;
if (!buildRepoBranches.TryGetValue(buildRepoBranch, out existingProjectName))
buildRepoBranches.Add(buildRepoBranch, buildProject.Name);
}
if (existingProjectName != null)
{
Log.Error("Project '{0}' is using the same build repo branch ({1}, {2}) as '{3}'; ignoring this project.", buildProject.Name, buildProject.RepoUrl, buildProject.Branch, existingProjectName);
// disable the existing project, too; we don't know which one is correct and don't want spurious build commits to be pushed
lock (buildProjectsLock)
if (buildProjects.RemoveAll(x => x.Name == existingProjectName) != 0)
Log.Error("Project '{0}' is using the same build repo branch ({1}, {2}) as '{3}'; ignoring this project.", existingProjectName, buildProject.RepoUrl, buildProject.Branch, buildProject.Name);
return;
}
lock (buildProjectsLock)
buildProjects.Add(buildProject);
Log.Info("Added build project: {0}", buildProject.Name);
});
return buildProjects;
}
private void CreateWatchers(IEnumerable<BuildProject> projects)
{
// create a new cancellation token for all the monitors about to be created
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationTokenSource linkedSource = CancellationTokenSource.CreateLinkedTokenSource(m_token, tokenSource.Token);
CancellationToken linkedToken = linkedSource.Token;
// create a watcher for each project
List<Task> watchers = new List<Task>();
foreach (BuildProject project in projects)
{
Watcher watcher = new Watcher(project, m_buildServerClient, m_gitHubClient, linkedToken);
watchers.Add(watcher.CreateTask());
}
m_currentConfigurationTokenSource = tokenSource;
m_watchers = watchers;
}
readonly CancellationToken m_token;
readonly BuildServerClient m_buildServerClient;
readonly GitHubClient m_gitHubClient;
readonly string m_user;
readonly string m_repo;
readonly string m_branch;
string m_lastConfigurationCommitId;
CancellationTokenSource m_currentConfigurationTokenSource;
List<Task> m_watchers;
static readonly Logger Log = LogManager.GetLogger("Overseer");
}
}
| 31.744444 | 197 | 0.721036 | [
"MIT"
] | LogosBible/Leeroy | src/Leeroy/Overseer.cs | 5,716 | C# |
namespace ApiaryDiary.Controllers
{
using ApiaryDiary.Controllers.Models.Locations;
using ApiaryDiary.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
public class LocationsController : Controller
{
private readonly ILocationInfoService locationInfoService;
private readonly IApiaryService apiaryService;
private readonly UserManager<IdentityUser> userManager;
public LocationsController(
ILocationInfoService locationInfoService,
IApiaryService apiaryService,
UserManager<IdentityUser> userManager)
{
this.locationInfoService = locationInfoService;
this.apiaryService = apiaryService;
this.userManager = userManager;
}
public IActionResult Create()
{
var userId = this.userManager.GetUserId(this.User);
var model = new AddLocationPostModel()
{
AllApairies = this.apiaryService.GetAll(userId),
};
return this.View(model);
}
[HttpPost]
public async Task<IActionResult> Create(AddLocationPostModel input)
{
var userId = this.userManager.GetUserId(this.User);
var apiaryId = input.SelectedApiary;
if (ModelState.IsValid == false)
{
input.AllApairies = this.apiaryService.GetAll(userId);
return this.View(input);
}
await this.locationInfoService.CreateDetailedAsync(
apiaryId, input.Settlement, input.Altitude, input.HasHoneyPlants, input.Description);
return this.RedirectToAction(nameof(ViewAll));
}
public async Task<IActionResult> Delete(int id)
{
if (this.ModelState.IsValid == false)
{
return this.NotFound();
}
await this.locationInfoService.DeleteAsync(id);
return this.RedirectToAction(nameof(ViewAll));
}
public IActionResult Edit(int id)
{
var location = this.locationInfoService.FindById(id);
if (location == null)
{
return this.NotFound();
}
var viewModel = new EditLocationPostModel
{
Id = location.Id,
Settlement = location.Settlement,
Altitude = location.Altitude,
Description = location.Description,
};
return this.View(viewModel);
}
[HttpPost]
public async Task<IActionResult> Edit(EditLocationPostModel input)
{
if (this.ModelState.IsValid == false)
{
return this.View(input);
}
await this.locationInfoService.EditAsync
(input.Id, input.Settlement, input.Altitude, input.Description);
return this.RedirectToAction(nameof(ViewAll));
}
public async Task<IActionResult> ViewAll()
{
var viewModel = new LocationsListingViewModel();
var allLocations = await this.locationInfoService.ViewAll();
viewModel.Locations = allLocations;
return this.View(viewModel);
}
}
}
| 29.578947 | 101 | 0.58363 | [
"MIT"
] | DeniPanov/ASP.NET-CORE-Web-App | ASP.NET-CORE-Web-App/ApiaryDiary.Controllers/LocationsController.cs | 3,374 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ssm-2014-11-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.SimpleSystemsManagement.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SimpleSystemsManagement.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for InvalidActivationIdException Object
/// </summary>
public class InvalidActivationIdExceptionUnmarshaller : IErrorResponseUnmarshaller<InvalidActivationIdException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public InvalidActivationIdException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public InvalidActivationIdException Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse)
{
context.Read();
InvalidActivationIdException unmarshalledObject = new InvalidActivationIdException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
}
return unmarshalledObject;
}
private static InvalidActivationIdExceptionUnmarshaller _instance = new InvalidActivationIdExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static InvalidActivationIdExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.141176 | 147 | 0.680664 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/SimpleSystemsManagement/Generated/Model/Internal/MarshallTransformations/InvalidActivationIdExceptionUnmarshaller.cs | 3,072 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the servicecatalog-appregistry-2020-06-24.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.AppRegistry.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.AppRegistry.Model.Internal.MarshallTransformations
{
/// <summary>
/// AssociateAttributeGroup Request Marshaller
/// </summary>
public class AssociateAttributeGroupRequestMarshaller : IMarshaller<IRequest, AssociateAttributeGroupRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((AssociateAttributeGroupRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(AssociateAttributeGroupRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.AppRegistry");
request.Headers["Content-Type"] = "application/json";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2020-06-24";
request.HttpMethod = "PUT";
if (!publicRequest.IsSetApplication())
throw new AmazonAppRegistryException("Request object does not have required field Application set");
request.AddPathResource("{application}", StringUtils.FromString(publicRequest.Application));
if (!publicRequest.IsSetAttributeGroup())
throw new AmazonAppRegistryException("Request object does not have required field AttributeGroup set");
request.AddPathResource("{attributeGroup}", StringUtils.FromString(publicRequest.AttributeGroup));
request.ResourcePath = "/applications/{application}/attribute-groups/{attributeGroup}";
request.MarshallerVersion = 2;
return request;
}
private static AssociateAttributeGroupRequestMarshaller _instance = new AssociateAttributeGroupRequestMarshaller();
internal static AssociateAttributeGroupRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static AssociateAttributeGroupRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.619565 | 162 | 0.65679 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/AppRegistry/Generated/Model/Internal/MarshallTransformations/AssociateAttributeGroupRequestMarshaller.cs | 3,645 | C# |
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json;
namespace BigCommerceSharp.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class Meta1 {
/// <summary>
/// Gets or Sets Meta
/// </summary>
[DataMember(Name="meta", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "meta")]
public Pagination1 Meta { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class Meta1 {\n");
sb.Append(" Meta: ").Append(Meta).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
}
| 24.761905 | 68 | 0.620192 | [
"MIT"
] | PrimePenguin/BigCommerceSharp | BigCommerceSharp/Model/Meta1.cs | 1,040 | C# |
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Anabi.DataAccess.Ef.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
ParentId = table.Column<int>(nullable: true),
Code = table.Column<string>(maxLength: 50, nullable: false),
Description = table.Column<string>(maxLength: 2000, nullable: true),
ForEntity = table.Column<string>(maxLength: 20, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.Id);
table.ForeignKey(
name: "FK_Categories_Parent",
column: x => x.ParentId,
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Counties",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
Name = table.Column<string>(maxLength: 50, nullable: false),
Abreviation = table.Column<string>(maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Counties", x => x.Id);
});
migrationBuilder.CreateTable(
name: "CrimeTypes",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
CrimeName = table.Column<string>(maxLength: 400, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CrimeTypes", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Decisions",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
Name = table.Column<string>(maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Decisions", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Identifiers",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
IdentifierType = table.Column<string>(maxLength: 50, nullable: false),
IsForPerson = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Identifiers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PrecautionaryMeasures",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
Name = table.Column<string>(maxLength: 100, nullable: false),
Code = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PrecautionaryMeasures", x => x.Id);
});
migrationBuilder.CreateTable(
name: "RecoveryBeneficiaries",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
Name = table.Column<string>(maxLength: 200, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RecoveryBeneficiaries", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Stages",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
Name = table.Column<string>(maxLength: 50, nullable: false),
StageCategory = table.Column<int>(nullable: true),
Description = table.Column<string>(nullable: true),
IsFinal = table.Column<bool>(nullable: false),
ParentId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Stages", x => x.Id);
table.ForeignKey(
name: "FK_Stages_Stages_ParentId",
column: x => x.ParentId,
principalTable: "Stages",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCode = table.Column<string>(maxLength: 20, nullable: false),
Password = table.Column<string>(type: "varchar(8000)", nullable: false),
Salt = table.Column<string>(type: "varchar(8000)", nullable: false),
Email = table.Column<string>(maxLength: 100, nullable: false),
Name = table.Column<string>(maxLength: 100, nullable: false),
Role = table.Column<string>(maxLength: 5000, nullable: false),
IsActive = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Addresses",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false),
LastChangeDate = table.Column<DateTime>(nullable: true),
CountyId = table.Column<int>(nullable: false),
Street = table.Column<string>(maxLength: 100, nullable: false),
City = table.Column<string>(maxLength: 30, nullable: true),
Building = table.Column<string>(maxLength: 10, nullable: true),
Description = table.Column<string>(maxLength: 300, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Addresses", x => x.Id);
table.ForeignKey(
name: "FK_Addresses_Counties",
column: x => x.CountyId,
principalTable: "Counties",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Assets",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
Name = table.Column<string>(maxLength: 100, nullable: false),
AddressId = table.Column<int>(nullable: true),
CategoryId = table.Column<int>(nullable: false),
Description = table.Column<string>(maxLength: 2000, nullable: true),
DecisionId = table.Column<int>(nullable: true),
Identifier = table.Column<string>(maxLength: 100, nullable: true),
NecessaryVolume = table.Column<decimal>(type: "decimal(20, 2)", nullable: true),
IsDeleted = table.Column<bool>(nullable: false),
NrOfObjects = table.Column<int>(nullable: true),
MeasureUnit = table.Column<string>(maxLength: 10, nullable: true),
Remarks = table.Column<string>(maxLength: 2000, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Assets", x => x.Id);
table.ForeignKey(
name: "FK_Assets_Addresses",
column: x => x.AddressId,
principalTable: "Addresses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Assets_Categories",
column: x => x.CategoryId,
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Assets_Decisions",
column: x => x.DecisionId,
principalTable: "Decisions",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Institutions",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
CategoryId = table.Column<int>(nullable: false),
Name = table.Column<string>(maxLength: 50, nullable: false),
ContactData = table.Column<string>(type: "varchar(8000)", nullable: true),
AddressDbId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Institutions", x => x.Id);
table.ForeignKey(
name: "FK_Institutions_Addresses_AddressDbId",
column: x => x.AddressDbId,
principalTable: "Addresses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Institutions_Categories",
column: x => x.CategoryId,
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Persons",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
AddressId = table.Column<int>(nullable: true),
Name = table.Column<string>(maxLength: 200, nullable: false),
Identification = table.Column<string>(maxLength: 20, nullable: false),
IdSerie = table.Column<string>(maxLength: 2, nullable: true),
IdNumber = table.Column<string>(maxLength: 6, nullable: true),
IsPerson = table.Column<bool>(nullable: false),
Birthdate = table.Column<DateTime>(nullable: true),
Nationality = table.Column<string>(maxLength: 20, nullable: true),
FirstName = table.Column<string>(maxLength: 50, nullable: true),
IdentifierId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Persons", x => x.Id);
table.ForeignKey(
name: "FK_Persons_Addresses",
column: x => x.AddressId,
principalTable: "Addresses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Persons_Identifiers",
column: x => x.IdentifierId,
principalTable: "Identifiers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "StorageSpaces",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
AddressId = table.Column<int>(nullable: false),
Name = table.Column<string>(maxLength: 200, nullable: false),
StorageSpacesType = table.Column<int>(nullable: false),
Description = table.Column<string>(maxLength: 2000, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_StorageSpaces", x => x.Id);
table.ForeignKey(
name: "FK_StorageSpaces_Addresses",
column: x => x.AddressId,
principalTable: "Addresses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "AssetDefendants",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
AssetId = table.Column<int>(nullable: false),
PersonId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AssetDefendants", x => x.Id);
table.ForeignKey(
name: "FK_Assets_AssetDefendant",
column: x => x.AssetId,
principalTable: "Assets",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Person_AssetDefendant",
column: x => x.PersonId,
principalTable: "Persons",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "HistoricalStages",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
AssetId = table.Column<int>(nullable: false),
StageId = table.Column<int>(nullable: false),
DecizieId = table.Column<int>(nullable: true),
InstitutionId = table.Column<int>(nullable: true),
EstimatedAmount = table.Column<decimal>(type: "Decimal(20,2)", nullable: true),
EstimatedAmountCurrency = table.Column<string>(maxLength: 3, nullable: true),
AssetState = table.Column<string>(maxLength: 100, nullable: true),
OwnerId = table.Column<int>(type: "Int", nullable: true),
ActualValue = table.Column<decimal>(type: "Decimal(20, 2)", nullable: true),
ActualValueCurrency = table.Column<string>(maxLength: 3, nullable: true),
LegalBasis = table.Column<string>(maxLength: 200, nullable: true),
DecisionNumber = table.Column<string>(maxLength: 50, nullable: true),
DecisionDate = table.Column<DateTime>(type: "Date", nullable: false),
Source = table.Column<string>(maxLength: 500, nullable: true),
SentOnEmail = table.Column<bool>(nullable: true),
FileNumber = table.Column<string>(maxLength: 200, nullable: true),
FileNumberParquet = table.Column<string>(maxLength: 200, nullable: true),
ReceivingDate = table.Column<DateTime>(nullable: true),
DefinitiveDate = table.Column<DateTime>(nullable: true),
SendToAuthoritiesDate = table.Column<DateTime>(nullable: true),
IsDefinitive = table.Column<bool>(nullable: true),
CrimeTypeId = table.Column<int>(nullable: true),
PrecautionaryMeasureId = table.Column<int>(nullable: true),
RecoveryBeneficiaryId = table.Column<int>(nullable: true),
RecoveryState = table.Column<string>(nullable: true),
EvaluationCommitteeDesignationDate = table.Column<DateTime>(nullable: true),
EvaluationCommitteePresident = table.Column<string>(maxLength: 200, nullable: true),
EvaluationCommittee = table.Column<string>(nullable: true),
RecoveryCommitteeDesignationDate = table.Column<DateTime>(nullable: true),
RecoveryCommitteePresident = table.Column<string>(maxLength: 200, nullable: true),
RecoveryCommittee = table.Column<string>(nullable: true),
LastActivity = table.Column<DateTime>(nullable: true),
PersonResponsible = table.Column<string>(maxLength: 200, nullable: true),
RecoveryApplicationNumber = table.Column<string>(maxLength: 100, nullable: true),
RecoveryApplicationDate = table.Column<DateTime>(nullable: true),
RecoveryDocumentType = table.Column<int>(nullable: true),
RecoveryIssuingInstitution = table.Column<string>(maxLength: 200, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_HistoricalStages", x => x.Id);
table.ForeignKey(
name: "FK_HistoricalStages_Assets",
column: x => x.AssetId,
principalTable: "Assets",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_HistoricalStages_CrimeTypes_CrimeTypeId",
column: x => x.CrimeTypeId,
principalTable: "CrimeTypes",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_HistoricalStages_Decisions",
column: x => x.DecizieId,
principalTable: "Decisions",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_HistoricalStages_Institutions",
column: x => x.InstitutionId,
principalTable: "Institutions",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_OwnerId",
column: x => x.OwnerId,
principalTable: "Persons",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_HistoricalStages_PrecautionaryMeasures_PrecautionaryMeasureId",
column: x => x.PrecautionaryMeasureId,
principalTable: "PrecautionaryMeasures",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_HistoricalStages_RecoveryBeneficiaries_RecoveryBeneficiaryId",
column: x => x.RecoveryBeneficiaryId,
principalTable: "RecoveryBeneficiaries",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_HistoricalStages_Stages",
column: x => x.StageId,
principalTable: "Stages",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "AssetStorageSpaces",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserCodeAdd = table.Column<string>(maxLength: 20, nullable: false),
UserCodeLastChange = table.Column<string>(maxLength: 20, nullable: true),
AddedDate = table.Column<DateTime>(nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"),
LastChangeDate = table.Column<DateTime>(nullable: true),
AssetId = table.Column<int>(nullable: false),
StorageSpaceId = table.Column<int>(nullable: false),
EntryDate = table.Column<DateTime>(nullable: false),
ExitDate = table.Column<DateTime>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AssetStorageSpaces", x => x.Id);
table.ForeignKey(
name: "FK_AssetsStorageSpaces_Assets",
column: x => x.AssetId,
principalTable: "Assets",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_AssetsStorageSpaces_StorageSpaces",
column: x => x.StorageSpaceId,
principalTable: "StorageSpaces",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Addresses_CountyId",
table: "Addresses",
column: "CountyId");
migrationBuilder.CreateIndex(
name: "IX_AssetDefendants_AssetId",
table: "AssetDefendants",
column: "AssetId");
migrationBuilder.CreateIndex(
name: "IX_AssetDefendants_PersonId",
table: "AssetDefendants",
column: "PersonId");
migrationBuilder.CreateIndex(
name: "IX_Assets_AddressId",
table: "Assets",
column: "AddressId");
migrationBuilder.CreateIndex(
name: "IX_Assets_CategoryId",
table: "Assets",
column: "CategoryId");
migrationBuilder.CreateIndex(
name: "IX_Assets_DecisionId",
table: "Assets",
column: "DecisionId");
migrationBuilder.CreateIndex(
name: "IX_AssetStorageSpaces_AssetId",
table: "AssetStorageSpaces",
column: "AssetId");
migrationBuilder.CreateIndex(
name: "IX_AssetStorageSpaces_StorageSpaceId",
table: "AssetStorageSpaces",
column: "StorageSpaceId");
migrationBuilder.CreateIndex(
name: "IX_Categories_ParentId",
table: "Categories",
column: "ParentId");
migrationBuilder.CreateIndex(
name: "indx_code_forentity",
table: "Categories",
columns: new[] { "Code", "ForEntity" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Counties_Abreviation",
table: "Counties",
column: "Abreviation",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_CrimeTypes_CrimeName",
table: "CrimeTypes",
column: "CrimeName",
unique: true);
migrationBuilder.CreateIndex(
name: "indx_uq_Decision",
table: "Decisions",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_HistoricalStages_AssetId",
table: "HistoricalStages",
column: "AssetId");
migrationBuilder.CreateIndex(
name: "IX_HistoricalStages_CrimeTypeId",
table: "HistoricalStages",
column: "CrimeTypeId");
migrationBuilder.CreateIndex(
name: "IX_HistoricalStages_DecizieId",
table: "HistoricalStages",
column: "DecizieId");
migrationBuilder.CreateIndex(
name: "IX_HistoricalStages_InstitutionId",
table: "HistoricalStages",
column: "InstitutionId");
migrationBuilder.CreateIndex(
name: "IX_HistoricalStages_OwnerId",
table: "HistoricalStages",
column: "OwnerId");
migrationBuilder.CreateIndex(
name: "IX_HistoricalStages_PrecautionaryMeasureId",
table: "HistoricalStages",
column: "PrecautionaryMeasureId");
migrationBuilder.CreateIndex(
name: "IX_HistoricalStages_RecoveryBeneficiaryId",
table: "HistoricalStages",
column: "RecoveryBeneficiaryId");
migrationBuilder.CreateIndex(
name: "IX_HistoricalStages_StageId",
table: "HistoricalStages",
column: "StageId");
migrationBuilder.CreateIndex(
name: "IX_Institutions_AddressDbId",
table: "Institutions",
column: "AddressDbId");
migrationBuilder.CreateIndex(
name: "IX_Institutions_CategoryId",
table: "Institutions",
column: "CategoryId");
migrationBuilder.CreateIndex(
name: "IX_Persons_AddressId",
table: "Persons",
column: "AddressId");
migrationBuilder.CreateIndex(
name: "indx_uq_Persons",
table: "Persons",
column: "Identification",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Persons_IdentifierId",
table: "Persons",
column: "IdentifierId");
migrationBuilder.CreateIndex(
name: "uq_RecoveryBeneficiaryName",
table: "RecoveryBeneficiaries",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "indx_uq_stagename",
table: "Stages",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Stages_ParentId",
table: "Stages",
column: "ParentId");
migrationBuilder.CreateIndex(
name: "IX_StorageSpaces_AddressId",
table: "StorageSpaces",
column: "AddressId",
unique: true);
migrationBuilder.CreateIndex(
name: "uq_StorageSpaceName",
table: "StorageSpaces",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Users_Email",
table: "Users",
column: "Email",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Users_UserCode",
table: "Users",
column: "UserCode",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AssetDefendants");
migrationBuilder.DropTable(
name: "AssetStorageSpaces");
migrationBuilder.DropTable(
name: "HistoricalStages");
migrationBuilder.DropTable(
name: "Users");
migrationBuilder.DropTable(
name: "StorageSpaces");
migrationBuilder.DropTable(
name: "Assets");
migrationBuilder.DropTable(
name: "CrimeTypes");
migrationBuilder.DropTable(
name: "Institutions");
migrationBuilder.DropTable(
name: "Persons");
migrationBuilder.DropTable(
name: "PrecautionaryMeasures");
migrationBuilder.DropTable(
name: "RecoveryBeneficiaries");
migrationBuilder.DropTable(
name: "Stages");
migrationBuilder.DropTable(
name: "Decisions");
migrationBuilder.DropTable(
name: "Categories");
migrationBuilder.DropTable(
name: "Addresses");
migrationBuilder.DropTable(
name: "Identifiers");
migrationBuilder.DropTable(
name: "Counties");
}
}
}
| 49.633822 | 122 | 0.518578 | [
"MPL-2.0"
] | bioan/anabi-gestiune-api | Anabi.DataAccess.Ef/Migrations/20190417131136_InitialCreate.cs | 37,277 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 02.05.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.LessThan.Complete.NullableInt64.SByte{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Nullable<System.Int64>;
using T_DATA2 =System.SByte;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__03__NV
public static class TestSet_504__param__03__NV
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001
//-----------------------------------------------------------------------
[Test]
public static void Test_002()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ < /*}OP*/ vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002
};//class TestSet_504__param__03__NV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.LessThan.Complete.NullableInt64.SByte
| 27.708333 | 135 | 0.532632 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/LessThan/Complete/NullableInt64/SByte/TestSet_504__param__03__NV.cs | 3,327 | 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 snowball-2016-06-30.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Snowball.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Snowball.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribeJob operation
/// </summary>
public class DescribeJobResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DescribeJobResponse response = new DescribeJobResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("JobMetadata", targetDepth))
{
var unmarshaller = JobMetadataUnmarshaller.Instance;
response.JobMetadata = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("SubJobMetadata", targetDepth))
{
var unmarshaller = new ListUnmarshaller<JobMetadata, JobMetadataUnmarshaller>(JobMetadataUnmarshaller.Instance);
response.SubJobMetadata = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidResourceException"))
{
return new InvalidResourceException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonSnowballException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static DescribeJobResponseUnmarshaller _instance = new DescribeJobResponseUnmarshaller();
internal static DescribeJobResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeJobResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.551402 | 168 | 0.648581 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/Snowball/Generated/Model/Internal/MarshallTransformations/DescribeJobResponseUnmarshaller.cs | 4,018 | 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.Linq;
using Paragon.Plugins;
using Paragon.Runtime.Annotations;
using Paragon.Runtime.Kernel.Windowing;
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Threading;
namespace Paragon.Runtime.Kernel.Plugins
{
/// <summary>
/// This class implements the paragon.app.window part of the Kernel.
/// Should be instantiated once per application. Creates related browser windows and co-ordinates them being in workspaces.
/// </summary>
[JavaScriptPlugin(Name = "paragon.app.window", IsBrowserSide = true)]
public class ParagonAppWindowPlugin : ParagonPlugin
{
private static readonly ILogger Logger = ParagonLogManager.GetLogger();
/// <summary>
/// The size and position of a window can be specified in a number of different ways.
/// The most simple option is not specifying anything at all, in which case a default size and platform dependent position will be used.
///
/// To set the position, size and constraints of the window, use the innerBounds or outerBounds properties.
/// Inner bounds do not include window decorations. Outer bounds include the window's title bar and frame.
/// Note that the padding between the inner and outer bounds is determined by the OS.
/// Therefore setting the same property for both inner and outer bounds is considered an error
/// (for example, setting both innerBounds.left and outerBounds.left).
///
/// To automatically remember the positions of windows you can give them ids.
/// If a window has an id, This id is used to remember the size and position of the window whenever it is moved or resized.
/// This size and position is then used instead of the specified bounds on subsequent opening of a window with the same id.
/// If you need to open a window with an id at a location other than the remembered default, you can create it hidden,
/// move it to the desired location, then show it.
/// </summary>
/// <param name="startUrl"></param>
/// <param name="options">
/// OPTIONAL.
/// </param>
/// <param name="callback">
/// OPTIONAL.
///
/// Called in the creating window (parent) before the load event is called in the created window (child).
/// The parent can set fields or functions on the child usable from onload. E.g. background.js:
///
/// function(createdWindow) { createdWindow.contentWindow.foo = function () { }; };
///
/// window.js:
///
/// window.onload = function () { foo(); }
///
/// If you specify the callback parameter, it should be a function that looks like this:
///
/// function(AppWindow createdWindow) {...};
/// </param>
[JavaScriptPluginMember, UsedImplicitly]
public void Create(string startUrl, CreateWindowOptions options, JavaScriptPluginCallback callback)
{
if (Application.RefreshUrl != null)
{
startUrl = Application.RefreshUrl;
}
else
{
//Check for single user config.
RegistryKey symphony = Registry.CurrentUser.OpenSubKey("Software\\" + Application.Name + "\\" + Application.Name);
if (symphony == null) {
//check for all users config
symphony = Registry.LocalMachine.OpenSubKey("Software\\" + Application.Name + "\\" + Application.Name);
}
if (symphony != null)
{
String podUrl = (string)symphony.GetValue("PodUrl", "");
Uri uri;
if (Uri.TryCreate(podUrl, UriKind.Absolute, out uri) && uri.Scheme == Uri.UriSchemeHttps)
{
startUrl = uri.ToString();
Logger.Info(string.Format("PodUrl at Registry key : {0}", startUrl));
}
}
}
Logger.Info(string.Format("Create window : {0}", startUrl));
var windowManager = Application.WindowManager as IApplicationWindowManagerEx;
if (windowManager != null)
{
windowManager.CreateWindow(new CreateWindowRequest(startUrl, options, callback));
}
}
/// <summary>
/// Returns an AppWindow object for the current script context (ie JavaScript 'window' object).
/// This can also be called on a handle to a script context for another page, for example: otherWindow.chrome.app.window.current().
/// </summary>
/// <returns></returns>
[JavaScriptPluginMember, UsedImplicitly]
public IApplicationWindow GetCurrent()
{
Logger.Debug("GetCurrent");
var windowManager = Application.WindowManager;
if (windowManager != null)
{
var browserId = PluginExecutionContext.BrowserIdentifier;
return windowManager.AllWindows.FirstOrDefault(window => window.ContainsBrowser(browserId));
}
return null;
}
/// <summary>
/// Gets an array of all currently created app windows.
/// </summary>
/// <returns></returns>
[JavaScriptPluginMember, UsedImplicitly]
public IApplicationWindow[] GetAll()
{
Logger.Debug("GetAll");
var windowManager = Application.WindowManager;
return windowManager != null ? windowManager.AllWindows : new IApplicationWindow[0];
}
/// <summary>
/// Gets an AppWindow with the given id. If no window with the given id exists null is returned.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[JavaScriptPluginMember, UsedImplicitly]
public IApplicationWindow GetById(string id)
{
Logger.Debug("GetById");
var windowManager = Application.WindowManager;
return windowManager != null ? windowManager.AllWindows.FirstOrDefault(window => window.GetId() == id) : null;
}
}
} | 46.407895 | 144 | 0.620783 | [
"Apache-2.0"
] | mcleo-d/SFE-Minuet-DesktopClient | minuet/Paragon.Runtime/Kernel/Plugins/ParagonAppWindowPlugin.cs | 7,056 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using System.Collections.ObjectModel;
namespace TrivMonkey
{
public partial class CreditsPage : PhoneApplicationPage
{
public CreditsPage()
{
InitializeComponent();
DataContext = App.ViewModel;
}
}
} | 20.259259 | 59 | 0.687386 | [
"MIT"
] | chuvidi2003/TrivMonkey | trivmonkey/CreditsPage.xaml.cs | 549 | C# |
using UnityEngine;
public class MenuController : MonoBehaviour
{
public LevelLoader levelLoader;
public Canvas creditsPanel;
public Canvas controlsPanel;
private void OnDestroy()
{
AkSoundEngine.PostEvent("MainMenu_Stop", gameObject);
}
private void Start()
{
AkSoundEngine.PostEvent("MainMenu_Start", gameObject);
creditsPanel.enabled = false;
controlsPanel.enabled = false;
}
public void StartGame()
{
AkSoundEngine.PostEvent("MenuItemClick", gameObject);
controlsPanel.enabled = false;
creditsPanel.enabled = false;
levelLoader.LoadNextLevel();
}
public void CloseGame()
{
controlsPanel.enabled = false;
creditsPanel.enabled = false;
Application.Quit();
}
public void OpenCredits()
{
AkSoundEngine.PostEvent("MenuItemClick", gameObject);
controlsPanel.enabled = false;
creditsPanel.enabled = true;
}
public void OpenControls()
{
AkSoundEngine.PostEvent("MenuItemClick", gameObject);
creditsPanel.enabled = false;
controlsPanel.enabled = true;
}
public void CloseCredits()
{
AkSoundEngine.PostEvent("MenuItemClick", gameObject);
creditsPanel.enabled = false;
}
public void CloseControls()
{
AkSoundEngine.PostEvent("MenuItemClick", gameObject);
controlsPanel.enabled = false;
}
}
| 23.31746 | 62 | 0.639891 | [
"MIT"
] | litelawliet/BrackeysJam2021 | BrackeysJam2021/Assets/Scripts/Menus/MenuController.cs | 1,471 | 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.AwsNative.MediaConnect
{
/// <summary>
/// Resource schema for AWS::MediaConnect::FlowVpcInterface
/// </summary>
[AwsNativeResourceType("aws-native:mediaconnect:FlowVpcInterface")]
public partial class FlowVpcInterface : Pulumi.CustomResource
{
/// <summary>
/// The Amazon Resource Name (ARN), a unique identifier for any AWS resource, of the flow.
/// </summary>
[Output("flowArn")]
public Output<string> FlowArn { get; private set; } = null!;
/// <summary>
/// Immutable and has to be a unique against other VpcInterfaces in this Flow.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// IDs of the network interfaces created in customer's account by MediaConnect.
/// </summary>
[Output("networkInterfaceIds")]
public Output<ImmutableArray<string>> NetworkInterfaceIds { get; private set; } = null!;
/// <summary>
/// Role Arn MediaConnect can assumes to create ENIs in customer's account.
/// </summary>
[Output("roleArn")]
public Output<string> RoleArn { get; private set; } = null!;
/// <summary>
/// Security Group IDs to be used on ENI.
/// </summary>
[Output("securityGroupIds")]
public Output<ImmutableArray<string>> SecurityGroupIds { get; private set; } = null!;
/// <summary>
/// Subnet must be in the AZ of the Flow
/// </summary>
[Output("subnetId")]
public Output<string> SubnetId { get; private set; } = null!;
/// <summary>
/// Create a FlowVpcInterface 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 FlowVpcInterface(string name, FlowVpcInterfaceArgs args, CustomResourceOptions? options = null)
: base("aws-native:mediaconnect:FlowVpcInterface", name, args ?? new FlowVpcInterfaceArgs(), MakeResourceOptions(options, ""))
{
}
private FlowVpcInterface(string name, Input<string> id, CustomResourceOptions? options = null)
: base("aws-native:mediaconnect:FlowVpcInterface", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing FlowVpcInterface 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 FlowVpcInterface Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new FlowVpcInterface(name, id, options);
}
}
public sealed class FlowVpcInterfaceArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The Amazon Resource Name (ARN), a unique identifier for any AWS resource, of the flow.
/// </summary>
[Input("flowArn", required: true)]
public Input<string> FlowArn { get; set; } = null!;
/// <summary>
/// Immutable and has to be a unique against other VpcInterfaces in this Flow.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Role Arn MediaConnect can assumes to create ENIs in customer's account.
/// </summary>
[Input("roleArn", required: true)]
public Input<string> RoleArn { get; set; } = null!;
[Input("securityGroupIds", required: true)]
private InputList<string>? _securityGroupIds;
/// <summary>
/// Security Group IDs to be used on ENI.
/// </summary>
public InputList<string> SecurityGroupIds
{
get => _securityGroupIds ?? (_securityGroupIds = new InputList<string>());
set => _securityGroupIds = value;
}
/// <summary>
/// Subnet must be in the AZ of the Flow
/// </summary>
[Input("subnetId", required: true)]
public Input<string> SubnetId { get; set; } = null!;
public FlowVpcInterfaceArgs()
{
}
}
}
| 39.428571 | 138 | 0.607609 | [
"Apache-2.0"
] | AaronFriel/pulumi-aws-native | sdk/dotnet/MediaConnect/FlowVpcInterface.cs | 5,520 | C# |
namespace NEFBDAACommons.Shared.Models
{
public enum DataExportTypeEnum
{
CSV, EXCEL, PDF
}
}
| 14.375 | 39 | 0.643478 | [
"MIT"
] | damianfraszczak/nefbdaa | src/NEFBDAACommons/Shared/Models/DataExportTypeEnum.cs | 117 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace NAudio.CoreAudioApi.Interfaces
{
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator
{
int EnumAudioEndpoints(DataFlow dataFlow, DeviceState stateMask,
out IMMDeviceCollection devices);
[PreserveSig]
int GetDefaultAudioEndpoint(DataFlow dataFlow, Role role, out IMMDevice endpoint);
int GetDevice(string id, out IMMDevice deviceName);
int RegisterEndpointNotificationCallback(IMMNotificationClient client);
int UnregisterEndpointNotificationCallback(IMMNotificationClient client);
}
}
| 32 | 90 | 0.725 | [
"MIT"
] | skor98/DtWPF | speechKit/NAudio-master/NAudio/CoreAudioApi/Interfaces/IMMDeviceEnumerator.cs | 802 | C# |
/*
* ORY Oathkeeper
*
* ORY Oathkeeper is a reverse proxy that checks the HTTP Authorization for validity against a set of rules. This service uses Hydra to validate access tokens and policies.
*
* The version of the OpenAPI document: v0.0.0
* Contact: hi@ory.am
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Ory.Oathkeeper.Client.Api;
using Ory.Oathkeeper.Client.Model;
using Ory.Oathkeeper.Client.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Ory.Oathkeeper.Client.Test.Model
{
/// <summary>
/// Class for testing OathkeeperSwaggerRule
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class OathkeeperSwaggerRuleTests : IDisposable
{
// TODO uncomment below to declare an instance variable for OathkeeperSwaggerRule
//private OathkeeperSwaggerRule instance;
public OathkeeperSwaggerRuleTests()
{
// TODO uncomment below to create an instance of OathkeeperSwaggerRule
//instance = new OathkeeperSwaggerRule();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of OathkeeperSwaggerRule
/// </summary>
[Fact]
public void OathkeeperSwaggerRuleInstanceTest()
{
// TODO uncomment below to test "IsType" OathkeeperSwaggerRule
//Assert.IsType<OathkeeperSwaggerRule>(instance);
}
/// <summary>
/// Test the property 'Authenticators'
/// </summary>
[Fact]
public void AuthenticatorsTest()
{
// TODO unit test for the property 'Authenticators'
}
/// <summary>
/// Test the property 'Authorizer'
/// </summary>
[Fact]
public void AuthorizerTest()
{
// TODO unit test for the property 'Authorizer'
}
/// <summary>
/// Test the property 'Description'
/// </summary>
[Fact]
public void DescriptionTest()
{
// TODO unit test for the property 'Description'
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Fact]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'Match'
/// </summary>
[Fact]
public void MatchTest()
{
// TODO unit test for the property 'Match'
}
/// <summary>
/// Test the property 'Mutators'
/// </summary>
[Fact]
public void MutatorsTest()
{
// TODO unit test for the property 'Mutators'
}
/// <summary>
/// Test the property 'Upstream'
/// </summary>
[Fact]
public void UpstreamTest()
{
// TODO unit test for the property 'Upstream'
}
}
}
| 27.291667 | 172 | 0.572214 | [
"Apache-2.0"
] | UkonnRa/sdk | clients/oathkeeper/dotnet/src/Ory.Oathkeeper.Client.Test/Model/OathkeeperSwaggerRuleTests.cs | 3,275 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QCloud.CosApi.Common
{
public static class Extension
{
public static long ToUnixTime(this DateTime nowTime)
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
return (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero);
}
}
}
| 27.941176 | 115 | 0.686316 | [
"MIT"
] | Tsingbo-Kooboo/Kooboo.CMS.Content.Persistence | src/Kooboo.CMS.Content.Persistence.QcloudCOS/sdk/Common/Extension.cs | 477 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace AppStoreConnect.Models.Responses.Common
{
public class NoContentResponse : ApplicationResponse
{
}
}
| 17.454545 | 56 | 0.765625 | [
"MIT"
] | dersia/AppStoreConnect | src/AppStoreConnect/Models/Responses/Common/NoContentResponse.cs | 194 | C# |
using System;
namespace Payconiq
{
public class Hypermedia
{
public Uri Href { get; set; }
}
} | 12.777778 | 37 | 0.591304 | [
"MIT"
] | fvanrysselberghe/payconiq-core-lib | src/Datamodel/Hypermedia.cs | 115 | C# |
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Octokit.Tests.Integration.Clients
{
public class UserEmailsClientTests
{
private readonly IUserEmailsClient _emailClient;
public UserEmailsClientTests()
{
var github = Helper.GetAuthenticatedClient();
_emailClient = github.User.Email;
}
[IntegrationTest]
public async Task CanGetEmail()
{
var emails = await _emailClient.GetAll();
Assert.NotEmpty(emails);
}
[IntegrationTest]
public async Task CanGetEmailWithApiOptions()
{
var emails = await _emailClient.GetAll(ApiOptions.None);
Assert.NotEmpty(emails);
}
[IntegrationTest]
public async Task ReturnsCorrectCountOfEmailsWithoutStart()
{
var options = new ApiOptions
{
PageSize = 5,
PageCount = 1
};
var emails = await _emailClient.GetAll(options);
Assert.NotEmpty(emails);
}
const string testEmailAddress = "hahaha-not-a-real-email@foo.com";
[IntegrationTest(Skip = "this isn't passing in CI - i hate past me right now")]
public async Task CanAddAndDeleteEmail()
{
var github = Helper.GetAuthenticatedClient();
await github.User.Email.Add(testEmailAddress);
var emails = await github.User.Email.GetAll();
Assert.Contains(testEmailAddress, emails.Select(x => x.Email));
await github.User.Email.Delete(testEmailAddress);
emails = await github.User.Email.GetAll();
Assert.DoesNotContain(testEmailAddress, emails.Select(x => x.Email));
}
}
}
| 28.171875 | 87 | 0.595119 | [
"MIT"
] | ArsenShnurkov/octokit.net | Octokit.Tests.Integration/Clients/UserEmailsClientTests.cs | 1,805 | C# |
using System;
using Microsoft.WindowsAzure.MobileServices;
using MicrosoftHouse.Abstractions;
using Xamarin.Forms;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
using MicrosoftHouse.Models;
using System.Text;
using TaskList.Helpers;
using System.Net.Http;
using Plugin.Connectivity;
namespace MicrosoftHouse.Services
{
public class AzureCloudService : ICloudService
{
/// <summary>
/// The Client reference to the Azure Mobile App
/// </summary>
private MobileServiceClient Client { get; set; }
public AzureCloudService()
{
Client = new MobileServiceClient(Locations.AppServiceUrl, new AuthenticationDelegatingHandler());
if (Locations.AlternateLoginHost != null)
Client.AlternateLoginHost = new Uri(Locations.AlternateLoginHost);
}
List<AppServiceIdentity> identities = null;
public async Task<AppServiceIdentity> GetIdentityAsync()
{
if (Client.CurrentUser == null || Client.CurrentUser?.MobileServiceAuthenticationToken == null)
{
throw new InvalidOperationException("Not Authenticated");
}
if (identities == null)
{
identities = await Client.InvokeApiAsync<List<AppServiceIdentity>>("/.auth/me");
}
if (identities.Count > 0)
return identities[0];
return null;
}
/// <summary>
/// Returns a link to the specific table.
/// </summary>
/// <typeparam name="T">The model</typeparam>
/// <returns>The table reference</returns>
public async Task<ICloudTable<T>> GetTableAsync<T>() where T : TableData
{
await InitializeAsync();
return new AzureCloudTable<T>(Client);
}
public async Task<MobileServiceUser> LoginAsync()
{
var loginProvider = DependencyService.Get<IPlatformProvider>();
Client.CurrentUser = loginProvider.RetrieveTokenFromSecureStore();
if (Client.CurrentUser != null)
{
// User has previously been authenticated - try to Refresh the token
try
{
var refreshed = await Client.RefreshUserAsync();
if (refreshed != null)
{
loginProvider.StoreTokenInSecureStore(refreshed);
return refreshed;
}
}
catch (Exception refreshException)
{
Debug.WriteLine($"Could not refresh token: {refreshException.Message}");
}
}
if (Client.CurrentUser != null && !IsTokenExpired(Client.CurrentUser.MobileServiceAuthenticationToken))
{
// User has previously been authenticated, no refresh is required
return Client.CurrentUser;
}
// We need to ask for credentials at this point
await loginProvider.LoginAsync(Client);
if (Client.CurrentUser != null)
{
// We were able to successfully log in
loginProvider.StoreTokenInSecureStore(Client.CurrentUser);
}
return Client.CurrentUser;
}
bool IsTokenExpired(string token)
{
// Get just the JWT part of the token (without the signature).
var jwt = token.Split(new Char[] { '.' })[1];
// Undo the URL encoding.
jwt = jwt.Replace('-', '+').Replace('_', '/');
switch (jwt.Length % 4)
{
case 0: break;
case 2: jwt += "=="; break;
case 3: jwt += "="; break;
default:
throw new ArgumentException("The token is not a valid Base64 string.");
}
// Convert to a JSON String
var bytes = Convert.FromBase64String(jwt);
string jsonString = UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length);
// Parse as JSON object and get the exp field value,
// which is the expiration date as a JavaScript primative date.
JObject jsonObj = JObject.Parse(jsonString);
var exp = Convert.ToDouble(jsonObj["exp"].ToString());
// Calculate the expiration by adding the exp value (in seconds) to the
// base date of 1/1/1970.
DateTime minTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var expire = minTime.AddSeconds(exp);
return (expire < DateTime.UtcNow);
}
public async Task LogoutAsync()
{
if (Client.CurrentUser == null || Client.CurrentUser.MobileServiceAuthenticationToken == null)
return;
// Log out of the identity provider (if required)
// Invalidate the token on the mobile backend
var authUri = new Uri($"{Client.MobileAppUri}/.auth/logout");
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("X-ZUMO-AUTH", Client.CurrentUser.MobileServiceAuthenticationToken);
await httpClient.GetAsync(authUri);
}
// Remove the token from the cache
DependencyService.Get<IPlatformProvider>().RemoveTokenFromSecureStore();
// Remove the token from the MobileServiceClient
await Client.LogoutAsync();
}
private async Task InitializeAsync()
{
// Short circuit - local database is already initialized
if (Client.SyncContext.IsInitialized)
{
Debug.WriteLine("InitializeAsync: Short Circuit");
return;
}
// Create a reference to the local sqlite store
Debug.WriteLine("InitializeAsync: Initializing store");
var store = new MobileServiceSQLiteStore("offlinecache.db");
// Define the database schema - When defined you have to refresh it in order to modify it
Debug.WriteLine("InitializeAsync: Defining Datastore");
store.DefineTable<Event>();
store.DefineTable<Room>();
store.DefineTable<EventLocation>();
store.DefineTable<CarPark>();
store.DefineTable<Reservation>();
// Actually create the store and update the schema
Debug.WriteLine("InitializeAsync: Initializing SyncContext");
await Client.SyncContext.InitializeAsync(store);
// Do the sync
Debug.WriteLine("InitializeAsync: Syncing Offline Cache");
await SyncOfflineCacheAsync();
}
public async Task SyncOfflineCacheAsync()
{
Debug.WriteLine("SyncOfflineCacheAsync: Initializing...");
await InitializeAsync();
if (!(await CrossConnectivity.Current.IsRemoteReachable(Client.MobileAppUri.Host, 443)))
{
Debug.WriteLine($"Cannot connect to {Client.MobileAppUri} right now - offline");
return;
}
// Push the Operations Queue to the mobile backend
Debug.WriteLine("SyncOfflineCacheAsync: Pushing Changes");
await Client.SyncContext.PushAsync();
// Pull each sync table
Debug.WriteLine("SyncOfflineCacheAsync: Pulling tasks event");
var eventtable = await GetTableAsync<Event>();
await eventtable.PullAsync();
Debug.WriteLine("SyncOfflineCacheAsync: Pulling tasks room");
var roomTable = await GetTableAsync<Room>();
await roomTable.PullAsync();
Debug.WriteLine("SyncOfflineCacheAsync: Pulling tasks locations");
var locationTable = await GetTableAsync<EventLocation>();
await locationTable.PullAsync();
Debug.WriteLine("SyncOfflineCacheAsync: Pulling tasks park");
var parkTable = await GetTableAsync<CarPark>();
await parkTable.PullAsync();
Debug.WriteLine("SyncOfflineCacheAsync: Pulling tasks reservation");
var reservationTable = await GetTableAsync<Reservation>();
await reservationTable.PullAsync();
}
public async Task RegisterForPushNotifications()
{
var platformProvider = DependencyService.Get<IPlatformProvider>();
await platformProvider.RegisterForPushNotifications(Client);
}
}
}
| 34.91453 | 121 | 0.630967 | [
"MIT"
] | Menne/Microsoft-House | App/MicrosoftHouse/MicrosoftHouse/Services/AzureCloudService.cs | 8,172 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Cloudflare.Inputs
{
public sealed class AccessGroupExcludeOktaArgs : Pulumi.ResourceArgs
{
[Input("identityProviderId")]
public Input<string>? IdentityProviderId { get; set; }
[Input("names")]
private InputList<string>? _names;
/// <summary>
/// Friendly name of the Access Group.
/// </summary>
public InputList<string> Names
{
get => _names ?? (_names = new InputList<string>());
set => _names = value;
}
public AccessGroupExcludeOktaArgs()
{
}
}
}
| 26.485714 | 88 | 0.623517 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-cloudflare | sdk/dotnet/Inputs/AccessGroupExcludeOktaArgs.cs | 927 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Cdb.V20170320.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeInstanceParamRecordsResponse : AbstractModel
{
/// <summary>
/// 符合条件的记录数。
/// </summary>
[JsonProperty("TotalCount")]
public long? TotalCount{ get; set; }
/// <summary>
/// 参数修改记录。
/// </summary>
[JsonProperty("Items")]
public ParamRecord[] Items{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// 内部实现,用户禁止调用
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "TotalCount", this.TotalCount);
this.SetParamArrayObj(map, prefix + "Items.", this.Items);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 30.396552 | 83 | 0.628474 | [
"Apache-2.0"
] | Darkfaker/tencentcloud-sdk-dotnet | TencentCloud/Cdb/V20170320/Models/DescribeInstanceParamRecordsResponse.cs | 1,875 | C# |
#region License
/* **************************************************************************************
* Copyright (c) Librame Pong All rights reserved.
*
* https://github.com/librame
*
* You must not remove this notice, or any other, from this software.
* **************************************************************************************/
#endregion
using Librame.Extensions.Core;
namespace Librame.Extensions.Drawing;
/// <summary>
/// 定义实现 <see cref="IBitmapList"/> 的位图列表。
/// </summary>
public class BitmapList : AbstractDisposable, IBitmapList
{
private readonly List<BitmapDescriptor> _bitmaps;
/// <summary>
/// 构造一个 <see cref="BitmapList"/>。
/// </summary>
public BitmapList()
{
_bitmaps = new();
}
/// <summary>
/// 使用 <see cref="SKBitmap"/> 集合构造一个 <see cref="BitmapList"/>。
/// </summary>
/// <param name="bitmaps">给定的 <see cref="IEnumerable{SKBitmap}"/>。</param>
public BitmapList(IEnumerable<SKBitmap> bitmaps)
{
_bitmaps = bitmaps.Select(s => new BitmapDescriptor(s)).ToList();
}
/// <summary>
/// 使用 <see cref="BitmapDescriptor"/> 集合构造一个 <see cref="BitmapList"/>。
/// </summary>
/// <param name="bitmaps">给定的 <see cref="List{BitmapDescriptor}"/>。</param>
public BitmapList(List<BitmapDescriptor> bitmaps)
{
_bitmaps = bitmaps;
}
/// <summary>
/// 位图数。
/// </summary>
public int Count
=> _bitmaps.Count;
/// <summary>
/// 添加位图。
/// </summary>
/// <param name="imageBuffer">给定的字节数组。</param>
public void Add(byte[] imageBuffer)
{
var descr = new BitmapDescriptor(SKBitmap.Decode(imageBuffer));
_bitmaps.Add(descr);
}
/// <summary>
/// 添加位图集合。
/// </summary>
/// <param name="imageBuffers">给定的字节数组集合。</param>
public void Add(IEnumerable<byte[]> imageBuffers)
=> imageBuffers.ForEach(buffer => Add(buffer));
/// <summary>
/// 添加位图。
/// </summary>
/// <param name="imagePath">给定的图像路径。</param>
public void Add(string imagePath)
{
var descr = new BitmapDescriptor(SKBitmap.Decode(imagePath), imagePath);
_bitmaps.Add(descr);
}
/// <summary>
/// 添加位图集合。
/// </summary>
/// <param name="imagePaths">给定的图像路径集合。</param>
public void Add(IEnumerable<string> imagePaths)
=> imagePaths.ForEach(path => Add(path));
/// <summary>
/// 添加位图描述符。
/// </summary>
/// <param name="descriptor">给定的 <see cref="BitmapDescriptor"/>。</param>
public void Add(BitmapDescriptor descriptor)
=> _bitmaps.Add(descriptor);
/// <summary>
/// 添加位图描述符集合。
/// </summary>
/// <param name="descriptors">给定的 <see cref="IEnumerable{BitmapDescriptor}"/>。</param>
public void Add(IEnumerable<BitmapDescriptor> descriptors)
=> _bitmaps.AddRange(descriptors);
/// <summary>
/// 清除当前位图集合。
/// </summary>
public void Clear()
{
if (_bitmaps.Count > 0)
{
_bitmaps.ForEach(b => ((SKBitmap)b.Source).Dispose());
_bitmaps.Clear();
}
}
/// <summary>
/// 获取位图枚举器。
/// </summary>
/// <returns>返回位图对象枚举器。</returns>
public IEnumerator<BitmapDescriptor> GetEnumerator()
=> _bitmaps.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
=> GetEnumerator();
/// <summary>
/// 释放已托管资源。
/// </summary>
/// <returns>返回是否成功释放的布尔值。</returns>
protected override bool ReleaseManaged()
{
Clear();
return true;
}
}
| 25.111888 | 90 | 0.556391 | [
"MIT"
] | gitter-badger/extensions-tick | src/LibrameTick.Extensions.Drawing.SkiaSharp/BitmapList.cs | 3,951 | 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 Cake.Common.Tests.Fixtures.Tools.DotNet.Format;
using Cake.Common.Tools.DotNet.Format;
using Cake.Testing;
using Xunit;
namespace Cake.Common.Tests.Unit.Tools.DotNet.Format
{
public sealed class DotNetFormatTests
{
public sealed class TheFormatMethod
{
[Fact]
public void Should_Throw_If_Settings_Are_Null()
{
// Given
var fixture = new DotNetFormatterFixture();
fixture.Root = "./src/project";
fixture.Settings = null;
fixture.GivenDefaultToolDoNotExist();
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "settings");
}
[Fact]
public void Should_Throw_If_Root_Is_Null()
{
// Given
var fixture = new DotNetFormatterFixture();
fixture.Settings = new DotNetFormatSettings();
fixture.GivenDefaultToolDoNotExist();
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsArgumentNullException(result, "root");
}
[Fact]
public void Should_Throw_If_Process_Was_Not_Started()
{
// Given
var fixture = new DotNetFormatterFixture();
fixture.Root = "./src/project";
fixture.GivenProcessCannotStart();
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsCakeException(result, ".NET CLI: Process was not started.");
}
[Fact]
public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code()
{
// Given
var fixture = new DotNetFormatterFixture();
fixture.Root = "./src/project";
fixture.GivenProcessExitsWithCode(1);
// When
var result = Record.Exception(() => fixture.Run());
// Then
AssertEx.IsCakeException(result, ".NET CLI: Process returned an error (exit code 1).");
}
[Fact]
public void Should_Add_Mandatory_Arguments()
{
// Given
var fixture = new DotNetFormatterFixture();
fixture.Root = "./src/project";
// When
var result = fixture.Run();
// Then
Assert.Equal("format \"./src/project\"", result.Args);
}
[Fact]
public void Should_Add_Additional_Arguments()
{
// Given
var fixture = new DotNetFormatterFixture();
fixture.Settings.Diagnostics.Add("CS123");
fixture.Settings.Diagnostics.Add("CA555");
fixture.Settings.Severity = DotNetFormatSeverity.Warning;
fixture.Settings.NoRestore = true;
fixture.Settings.VerifyNoChanges = true;
fixture.Settings.Include.Add("./src/");
fixture.Settings.Include.Add("./tests/");
fixture.Settings.Exclude.Add("./src/submodule-a/");
fixture.Settings.IncludeGenerated = true;
fixture.Settings.Verbosity = Common.Tools.DotNet.DotNetVerbosity.Diagnostic;
fixture.Settings.BinaryLog = "./temp/b.log";
fixture.Settings.Report = "./temp/report.json";
fixture.Root = "./src/project";
// When
var result = fixture.Run();
// Then
var expected = "format \"./src/project\" --diagnostics CS123 CA555 --severity warn --no-restore --verify-no-changes --include ./src/ ./tests/ --exclude ./src/submodule-a/ --include-generated";
expected += " --binarylog \"/Working/temp/b.log\" --report \"/Working/temp/report.json\" --verbosity diagnostic";
Assert.Equal(expected, result.Args);
}
[Theory]
[InlineData("./src/project", "format \"./src/project\"")]
[InlineData("./src/cake build/", "format \"./src/cake build/\"")]
[InlineData("./src/cake build/cake cli", "format \"./src/cake build/cake cli\"")]
public void Should_Quote_Root_Path(string text, string expected)
{
// Given
var fixture = new DotNetFormatterFixture();
fixture.Root = text;
// When
var result = fixture.Run();
// Then
Assert.Equal(expected, result.Args);
}
[Fact]
public void Should_Add_Subcommand()
{
// Given
var fixture = new DotNetFormatterFixture();
fixture.Root = "./src/project";
fixture.Subcommand = "style";
// When
var result = fixture.Run();
// Then
Assert.Equal("format style \"./src/project\"", result.Args);
}
}
}
}
| 36.111111 | 208 | 0.513303 | [
"Apache-2.0"
] | AnimalStudioOfficial/My-Cake | src/Cake.Common.Tests/Unit/Tools/DotNet/Format/DotNetFormatTests.cs | 5,527 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace NASB_Parser.FloatSources
{
public class FSFunc : FloatSource
{
public FuncWay Way { get; set; }
public FloatSource ContainerA { get; set; }
public FloatSource ContainerB { get; set; }
public FloatSource ContainerC { get; set; }
public FSFunc()
{
}
internal FSFunc(BulkSerializeReader reader) : base(reader)
{
Way = (FuncWay)reader.ReadInt();
ContainerA = Read(reader);
ContainerB = Read(reader);
ContainerC = Read(reader);
}
public override void Write(BulkSerializeWriter writer)
{
base.Write(writer);
writer.Write(Way);
writer.Write(ContainerA);
writer.Write(ContainerB);
writer.Write(ContainerC);
}
public enum FuncWay
{
Abs,
Add,
Sub,
Div,
Mult,
Sin,
Cos,
Mod,
Clamp,
Floor,
Ceil,
MoveTo,
MoveToAng,
MoveToF,
MoveToAngF,
Sign,
Lerp,
InvLerp,
Repeat,
Pow,
Sqrt,
Log,
Log10,
Atan,
Atan2,
RoundToInt,
Max,
Min,
Pi
}
}
} | 22.029412 | 66 | 0.447931 | [
"MIT"
] | megalon/NASB_Parser | NASB_Parser/FloatSources/FSFunc.cs | 1,500 | C# |
using System;
namespace Xavalon.XamlStyler.Package
{
internal static class Guids
{
public const string XamlStylerPackageGuidString = "a224be3c-88d1-4a57-9804-181dbef68021";
public const string CommandSetGuidString = "83fc41d5-eacb-4fa8-aaa3-9a9bdd5f6407";
public const string UIContextGuidString = "2dc9b780-2911-46e9-bd66-508dfd5f68a3";
public static readonly Guid CommandSetGuid = new Guid(Guids.CommandSetGuidString);
};
} | 36.384615 | 98 | 0.742072 | [
"Apache-2.0"
] | MatFillion/XamlStyler | XamlStyler.Package/Guids.cs | 475 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace Pipedrive
{
public class Activity : IDealUpdateEntity
{
public long Id { get; set; }
[JsonProperty("company_id")]
public long CompanyId { get; set; }
[JsonProperty("user_id")]
public long UserId { get; set; }
[JsonProperty("done")]
public bool Done { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("reference_type")]
public string ReferenceType { get; set; }
[JsonProperty("reference_id")]
public string ReferenceId { get; set; }
[JsonProperty("due_date")]
public DateTime? DueDate { get; set; }
[JsonProperty("due_time")]
public string DueTime { get; set; }
[JsonProperty("duration")]
public string Duration { get; set; }
[JsonProperty("add_time")]
public DateTime AddTime { get; set; }
[JsonProperty("marked_as_done_time")]
public DateTime? MarkedAsDoneTime { get; set; }
[JsonProperty("last_notification_time")]
public DateTime? LastNotificationTime { get; set; }
[JsonProperty("last_notification_user_id")]
public long? LastNotificationUserId { get; set; }
[JsonProperty("notification_language_id")]
public long? NotificationLanguageId { get; set; }
[JsonProperty("subject")]
public string Subject { get; set; }
[JsonProperty("org_id")]
public long? OrgId { get; set; }
[JsonProperty("person_id")]
public long? PersonId { get; set; }
[JsonProperty("deal_id")]
public long? DealId { get; set; }
[JsonProperty("active_flag")]
public bool ActiveFlag { get; set; }
[JsonProperty("update_time")]
public DateTime? UpdateTime { get; set; }
[JsonProperty("update_user_id")]
public long? UpdateUserId { get; set; }
[JsonProperty("gcal_event_id")]
public string GcalEventId { get; set; }
[JsonProperty("google_calendar_id")]
public string GoogleCalendarId { get; set; }
[JsonProperty("google_calendar_etag")]
public string GoogleCalendarEtag { get; set; }
[JsonProperty("note")]
public string Note { get; set; }
[JsonProperty("created_by_user_id")]
public long CreatedByUserId { get; set; }
[JsonProperty("participants")]
public List<Participant> Participants { get; set; }
[JsonProperty("org_name")]
public string OrgName { get; set; }
[JsonProperty("person_name")]
public string PersonName { get; set; }
[JsonProperty("deal_title")]
public string DealTitle { get; set; }
[JsonProperty("owner_name")]
public string OwnerName { get; set; }
[JsonProperty("person_dropbox_bcc")]
public string PersonDropboxBcc { get; set; }
[JsonProperty("deal_dropbox_bcc")]
public string DealDropboxBcc { get; set; }
[JsonProperty("assigned_to_user_id")]
public long? AssignedToUserId { get; set; }
public ActivityUpdate ToUpdate()
{
return new ActivityUpdate
{
Subject = Subject,
Done = Done ? ActivityDone.Done : ActivityDone.Undone,
Type = Type,
DueDate = DueDate,
DueTime = DueTime,
Duration = Duration,
UserId = UserId,
DealId = DealId,
PersonId = PersonId,
Participants = Participants,
OrgId = OrgId,
Note = Note
};
}
}
}
| 28.37594 | 70 | 0.575782 | [
"MIT"
] | Panksy/pipedrive-dotnet | src/Pipedrive.net/Models/Response/Activity.cs | 3,776 | C# |
namespace ClubHouse.Domain {
public enum NotificationType : byte {
Followed = 1,
InviteToJoin = 9,
SystemNotification = 14,
EventSchedule = 16
}
}
| 20.888889 | 41 | 0.590426 | [
"MIT"
] | Zahragheaybi/ClubHouse-Windows | Domain/ClubHouse.Domain/Misc/NotificationType.cs | 190 | C# |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace TestUtilities {
[ExcludeFromCodeCoverage]
internal sealed class TestMainThreadService {
[DllImport("ole32.dll", ExactSpelling = true, SetLastError = true)]
private static extern int OleInitialize(IntPtr value);
private static readonly Lazy<TestMainThreadService> LazyInstance = new Lazy<TestMainThreadService>(Create, LazyThreadSafetyMode.ExecutionAndPublication);
private static TestMainThreadService Create() {
var mainThreadService = new TestMainThreadService();
var initialized = new ManualResetEventSlim();
AppDomain.CurrentDomain.DomainUnload += mainThreadService.Destroy;
AppDomain.CurrentDomain.ProcessExit += mainThreadService.Destroy;
// We want to maintain an application on a single STA thread
// set Background so that it won't block process exit.
var thread = new Thread(mainThreadService.RunMainThread) { Name = "WPF Dispatcher Thread" };
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start(initialized);
initialized.Wait();
Dispatcher.FromThread(thread).Invoke(() => {
mainThreadService.Thread = thread;
mainThreadService.SyncContext = SynchronizationContext.Current;
});
return mainThreadService;
}
public static TestMainThreadService Instance => LazyInstance.Value;
private readonly AsyncLocal<TestMainThread> _testMainThread;
private DispatcherFrame _frame;
private Application _application;
private TestMainThreadService() {
_testMainThread = new AsyncLocal<TestMainThread>();
}
public Thread Thread { get; private set; }
public SynchronizationContext SyncContext { get; private set; }
internal TestMainThread CreateTestMainThread() {
if (_testMainThread.Value != null) {
throw new InvalidOperationException("AsyncLocal<TestMainThread> reentrancy");
}
var testMainThread = new TestMainThread(this, RemoveTestMainThread);
_testMainThread.Value = testMainThread;
return testMainThread;
}
private void RemoveTestMainThread() => _testMainThread.Value = null;
public void Invoke(Action action) {
ExceptionDispatchInfo exception = Thread == Thread.CurrentThread
? CallSafe(action)
: _application.Dispatcher.Invoke(() => CallSafe(action));
exception?.Throw();
}
public async Task InvokeAsync(Action action) {
ExceptionDispatchInfo exception;
if (Thread == Thread.CurrentThread) {
exception = CallSafe(action);
} else {
exception = await _application.Dispatcher.InvokeAsync(() => CallSafe(action), DispatcherPriority.Normal);
}
exception?.Throw();
}
public T Invoke<T>(Func<T> action) {
var result = Thread == Thread.CurrentThread
? CallSafe(action)
: _application.Dispatcher.Invoke(() => CallSafe(action));
result.Exception?.Throw();
return result.Value;
}
public async Task<T> InvokeAsync<T>(Func<T> action) {
CallSafeResult<T> result;
if (Thread == Thread.CurrentThread) {
result = CallSafe(action);
} else {
result = await _application.Dispatcher.InvokeAsync(() => CallSafe(action));
}
result.Exception?.Throw();
return result.Value;
}
private void RunMainThread(object obj) {
if (Application.Current != null) {
// Need to be on our own sta thread
Application.Current.Dispatcher.Invoke(Application.Current.Shutdown);
if (Application.Current != null) {
throw new InvalidOperationException("Unable to shut down existing application.");
}
}
// Kick OLE so we can use the clipboard if necessary
OleInitialize(IntPtr.Zero);
_application = new Application {
// Application should survive window closing events to be reusable
ShutdownMode = ShutdownMode.OnExplicitShutdown
};
// Dispatcher.Run internally calls PushFrame(new DispatcherFrame()), so we need to call PushFrame ourselves
_frame = new DispatcherFrame(exitWhenRequested: false);
var exceptionInfos = new List<ExceptionDispatchInfo>();
// Initialization completed
((ManualResetEventSlim)obj).Set();
while (_frame.Continue) {
var exception = CallSafe(() => Dispatcher.PushFrame(_frame));
if (exception != null) {
exceptionInfos.Add(exception);
}
}
var dispatcher = Dispatcher.FromThread(Thread.CurrentThread);
if (dispatcher != null && !dispatcher.HasShutdownStarted) {
dispatcher.InvokeShutdown();
}
if (exceptionInfos.Any()) {
throw new AggregateException(exceptionInfos.Select(ce => ce.SourceException).ToArray());
}
}
private void Destroy(object sender, EventArgs e) {
AppDomain.CurrentDomain.DomainUnload -= Destroy;
AppDomain.CurrentDomain.ProcessExit -= Destroy;
var mainThread = Thread;
Thread = null;
_frame.Continue = false;
// If the thread is still alive, allow it to exit normally so the dispatcher can continue to clear pending work items
// 10 seconds should be enough
mainThread.Join(10000);
}
private static ExceptionDispatchInfo CallSafe(Action action)
=> CallSafe<object>(() => {
action();
return null;
}).Exception;
private static CallSafeResult<T> CallSafe<T>(Func<T> func) {
try {
return new CallSafeResult<T> { Value = func() };
} catch (ThreadAbortException tae) {
// Thread should be terminated anyway
Thread.ResetAbort();
return new CallSafeResult<T> { Exception = ExceptionDispatchInfo.Capture(tae) };
} catch (Exception e) {
return new CallSafeResult<T> { Exception = ExceptionDispatchInfo.Capture(e) };
}
}
private class CallSafeResult<T> {
public T Value { get; set; }
public ExceptionDispatchInfo Exception { get; set; }
}
}
}
| 38.975124 | 161 | 0.618713 | [
"Apache-2.0"
] | Bhaskers-Blu-Org2/PTVS | Common/Tests/Utilities/TestMainThreadService.cs | 7,836 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace x42.Feature.Database.Tables
{
[Table("profilereservation")]
public class ProfileReservationData
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid ReservationId { get; set; }
public string Name { get; set; }
public string KeyAddress { get; set; }
public string ReturnAddress { get; set; }
public string Signature { get; set; }
public int Status { get; set; }
public string PriceLockId { get; set; }
public int ReservationExpirationBlock { get; set; }
public bool Relayed { get; set; }
}
} | 33.545455 | 61 | 0.661247 | [
"MIT"
] | psavva/XServer | xServer.D/Feature/Database/Tables/ProfileReservationData.cs | 740 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OnlineBookStore.Entities.Concrete;
namespace OnlineBookStore.Business.Abstract
{
public interface IOrderService
{
List<Order> GetOrdersIdByCustomerId(int customerId);
int CreateAndReturnOrderId(Order order);
int GetOrderIdByDate(string date);
void DeleteOrderByOrderId(int orderId);
void SendInvoiceByEmail(Customer customer, int orderId);
void SendInvoiceByPhone(LoginedCustomer customer, int orderId);
void SendInfoAboutCancelOrderByEmail(Customer customer, int orderId);
}
}
| 30.5 | 77 | 0.754098 | [
"MIT"
] | arxlan99/OnlineBookStore | OnlineBookStore.Business/Abstract/IOrderService.cs | 673 | C# |
namespace Xilium.CefGlue
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Xilium.CefGlue.Interop;
/// <summary>
/// Implement this interface to handle events when window rendering is disabled.
/// The methods of this class will be called on the UI thread.
/// </summary>
public abstract unsafe partial class CefRenderHandler
{
private static readonly CefRectangle[] s_emptyRectangleArray = new CefRectangle[0];
private cef_accessibility_handler_t* get_accessibility_handler(cef_render_handler_t* self)
{
CheckSelf(self);
var result = GetAccessibilityHandler();
if (result == null) return null;
return result.ToNative();
}
/// <summary>
/// Return the handler for accessibility notifications. If no handler is
/// provided the default implementation will be used.
/// </summary>
protected abstract CefAccessibilityHandler GetAccessibilityHandler();
private int get_root_screen_rect(cef_render_handler_t* self, cef_browser_t* browser, cef_rect_t* rect)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_rect = new CefRectangle();
var result = GetRootScreenRect(m_browser, ref m_rect);
if (result)
{
rect->x = m_rect.X;
rect->y = m_rect.Y;
rect->width = m_rect.Width;
rect->height = m_rect.Height;
return 1;
}
else return 0;
}
/// <summary>
/// Called to retrieve the root window rectangle in screen coordinates. Return
/// true if the rectangle was provided.
/// </summary>
protected virtual bool GetRootScreenRect(CefBrowser browser, ref CefRectangle rect)
{
// TODO: return CefRectangle? (Nullable<CefRectangle>) instead of returning bool?
return false;
}
private int get_view_rect(cef_render_handler_t* self, cef_browser_t* browser, cef_rect_t* rect)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_rect = new CefRectangle();
var result = GetViewRect(m_browser, ref m_rect);
if (result)
{
rect->x = m_rect.X;
rect->y = m_rect.Y;
rect->width = m_rect.Width;
rect->height = m_rect.Height;
return 1;
}
else return 0;
}
/// <summary>
/// Called to retrieve the view rectangle which is relative to screen
/// coordinates. Return true if the rectangle was provided.
/// </summary>
protected virtual bool GetViewRect(CefBrowser browser, ref CefRectangle rect)
{
// TODO: return CefRectangle? (Nullable<CefRectangle>) instead of returning bool?
return false;
}
private int get_screen_point(cef_render_handler_t* self, cef_browser_t* browser, int viewX, int viewY, int* screenX, int* screenY)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
int m_screenX = 0;
int m_screenY = 0;
var result = GetScreenPoint(m_browser, viewX, viewY, ref m_screenX, ref m_screenY);
if (result)
{
*screenX = m_screenX;
*screenY = m_screenY;
return 1;
}
else return 0;
}
/// <summary>
/// Called to retrieve the translation from view coordinates to actual screen
/// coordinates. Return true if the screen coordinates were provided.
/// </summary>
protected virtual bool GetScreenPoint(CefBrowser browser, int viewX, int viewY, ref int screenX, ref int screenY)
{
return false;
}
private int get_screen_info(cef_render_handler_t* self, cef_browser_t* browser, cef_screen_info_t* screen_info)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_screenInfo = new CefScreenInfo(screen_info);
var result = GetScreenInfo(m_browser, m_screenInfo);
m_screenInfo.Dispose();
m_browser.Dispose();
return result ? 1 : 0;
}
/// <summary>
/// Called to allow the client to fill in the CefScreenInfo object with
/// appropriate values. Return true if the |screen_info| structure has been
/// modified.
/// If the screen info rectangle is left empty the rectangle from GetViewRect
/// will be used. If the rectangle is still empty or invalid popups may not be
/// drawn correctly.
/// </summary>
protected abstract bool GetScreenInfo(CefBrowser browser, CefScreenInfo screenInfo);
private void on_popup_show(cef_render_handler_t* self, cef_browser_t* browser, int show)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
OnPopupShow(m_browser, show != 0);
}
/// <summary>
/// Called when the browser wants to show or hide the popup widget. The popup
/// should be shown if |show| is true and hidden if |show| is false.
/// </summary>
protected virtual void OnPopupShow(CefBrowser browser, bool show)
{
}
private void on_popup_size(cef_render_handler_t* self, cef_browser_t* browser, cef_rect_t* rect)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_rect = new CefRectangle(rect->x, rect->y, rect->width, rect->height);
OnPopupSize(m_browser, m_rect);
}
/// <summary>
/// Called when the browser wants to move or resize the popup widget. |rect|
/// contains the new location and size in view coordinates.
/// </summary>
protected abstract void OnPopupSize(CefBrowser browser, CefRectangle rect);
private void on_paint(cef_render_handler_t* self, cef_browser_t* browser, CefPaintElementType type, UIntPtr dirtyRectsCount, cef_rect_t* dirtyRects, void* buffer, int width, int height)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
// TODO: reuse arrays?
var m_dirtyRects = new CefRectangle[(int)dirtyRectsCount];
var count = (int)dirtyRectsCount;
var rect = dirtyRects;
for (var i = 0; i < count; i++)
{
m_dirtyRects[i].X = rect->x;
m_dirtyRects[i].Y = rect->y;
m_dirtyRects[i].Width = rect->width;
m_dirtyRects[i].Height = rect->height;
rect++;
}
OnPaint(m_browser, type, m_dirtyRects, (IntPtr)buffer, width, height);
}
/// <summary>
/// Called when an element should be painted. Pixel values passed to this
/// method are scaled relative to view coordinates based on the value of
/// CefScreenInfo.device_scale_factor returned from GetScreenInfo. |type|
/// indicates whether the element is the view or the popup widget. |buffer|
/// contains the pixel data for the whole image. |dirtyRects| contains the set
/// of rectangles in pixel coordinates that need to be repainted. |buffer| will
/// be |width|*|height|*4 bytes in size and represents a BGRA image with an
/// upper-left origin.
/// </summary>
protected abstract void OnPaint(CefBrowser browser, CefPaintElementType type, CefRectangle[] dirtyRects, IntPtr buffer, int width, int height);
private void on_cursor_change(cef_render_handler_t* self, cef_browser_t* browser, IntPtr cursor, CefCursorType type, cef_cursor_info_t* custom_cursor_info)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_cefCursorInfo = type == CefCursorType.Custom ? new CefCursorInfo(custom_cursor_info) : null;
OnCursorChange(m_browser, cursor, type, m_cefCursorInfo);
if (m_cefCursorInfo != null) m_cefCursorInfo.Dispose();
}
/// <summary>
/// Called when the browser's cursor has changed. If |type| is CT_CUSTOM then
/// |custom_cursor_info| will be populated with the custom cursor information.
/// </summary>
protected abstract void OnCursorChange(CefBrowser browser, IntPtr cursorHandle, CefCursorType type, CefCursorInfo customCursorInfo);
private int start_dragging(cef_render_handler_t* self, cef_browser_t* browser, cef_drag_data_t* drag_data, CefDragOperationsMask allowed_ops, int x, int y)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_dragData = CefDragData.FromNative(drag_data);
var m_result = StartDragging(m_browser, m_dragData, allowed_ops, x, y);
return m_result ? 1 : 0;
}
/// <summary>
/// Called when the user starts dragging content in the web view. Contextual
/// information about the dragged content is supplied by |drag_data|.
/// (|x|, |y|) is the drag start location in screen coordinates.
/// OS APIs that run a system message loop may be used within the
/// StartDragging call.
/// Return false to abort the drag operation. Don't call any of
/// CefBrowserHost::DragSource*Ended* methods after returning false.
/// Return true to handle the drag operation. Call
/// CefBrowserHost::DragSourceEndedAt and DragSourceSystemDragEnded either
/// synchronously or asynchronously to inform the web view that the drag
/// operation has ended.
/// </summary>
protected virtual bool StartDragging(CefBrowser browser, CefDragData dragData, CefDragOperationsMask allowedOps, int x, int y)
{
return false;
}
private void update_drag_cursor(cef_render_handler_t* self, cef_browser_t* browser, CefDragOperationsMask operation)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
UpdateDragCursor(m_browser, operation);
}
/// <summary>
/// Called when the web view wants to update the mouse cursor during a
/// drag & drop operation. |operation| describes the allowed operation
/// (none, move, copy, link).
/// </summary>
protected virtual void UpdateDragCursor(CefBrowser browser, CefDragOperationsMask operation)
{
}
private void on_scroll_offset_changed(cef_render_handler_t* self, cef_browser_t* browser, double x, double y)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
OnScrollOffsetChanged(m_browser, x, y);
}
/// <summary>
/// Called when the scroll offset has changed.
/// </summary>
protected abstract void OnScrollOffsetChanged(CefBrowser browser, double x, double y);
private void on_ime_composition_range_changed(cef_render_handler_t* self, cef_browser_t* browser, cef_range_t* selected_range, UIntPtr character_boundsCount, cef_rect_t* character_bounds)
{
CheckSelf(self);
// TODO: reuse array/special list for rectange - this method called only from one thread and can be reused
var m_browser = CefBrowser.FromNative(browser);
var m_selectedRange = new CefRange(selected_range->from, selected_range->to);
CefRectangle[] m_characterBounds;
if (character_boundsCount == UIntPtr.Zero)
{
m_characterBounds = s_emptyRectangleArray;
}
else
{
var m_characterBoundsCount = checked((int)character_boundsCount);
m_characterBounds = new CefRectangle[m_characterBoundsCount];
for (var i = 0; i < m_characterBoundsCount; i++)
{
m_characterBounds[i] = new CefRectangle(
character_bounds[i].x,
character_bounds[i].y,
character_bounds[i].width,
character_bounds[i].height
);
}
}
OnImeCompositionRangeChanged(m_browser, m_selectedRange, m_characterBounds);
}
/// <summary>
/// Called when the IME composition range has changed. |selected_range| is the
/// range of characters that have been selected. |character_bounds| is the
/// bounds of each character in view coordinates.
/// </summary>
protected abstract void OnImeCompositionRangeChanged(CefBrowser browser, CefRange selectedRange, CefRectangle[] characterBounds);
private void on_text_selection_changed(cef_render_handler_t* self, cef_browser_t* browser, cef_string_t* selected_text, cef_range_t* selected_range)
{
CheckSelf(self);
var m_browser = CefBrowser.FromNative(browser);
var m_selected_text = cef_string_t.ToString(selected_text);
var m_selected_range = new CefRange(selected_range->from, selected_range->to);
OnTextSelectionChanged(m_browser, m_selected_text, m_selected_range);
}
/// <summary>
/// Called when text selection has changed for the specified |browser|.
/// |selected_text| is the currently selected text and |selected_range| is
/// the character range.
/// </summary>
protected virtual void OnTextSelectionChanged(CefBrowser browser, string selectedText, CefRange selectedRange) { }
}
}
| 38.540984 | 195 | 0.616333 | [
"MIT"
] | 00aj99/Chromely | src/CefGlue/Chromely.Unofficial.CefGlue.NetStd/Classes.Handlers/CefRenderHandler.cs | 14,108 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.12
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace pxr {
public class GfVec3dVector : global::System.IDisposable, global::System.Collections.IEnumerable
, global::System.Collections.Generic.IEnumerable<GfVec3d>
{
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
protected bool swigCMemOwn;
internal GfVec3dVector(global::System.IntPtr cPtr, bool cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(GfVec3dVector obj) {
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
~GfVec3dVector() {
Dispose();
}
public virtual void Dispose() {
lock(this) {
if (swigCPtr.Handle != global::System.IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
UsdCsPINVOKE.delete_GfVec3dVector(swigCPtr);
}
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
global::System.GC.SuppressFinalize(this);
}
}
public GfVec3dVector(global::System.Collections.ICollection c) : this() {
if (c == null)
throw new global::System.ArgumentNullException("c");
foreach (GfVec3d element in c) {
this.Add(element);
}
}
public bool IsFixedSize {
get {
return false;
}
}
public bool IsReadOnly {
get {
return false;
}
}
public GfVec3d this[int index] {
get {
return getitem(index);
}
set {
setitem(index, value);
}
}
public int Capacity {
get {
return (int)capacity();
}
set {
if (value < size())
throw new global::System.ArgumentOutOfRangeException("Capacity");
reserve((uint)value);
}
}
public int Count {
get {
return (int)size();
}
}
public bool IsSynchronized {
get {
return false;
}
}
public void CopyTo(GfVec3d[] array)
{
CopyTo(0, array, 0, this.Count);
}
public void CopyTo(GfVec3d[] array, int arrayIndex)
{
CopyTo(0, array, arrayIndex, this.Count);
}
public void CopyTo(int index, GfVec3d[] array, int arrayIndex, int count)
{
if (array == null)
throw new global::System.ArgumentNullException("array");
if (index < 0)
throw new global::System.ArgumentOutOfRangeException("index", "Value is less than zero");
if (arrayIndex < 0)
throw new global::System.ArgumentOutOfRangeException("arrayIndex", "Value is less than zero");
if (count < 0)
throw new global::System.ArgumentOutOfRangeException("count", "Value is less than zero");
if (array.Rank > 1)
throw new global::System.ArgumentException("Multi dimensional array.", "array");
if (index+count > this.Count || arrayIndex+count > array.Length)
throw new global::System.ArgumentException("Number of elements to copy is too large.");
for (int i=0; i<count; i++)
array.SetValue(getitemcopy(index+i), arrayIndex+i);
}
global::System.Collections.Generic.IEnumerator<GfVec3d> global::System.Collections.Generic.IEnumerable<GfVec3d>.GetEnumerator() {
return new GfVec3dVectorEnumerator(this);
}
global::System.Collections.IEnumerator global::System.Collections.IEnumerable.GetEnumerator() {
return new GfVec3dVectorEnumerator(this);
}
public GfVec3dVectorEnumerator GetEnumerator() {
return new GfVec3dVectorEnumerator(this);
}
// Type-safe enumerator
/// Note that the IEnumerator documentation requires an InvalidOperationException to be thrown
/// whenever the collection is modified. This has been done for changes in the size of the
/// collection but not when one of the elements of the collection is modified as it is a bit
/// tricky to detect unmanaged code that modifies the collection under our feet.
public sealed class GfVec3dVectorEnumerator : global::System.Collections.IEnumerator
, global::System.Collections.Generic.IEnumerator<GfVec3d>
{
private GfVec3dVector collectionRef;
private int currentIndex;
private object currentObject;
private int currentSize;
public GfVec3dVectorEnumerator(GfVec3dVector collection) {
collectionRef = collection;
currentIndex = -1;
currentObject = null;
currentSize = collectionRef.Count;
}
// Type-safe iterator Current
public GfVec3d Current {
get {
if (currentIndex == -1)
throw new global::System.InvalidOperationException("Enumeration not started.");
if (currentIndex > currentSize - 1)
throw new global::System.InvalidOperationException("Enumeration finished.");
if (currentObject == null)
throw new global::System.InvalidOperationException("Collection modified.");
return (GfVec3d)currentObject;
}
}
// Type-unsafe IEnumerator.Current
object global::System.Collections.IEnumerator.Current {
get {
return Current;
}
}
public bool MoveNext() {
int size = collectionRef.Count;
bool moveOkay = (currentIndex+1 < size) && (size == currentSize);
if (moveOkay) {
currentIndex++;
currentObject = collectionRef[currentIndex];
} else {
currentObject = null;
}
return moveOkay;
}
public void Reset() {
currentIndex = -1;
currentObject = null;
if (collectionRef.Count != currentSize) {
throw new global::System.InvalidOperationException("Collection modified.");
}
}
public void Dispose() {
currentIndex = -1;
currentObject = null;
}
}
public void Clear() {
UsdCsPINVOKE.GfVec3dVector_Clear(swigCPtr);
}
public void Add(GfVec3d x) {
UsdCsPINVOKE.GfVec3dVector_Add(swigCPtr, GfVec3d.getCPtr(x));
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
private uint size() {
uint ret = UsdCsPINVOKE.GfVec3dVector_size(swigCPtr);
return ret;
}
private uint capacity() {
uint ret = UsdCsPINVOKE.GfVec3dVector_capacity(swigCPtr);
return ret;
}
private void reserve(uint n) {
UsdCsPINVOKE.GfVec3dVector_reserve(swigCPtr, n);
}
public GfVec3dVector() : this(UsdCsPINVOKE.new_GfVec3dVector__SWIG_0(), true) {
}
public GfVec3dVector(GfVec3dVector other) : this(UsdCsPINVOKE.new_GfVec3dVector__SWIG_1(GfVec3dVector.getCPtr(other)), true) {
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
public GfVec3dVector(int capacity) : this(UsdCsPINVOKE.new_GfVec3dVector__SWIG_2(capacity), true) {
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
private GfVec3d getitemcopy(int index) {
GfVec3d ret = new GfVec3d(UsdCsPINVOKE.GfVec3dVector_getitemcopy(swigCPtr, index), true);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private GfVec3d getitem(int index) {
GfVec3d ret = new GfVec3d(UsdCsPINVOKE.GfVec3dVector_getitem(swigCPtr, index), false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
private void setitem(int index, GfVec3d val) {
UsdCsPINVOKE.GfVec3dVector_setitem(swigCPtr, index, GfVec3d.getCPtr(val));
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
public void AddRange(GfVec3dVector values) {
UsdCsPINVOKE.GfVec3dVector_AddRange(swigCPtr, GfVec3dVector.getCPtr(values));
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
public GfVec3dVector GetRange(int index, int count) {
global::System.IntPtr cPtr = UsdCsPINVOKE.GfVec3dVector_GetRange(swigCPtr, index, count);
GfVec3dVector ret = (cPtr == global::System.IntPtr.Zero) ? null : new GfVec3dVector(cPtr, true);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public void Insert(int index, GfVec3d x) {
UsdCsPINVOKE.GfVec3dVector_Insert(swigCPtr, index, GfVec3d.getCPtr(x));
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
public void InsertRange(int index, GfVec3dVector values) {
UsdCsPINVOKE.GfVec3dVector_InsertRange(swigCPtr, index, GfVec3dVector.getCPtr(values));
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
public void RemoveAt(int index) {
UsdCsPINVOKE.GfVec3dVector_RemoveAt(swigCPtr, index);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
public void RemoveRange(int index, int count) {
UsdCsPINVOKE.GfVec3dVector_RemoveRange(swigCPtr, index, count);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
public static GfVec3dVector Repeat(GfVec3d value, int count) {
global::System.IntPtr cPtr = UsdCsPINVOKE.GfVec3dVector_Repeat(GfVec3d.getCPtr(value), count);
GfVec3dVector ret = (cPtr == global::System.IntPtr.Zero) ? null : new GfVec3dVector(cPtr, true);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public void Reverse() {
UsdCsPINVOKE.GfVec3dVector_Reverse__SWIG_0(swigCPtr);
}
public void Reverse(int index, int count) {
UsdCsPINVOKE.GfVec3dVector_Reverse__SWIG_1(swigCPtr, index, count);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
public void SetRange(int index, GfVec3dVector values) {
UsdCsPINVOKE.GfVec3dVector_SetRange(swigCPtr, index, GfVec3dVector.getCPtr(values));
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
}
}
| 33.722581 | 131 | 0.701454 | [
"Apache-2.0"
] | MrDice/usd-unity-sdk | src/USD.NET/generated/pxr/base/gf/GfVec3dVector.cs | 10,454 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace ScoreApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Error()
{
ViewData["RequestId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
return View();
}
}
}
| 21.083333 | 88 | 0.632411 | [
"MIT"
] | the-s-a-m/ScoreApp | ScoreApp/Controllers/HomeController.cs | 506 | C# |
// Sequência S
/*
Escreva um algoritmo para calcular e escrever o valor de S, sendo S dado pela
fórmula: S = 1 + 1/2 + 1/3 + … + 1/100
- Entrada
Não há nenhuma entrada neste problema.
- Saída
A saída contém um valor correspondente ao valor de S.
O valor deve ser impresso com dois dígitos após o ponto decimal.
*/
using System;
class DIO {
static void Main(string[] args) {
double a, c, S= 0;
for (a = 1; a <= 100; a++) {
c = 1 / a;
S += c;
}
var x = Math.Round(S,2);
Console.WriteLine(x);
}
} | 17.677419 | 77 | 0.59854 | [
"MIT"
] | BarbaraM1/desafios-bootcamps-dio | C#/Programando em C#/SequenciaS.cs | 559 | C# |
namespace JsExpressions
{
/// <summary>
/// Represents a JQuery object result, which is like an array of elements with some
/// helper methods to manipulate all of those elements.
/// </summary>
/// <remarks>
/// As you find the need to call jQuery methods that aren't here yet, please add them
/// to this type.
/// </remarks>
public class JQueryJsExpression : ArrayJsExpression<ElementJsExpression>
{
public JQueryJsExpression(JsExpression expression)
: base(expression, e => new ElementJsExpression(e))
{}
/// <summary>
/// Creates an expression that represents calling "prop(...)" on a jQuery object.
/// <example><code>var disabled = JQuery.Find(".submit-button").Prop("disabled");</code></example>
/// </summary>
/// <param name="propertyName"></param>
/// <returns></returns>
public JsExpression Prop(JsExpression propertyName)
{
return this["prop"].Call(propertyName);
}
}
} | 33 | 100 | 0.689394 | [
"MIT"
] | Aviacode/JsExpressions | JsExpressions/JQueryJsExpression.cs | 926 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TestingMVC.Models;
namespace TestingMVC.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 21.921053 | 112 | 0.596639 | [
"Apache-2.0"
] | ASCITSOL/asp.net | samples/aspnetcore/mvc/testing/TestingMVC/src/TestingMVC/Controllers/HomeController.cs | 835 | C# |
using Avalonia;
using System.Windows.Input;
namespace FluentAvalonia.UI.Input
{
/// <summary>
/// Provides a base class for defining the command behavior of an interactive UI element that
/// performs an action when invoked (such as sending an email, deleting an item, or submitting a form).
/// </summary>
public partial class XamlUICommand : AvaloniaObject, ICommand
{
public void NotifyCanExecuteChanged() => CanExecuteChanged?.Invoke(this, null);
public bool CanExecute(object param)
{
bool canExec = false;
var args = new CanExecuteRequestedEventArgs(param);
CanExecuteRequested?.Invoke(this, args);
canExec = args.CanExecute;
var command = Command;
if (command != null)
{
bool canExecCommand = command.CanExecute(param);
canExec = canExec && canExecCommand;
}
return canExec;
}
public void Execute(object param)
{
var args = new ExecuteRequestedEventArgs(param);
ExecuteRequested?.Invoke(this, args);
Command?.Execute(param);
}
}
}
| 23.068182 | 104 | 0.71133 | [
"MIT"
] | Apollo199999999/FluentAvalonia | FluentAvalonia/UI/Input/XamlUICommand.cs | 1,017 | C# |
namespace HREngine.Bots
{
class Pen_CS2_196 : PenTemplate //razorfenhunter
{
// kampfschrei:/ ruft einen eber (1/1) herbei.
public override int getPlayPenalty(Playfield p, Minion m, Minion target, int choice, bool isLethal)
{
return 0;
}
}
} | 26.545455 | 107 | 0.623288 | [
"MIT"
] | chi-rei-den/Silverfish | penalties/Pen_CS2_196.cs | 292 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Description
{
using System.Collections.Generic;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel;
using System.Xml;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
public class ServiceThrottlingBehavior : IServiceBehavior
{
//For V1: Default MaxConcurrentInstances should not enforce any throttle
//But still it should not be set to Int32.MAX;
//So compute default MaxInstances to be large enough to support MaxCalls & MaxSessions.
internal static int DefaultMaxConcurrentInstances = ServiceThrottle.DefaultMaxConcurrentCallsCpuCount + ServiceThrottle.DefaultMaxConcurrentSessionsCpuCount;
int calls = ServiceThrottle.DefaultMaxConcurrentCallsCpuCount;
int sessions = ServiceThrottle.DefaultMaxConcurrentSessionsCpuCount;
int instances = Int32.MaxValue;
bool maxInstanceSetExplicitly;
public int MaxConcurrentCalls
{
get { return this.calls; }
set
{
if (value <= 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxThrottleLimitMustBeGreaterThanZero0)));
this.calls = value;
}
}
public int MaxConcurrentSessions
{
get { return this.sessions; }
set
{
if (value <= 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxThrottleLimitMustBeGreaterThanZero0)));
this.sessions = value;
}
}
public int MaxConcurrentInstances
{
get
{
if (this.maxInstanceSetExplicitly)
{
return this.instances;
}
else
{
//For V1: Default MaxConcurrentInstances should not enforce any throttle
//But still it should not be set to Int32.MAX;
//So compute default MaxInstances to be large enough to support MaxCalls & MaxSessions.
this.instances = this.calls + this.sessions;
if (this.instances < 0)
{
this.instances = Int32.MaxValue;
}
}
return this.instances;
}
set
{
if (value <= 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxThrottleLimitMustBeGreaterThanZero0)));
this.instances = value;
this.maxInstanceSetExplicitly = true;
}
}
void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
}
void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
{
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
if (serviceHostBase == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serviceHostBase"));
ServiceThrottle serviceThrottle = serviceHostBase.ServiceThrottle;
serviceThrottle.MaxConcurrentCalls = this.calls;
serviceThrottle.MaxConcurrentSessions = this.sessions;
serviceThrottle.MaxConcurrentInstances = this.MaxConcurrentInstances;
for (int i = 0; i < serviceHostBase.ChannelDispatchers.Count; i++)
{
ChannelDispatcher channelDispatcher = serviceHostBase.ChannelDispatchers[i] as ChannelDispatcher;
if (channelDispatcher != null)
{
if (serviceThrottle != channelDispatcher.ServiceThrottle && channelDispatcher.IsServiceThrottleReplaced)
{
ServiceThrottle throttle = new ServiceThrottle(serviceHostBase);
throttle.MaxConcurrentCalls = this.calls;
throttle.MaxConcurrentSessions = this.sessions;
throttle.MaxConcurrentInstances = this.MaxConcurrentInstances;
channelDispatcher.ServiceThrottle = throttle;
}
else
{
channelDispatcher.ServiceThrottle = serviceThrottle;
}
}
}
}
}
}
| 40.653226 | 193 | 0.591351 | [
"MIT"
] | Abdalla-rabie/referencesource | System.ServiceModel/System/ServiceModel/Description/ServiceThrottlingBehavior.cs | 5,041 | C# |
using Wirehome.Core.Exceptions;
namespace Wirehome.Core.Components.Exceptions
{
public class ComponentNotFoundException : NotFoundException
{
public ComponentNotFoundException(string uid) :
base($"Component with UID '{uid}' not found.")
{
}
}
}
| 22.692308 | 63 | 0.657627 | [
"Apache-2.0"
] | SeppPenner/Wirehome.Core | Wirehome.Core/Components/Exceptions/ComponentNotFoundException.cs | 297 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PureCloudPlatform.Client.V2.Client;
namespace PureCloudPlatform.Client.V2.Model
{
/// <summary>
/// List of planning groups
/// </summary>
[DataContract]
public partial class PlanningGroupList : IEquatable<PlanningGroupList>
{
/// <summary>
/// Initializes a new instance of the <see cref="PlanningGroupList" /> class.
/// </summary>
/// <param name="Entities">Entities.</param>
public PlanningGroupList(List<PlanningGroup> Entities = null)
{
this.Entities = Entities;
}
/// <summary>
/// Gets or Sets Entities
/// </summary>
[DataMember(Name="entities", EmitDefaultValue=false)]
public List<PlanningGroup> Entities { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PlanningGroupList {\n");
sb.Append(" Entities: ").Append(Entities).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
Formatting = Formatting.Indented
});
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as PlanningGroupList);
}
/// <summary>
/// Returns true if PlanningGroupList instances are equal
/// </summary>
/// <param name="other">Instance of PlanningGroupList to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PlanningGroupList other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return true &&
(
this.Entities == other.Entities ||
this.Entities != null &&
this.Entities.SequenceEqual(other.Entities)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Entities != null)
hash = hash * 59 + this.Entities.GetHashCode();
return hash;
}
}
}
}
| 29.698413 | 85 | 0.528862 | [
"MIT"
] | F-V-L/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/PlanningGroupList.cs | 3,742 | C# |
using System;
using System.Collections.Generic;
using Xunit;
namespace SensorValidate.Tests
{
public class SensorValidatorTest
{
[Fact]
public void ReportsErrorWhenSOCJumps() {
Assert.False(SensorValidator.ValidateSOCreadings(
new List<double>{0.0, 0.01, 0.5, 0.51}
));
}
[Fact]
public void ReportsErrorWhenCurrentJumps() {
Assert.False(SensorValidator.ValidateCurrentReadings(
new List<double>{0.03, 0.03, 0.03, 0.33}
));
}
[Fact]
public void ReportsErrorWhenSOCEmpty()
{
Assert.False(SensorValidator.ValidateSOCreadings(
new List<double> { }
));
}
[Fact]
public void ReportsErrorWhenCurrentEmpty()
{
Assert.False(SensorValidator.ValidateCurrentReadings(
new List<double> { }
));
}
[Fact]
public void ReportsErrorWhenSOCReadingsHasNaN()
{
Assert.False(SensorValidator.ValidateSOCreadings(
new List<double> { Double.NaN, Double.NaN, 0.1, Double.NaN }
));
}
[Fact]
public void ReportsErrorWhenCurrentReadingsHasNaN()
{
Assert.False(SensorValidator.ValidateCurrentReadings(
new List<double> { 0.03, 0.03, Double.NaN, Double.NaN }
));
}
}
}
| 26 | 73 | 0.540486 | [
"MIT"
] | clean-code-craft-tcq-1/ms1snippet-cs-Abirami-Sivamani | SensorValidate.Tests/SensorValidatorTest.cs | 1,482 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace BlockChain_Demo.Models
{
//Source: https://www.c-sharpcorner.com/article/blockchain-basics-building-a-blockchain-in-net-core/
//Source: https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256?view=net-5.0
public class Block
{
public int BlockHeight {get;set;} // index that can be used as an ID
public DateTime TimeStamp { get; set; } // Time of block creation
public string PrevHash { get; set; } // hash of prev block
public string BlockHash { get; set; } // hash of this block
public string TransData { get; set; } // transactions
public int Nonce { get; set; }
public Block(DateTime timeStamp, string transData)
{
BlockHeight = 0;
TimeStamp = timeStamp;
TransData = transData;
BlockHash = GetBlockHash();
}
public string GetBlockHash()
{
SHA256 sha256Object = SHA256.Create();
// Convert all data to string to format for ASCII Encoding Result
string blockString = string.Format("{0}{1}{2}{3}", BlockHeight, TimeStamp, PrevHash, TransData);
// Convert to bytes since sha256 can only be passed byte[]
byte[] blockBytes = Encoding.ASCII.GetBytes(blockString);
// Use inherited ComputeHash method
byte[] blockBytesResult = sha256Object.ComputeHash(blockBytes);
// Convert the hash result back to a string
string blockHashResult = Convert.ToBase64String(blockBytesResult);
return blockHashResult;
}
}
}
| 38.695652 | 108 | 0.643258 | [
"MIT"
] | coffeelabor/DS_Algo | BlockChain_Demo/Models/BlockChain/Block.cs | 1,782 | C# |
namespace EnvironmentAssessment.Common.VimApi
{
public enum VirtualMachineMovePriority
{
lowPriority,
highPriority,
defaultPriority
}
}
| 14.5 | 45 | 0.8 | [
"MIT"
] | octansIt/environmentassessment | EnvironmentAssessment.Wizard/Common/VimApi/V/VirtualMachineMovePriority.cs | 145 | C# |
using System;
namespace Mcma.Client.Azure.AzureAD
{
public class AzureADAuthContext
{
public string Scope { get; set; }
public void ValidateScope()
{
if (string.IsNullOrWhiteSpace(Scope))
throw new Exception("Azure AD auth context must specify a scope.");
}
}
} | 22.333333 | 83 | 0.597015 | [
"Apache-2.0"
] | ebu/mcma-libraries-dotnet | Azure/Mcma.Client.Azure/AzureAD/AzureADAuthContext.cs | 335 | C# |
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace PInvoke
{
/// <content>
/// Contains the <see cref="MagicType"/> nested type.
/// </content>
public partial struct IMAGE_OPTIONAL_HEADER
{
/// <summary>
/// Expected values for the <see cref="Magic"/> field.
/// </summary>
public enum MagicType : ushort
{
/// <summary>
/// The file is a 32-bit executable image.
/// </summary>
IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10b,
/// <summary>
/// The file is a 64-bit executable image.
/// </summary>
IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20b,
/// <summary>
/// The file is a ROM image.
/// </summary>
IMAGE_ROM_OPTIONAL_HDR_MAGIC = 0x107,
}
}
} | 30.21875 | 101 | 0.544984 | [
"MIT"
] | AArnott/PInvoke.exp | src/Windows.Core/IMAGE_OPTIONAL_HEADER+MagicType.cs | 969 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.EntityFrameworkCore.Sqlite.Metadata.Internal;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static class SqliteAnnotationNames
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string Prefix = "Sqlite:";
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string LegacyAutoincrement = "Autoincrement";
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string Autoincrement = Prefix + LegacyAutoincrement;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string InlinePrimaryKey = Prefix + "InlinePrimaryKey";
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string InlinePrimaryKeyName = Prefix + "InlinePrimaryKeyName";
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string InitSpatialMetaData = Prefix + "InitSpatialMetaData";
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string Srid = Prefix + "Srid";
}
| 63.885714 | 109 | 0.719365 | [
"MIT"
] | Applesauce314/efcore | src/EFCore.Sqlite.Core/Metadata/Internal/SqliteAnnotationNames.cs | 4,472 | C# |
namespace EasyCaching.ResponseCaching
{
using EasyCaching.Core.Internal;
using Microsoft.AspNetCore.Builder;
/// <summary>
/// EasyCaching response caching extensions.
/// </summary>
public static class EasyCachingResponseCachingExtensions
{
/// <summary>
/// Uses the easy caching response caching.
/// </summary>
/// <returns>The easy caching response caching.</returns>
/// <param name="app">App.</param>
public static IApplicationBuilder UseEasyCachingResponseCaching(this IApplicationBuilder app)
{
ArgumentCheck.NotNull(app, nameof(app));
return app.UseMiddleware<EasyCachingResponseCachingMiddleware>();
}
}
}
| 30.833333 | 101 | 0.652703 | [
"MIT"
] | alexinea/EasyCaching | src/EasyCaching.ResponseCaching/EasyCachingResponseCachingExtensions.cs | 742 | 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 Microsoft.VisualStudio.TestTools.UnitTesting;
using Org.Apache.REEF.Tang.Annotations;
using Org.Apache.REEF.Tang.Implementations.Tang;
using Org.Apache.REEF.Tang.Interface;
using Org.Apache.REEF.Tang.Util;
namespace Org.Apache.REEF.Tang.Tests.Injection
{
[TestClass]
public class TestNamedParameter
{
[TestMethod]
public void TestOptionalParameter()
{
ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder();
cb.BindNamedParameter<StringTest.NamedString, string>(GenericType<StringTest.NamedString>.Class, "foo");
IInjector i = TangFactory.GetTang().NewInjector(cb.Build());
var o = i.GetInstance<StringTest>();
o.Verify("foo");
}
[TestMethod]
public void TestOptionalParameterWithDefault()
{
ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder();
IInjector i = TangFactory.GetTang().NewInjector(cb.Build());
var o = i.GetInstance<StringTest>();
o.Verify(" ");
}
[TestMethod]
public void TestBoolParameter()
{
ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder();
cb.BindNamedParameter<BooleanTest.NamedBool, bool>(GenericType<BooleanTest.NamedBool>.Class, "true");
IInjector i = TangFactory.GetTang().NewInjector(cb.Build());
var o = i.GetInstance<BooleanTest>();
o.Verify(true);
}
[TestMethod]
public void TestBoolUpperCaseParameter()
{
ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder();
cb.BindNamedParameter<BooleanTest.NamedBool, bool>(GenericType<BooleanTest.NamedBool>.Class, "True");
IInjector i = TangFactory.GetTang().NewInjector(cb.Build());
var o = i.GetInstance<BooleanTest>();
o.Verify(true);
}
[TestMethod]
public void TestBoolParameterWithDefault()
{
ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder();
IInjector i = TangFactory.GetTang().NewInjector(cb.Build());
var o = i.GetInstance<BooleanTest>();
o.Verify(false);
}
[TestMethod]
public void TestByteParameter()
{
ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder();
cb.BindNamedParameter<ByteTest.NamedByte, byte>(GenericType<ByteTest.NamedByte>.Class, "6");
IInjector i = TangFactory.GetTang().NewInjector(cb.Build());
var o = i.GetInstance<ByteTest>();
o.Verify(6);
}
[TestMethod]
public void TestByteArrayParameter()
{
ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder();
string input = "abcde";
cb.BindNamedParameter<ByteArrayTest.NamedByteArray, byte[]>(GenericType<ByteArrayTest.NamedByteArray>.Class, input);
IInjector i = TangFactory.GetTang().NewInjector(cb.Build());
var o = i.GetInstance<ByteArrayTest>();
byte[] bytes = new byte[input.Length * sizeof(char)];
System.Buffer.BlockCopy(input.ToCharArray(), 0, bytes, 0, bytes.Length);
Assert.IsTrue(o.Verify(bytes));
}
[TestMethod]
public void TestCharParameter()
{
ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder();
cb.BindNamedParameter<CharTest.NamedChar, char>(GenericType<CharTest.NamedChar>.Class, "C");
IInjector i = TangFactory.GetTang().NewInjector(cb.Build());
var o = i.GetInstance<CharTest>();
o.Verify('C');
}
[TestMethod]
public void TestShortParameter()
{
ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder();
cb.BindNamedParameter<Int16Test.NamedShort, short>(GenericType<Int16Test.NamedShort>.Class, "8");
IInjector i = TangFactory.GetTang().NewInjector(cb.Build());
var o = i.GetInstance<Int16Test>();
o.Verify(8);
}
[TestMethod]
public void TestIntParameter()
{
ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder();
cb.BindNamedParameter<Int32Test.NamedInt, int>(GenericType<Int32Test.NamedInt>.Class, "8");
IInjector i = TangFactory.GetTang().NewInjector(cb.Build());
var o = i.GetInstance<Int32Test>();
o.Verify(8);
}
[TestMethod]
public void TestLongParameter()
{
ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder();
cb.BindNamedParameter<Int64Test.NamedLong, long>(GenericType<Int64Test.NamedLong>.Class, "8777");
IInjector i = TangFactory.GetTang().NewInjector(cb.Build());
var o = i.GetInstance<Int64Test>();
o.Verify(8777);
}
[TestMethod]
public void TestFloatParameter()
{
ICsConfigurationBuilder cb = TangFactory.GetTang().NewConfigurationBuilder();
cb.BindNamedParameter<FloatTest.NamedSingle, float>(GenericType<FloatTest.NamedSingle>.Class, "3.5");
IInjector i = TangFactory.GetTang().NewInjector(cb.Build());
var o = i.GetInstance<FloatTest>();
float x = 3.5F;
o.Verify(x);
}
}
public class StringTest
{
private readonly string str;
[Inject]
public StringTest([Parameter(typeof(NamedString))] string s)
{
this.str = s;
}
public void Verify(string s)
{
Assert.AreEqual(s, str);
}
[NamedParameter(DefaultValue = " ")]
public class NamedString : Name<string>
{
}
}
public class CharTest
{
private readonly char c;
[Inject]
public CharTest([Parameter(typeof(NamedChar))] char c)
{
this.c = c;
}
public void Verify(char s)
{
Assert.AreEqual(s, c);
}
[NamedParameter(DefaultValue = " ")]
public class NamedChar : Name<char>
{
}
}
public class ByteTest
{
private readonly byte b;
[Inject]
public ByteTest([Parameter(typeof(NamedByte))] byte b)
{
this.b = b;
}
public void Verify(byte v)
{
Assert.AreEqual(v, b);
}
[NamedParameter(DefaultValue = "7")]
public class NamedByte : Name<byte>
{
}
}
public class BooleanTest
{
private readonly bool b;
[Inject]
public BooleanTest([Parameter(typeof(NamedBool))] bool b)
{
this.b = b;
}
public void Verify(bool v)
{
Assert.AreEqual(v, b);
}
[NamedParameter(DefaultValue = "false")]
public class NamedBool : Name<bool>
{
}
}
public class ByteArrayTest
{
private readonly byte[] b;
[Inject]
public ByteArrayTest([Parameter(typeof(NamedByteArray))] byte[] b)
{
this.b = b;
}
public bool Verify(byte[] v)
{
if (v.Length != b.Length)
{
return false;
}
for (int i = 0; i < v.Length; i++)
{
if (v[i] != b[i])
{
return false;
}
}
return true;
}
[NamedParameter]
public class NamedByteArray : Name<byte[]>
{
}
}
public class Int16Test
{
private readonly short s;
[Inject]
public Int16Test([Parameter(typeof(NamedShort))] short s)
{
this.s = s;
}
public void Verify(short v)
{
Assert.AreEqual(v, s);
}
[NamedParameter(DefaultValue = "3")]
public class NamedShort : Name<short>
{
}
}
public class Int32Test
{
private readonly int i;
[Inject]
public Int32Test([Parameter(typeof(NamedInt))] int i)
{
this.i = i;
}
public void Verify(int v)
{
Assert.AreEqual(v, i);
}
[NamedParameter(DefaultValue = "3")]
public class NamedInt : Name<int>
{
}
}
public class Int64Test
{
private readonly long l;
[Inject]
public Int64Test([Parameter(typeof(NamedLong))] long l)
{
this.l = l;
}
public void Verify(int v)
{
Assert.AreEqual(v, l);
}
[NamedParameter(DefaultValue = "34567")]
public class NamedLong : Name<long>
{
}
}
public class FloatTest
{
private readonly float f;
[Inject]
public FloatTest([Parameter(typeof(NamedSingle))] float f)
{
this.f = f;
}
public void Verify(float v)
{
Assert.AreEqual(v, f);
}
[NamedParameter(DefaultValue = "12.5")]
public class NamedSingle : Name<float>
{
}
}
} | 29.963483 | 129 | 0.548983 | [
"Apache-2.0"
] | yunseong/incubator-reef | lang/cs/Org.Apache.REEF.Tang.Tests/Injection/TestNamedParameter.cs | 10,314 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CITITO.BusinessObjects;
using CITITO.BusinessServices;
using CITITO.BusinessControls;
using System.Data.SqlClient;
using MetroFramework.Forms;
namespace CITITO
{
public partial class frm_TaskCodeModify : MetroForm
{
SqlConnection conn;
//Start Pass insatance when form is already opend or not
private static frm_TaskCodeModify _instance;
public static frm_TaskCodeModify GetInstance(String uTaskCode, String uDescription, String uUOM, String uQuota, String uProject, String uProcessCode, int uSkip)
{
if (_instance == null || _instance.IsDisposed)
{
String mTaskCode = uTaskCode;
String mDescription = uDescription;
String mUOM = uUOM;
String mQuota = uQuota;
String mProject = uProject;
String mProcessCode = uProcessCode;
int mSkip = uSkip;
_instance = new frm_TaskCodeModify(mTaskCode, mDescription, mUOM, mQuota, mProject, mProcessCode, mSkip);
}
return _instance;
}
public frm_TaskCodeModify(String uTaskCode, String uDescription, String uUOM, String uQuota, String uProject, String uProcessCode, int uSkip)
{
InitializeComponent();
//Parameters Initialize
txtTaskCode.Text = uTaskCode;
txtDescription.Text = uDescription;
cmbUOM.Text = uUOM;
lbltmpProject.Text = uProject;
lbltmpProcessCode.Text = uProcessCode;
numericUpDownQuota.Value = int.Parse(uQuota);
if (uSkip==1)
{
chkOutputValidation.Checked = true;
}
if (uSkip == 0)
{
chkOutputValidation.Checked = false;
}
tmpTask.Text = uTaskCode;
tmpDes.Text = uDescription;
tmpUOM.Text = uUOM;
tmpQuota.Text = uQuota;
lbltmpSkip.Text = uSkip.ToString();
//Global Variables
conn = new SqlConnection(Properties.Settings.Default.CITITOConnectionString);
conn.Open();
}
//Exit button
private void btnExit_Click(object sender, EventArgs e)
{
Application.OpenForms["frm_TaskCodeRegister"].BringToFront();
this.Close();
}
//Modify
private void btnUpdate_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(txtDescription.Text))
{
MetroFramework.MetroMessageBox.Show(this, "\nDescription field cannot be empty.", "Invalid!", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtDescription.Focus();
return;
}
if (String.IsNullOrEmpty(cmbUOM.Text))
{
MetroFramework.MetroMessageBox.Show(this, "\nPlease enter UOM.", "Invalid!", MessageBoxButtons.OK, MessageBoxIcon.Error);
cmbUOM.Focus();
return;
}
if (numericUpDownQuota.Value==0)
{
MetroFramework.MetroMessageBox.Show(this, "\nQuota cannoth be zero.", "Invalid!", MessageBoxButtons.OK, MessageBoxIcon.Error);
numericUpDownQuota.Focus();
return;
}
if (String.IsNullOrEmpty(numericUpDownQuota.Text))
{
MetroFramework.MetroMessageBox.Show(this, "\nQuota cannoth be empty.", "Invalid!", MessageBoxButtons.OK, MessageBoxIcon.Error);
numericUpDownQuota.Focus();
return;
}
string tempTask = tmpTask.Text;
string tempDes = tmpDes.Text;
string tempUOM = tmpUOM.Text;
int tempQuota = int.Parse(tmpQuota.Text);
string tempProject = lbltmpProject.Text;
string tempProcessCode = lbltmpProcessCode.Text;
int mCheck = 0;
//Check User output validation /* 0 - Yes, 1 - No */
if (chkOutputValidation.Checked)
{
mCheck = 1; /* 1 - No */
}
else
{
mCheck = 0; /* 0 - Yes */
}
DialogResult resulta = MetroFramework.MetroMessageBox.Show(this, "\nDo you want to modify task code?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (resulta == DialogResult.Yes)
{
TaskHeaderMng mTaskHeaderMng = new TaskHeaderMng(this.conn);
TaskDetailMng mTaskDetailMng = new TaskDetailMng(this.conn);
if (mTaskDetailMng.UpdateTaskCodeDetail(txtTaskCode.Text, txtDescription.Text, cmbUOM.Text, int.Parse(numericUpDownQuota.Value.ToString()), tempTask, tempDes, tempUOM, tempQuota, tempProcessCode) >0)
{
mTaskHeaderMng.UpdateTaskCodeHeader(tempTask, tempProject, tempProcessCode, mCheck);
MetroFramework.MetroMessageBox.Show(this, "\n Task code details has been updated!", "Modified!", MessageBoxButtons.OK, MessageBoxIcon.Information);
Application.OpenForms["frm_ProjectRegistrationPanel"].BringToFront();
this.Close();
}
}
else
{
Application.OpenForms["frm_ProjectRegistrationPanel"].BringToFront();
this.Close();
}
}
private void frm_TaskCodeModify_Load(object sender, EventArgs e)
{
}
}
}
| 35.266667 | 215 | 0.58309 | [
"MIT"
] | AselaWD/CITITO | CITITO-Solution/CITITO/CITITO/CITITO/frm_TaskCodeModify.cs | 5,821 | C# |
// [[[[INFO>
// Copyright 2015 Raging Bool (http://ragingbool.org, https://github.com/RagingBool)
//
// 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.
//
// For more information check https://github.com/RagingBool/RagingBool.Carcosa
// ]]]]
using Akka.Actor;
using Epicycle.Commons;
using Epicycle.Commons.FileSystem;
using Epicycle.Commons.Time;
using Epicycle.Input.Keyboard;
using RagingBool.Carcosa.Core.Control;
using RagingBool.Carcosa.Core.Stage;
using RagingBool.Carcosa.Core.Workspace;
using RagingBool.Carcosa.Devices;
using RagingBool.Carcosa.Devices.InputControl;
using RagingBool.Carcosa.Devices.InputControl.ControlBoard;
using System.Collections.Generic;
using System.Threading;
namespace RagingBool.Carcosa.Core
{
public sealed class Carcosa : ICarcosa
{
private readonly IClock _clock;
private readonly IFileSystem _fileSystem;
private readonly CarcosaWorkspace _workspace;
private readonly IStage _stage;
private readonly Thread _updateThread;
private readonly OverlappingControlBoards _controlBoards;
private IList<IDevice> _devices;
private IList<IUpdatable> _updatables;
private readonly ActorSystem _actorSystem;
private IActorRef _carcosaActor;
private bool _isRunning;
public Carcosa(IClock clock, IFileSystem fileSystem, FileSystemPath workspacePath)
{
ArgAssert.NotNull(clock, "clock");
ArgAssert.NotNull(fileSystem, "fileSystem");
ArgAssert.NotNull(workspacePath, "workspacePath");
_clock = clock;
_fileSystem = fileSystem;
_workspace = new CarcosaWorkspace(_fileSystem, workspacePath);
_devices = new List<IDevice>();
_updatables = new List<IUpdatable>();
_controlBoards = new OverlappingControlBoards();
_stage = new PartyStage(_clock, _workspace, _controlBoards);
_updateThread = new Thread(UpdateThreadLoop);
_actorSystem = ActorSystem.Create("Carcosa");
_isRunning = false;
}
public ICarcosaWorkspace Workspace
{
get { return _workspace; }
}
public void Start()
{
foreach(var device in _devices)
{
device.Connect();
}
_stage.Start();
_carcosaActor = _actorSystem.ActorOf<CarcosaActor>(_workspace.WorkspaceName);
_carcosaActor.Tell(new StartMessage(_clock.Time));
_isRunning = true;
_updateThread.Start();
}
public void Stop()
{
foreach (var device in _devices)
{
device.Disconnect();
}
_isRunning = false;
_carcosaActor.Tell(new StopMessage(_clock.Time));
_stage.Stop();
_actorSystem.Shutdown();
}
public void AwaitTermination()
{
_actorSystem.AwaitTermination();
}
public void RegisterDevice(IDevice device)
{
_devices.Add(device);
}
public void RegisterUpdatable(IUpdatable updatable)
{
_updatables.Add(updatable);
}
public void RegisterControlBoard(IControlBoard controlBoard)
{
_controlBoards.Register(controlBoard);
}
public void RegisterWindowsKeyboard(
IKeyboard<WindowsKey, TimedKey> keyboard,
KeyboardControlBoardConfig<WindowsKey> keyboardControlBoardConfig)
{
_carcosaActor.Tell(new RegisterWindowsKeyboardMessage(keyboard, keyboardControlBoardConfig));
}
private void UpdateThreadLoop()
{
while(_isRunning)
{
foreach (var updatable in _updatables)
{
updatable.Update();
}
_carcosaActor.Tell(new UpdateMessage(_clock.Time));
_stage.Update();
Thread.Sleep(10);
}
}
}
}
| 29.987013 | 105 | 0.625379 | [
"Apache-2.0"
] | RagingBool/RagingBool.Carcosa | projects/RagingBool.Carcosa.Core_cs/Carcosa.cs | 4,620 | 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.IO;
using System.Collections;
using NUnit.Framework;
using NStorage.Common;
using NStorage.Test;
using NStorage.FileSystem;
using NStorage.NIO;
using System.Collections.Generic;
using NStorage.Utility;
namespace NStorage.Test.POIFS.FileSystem
{
/// <summary>
/// Summary description for TestNPOIFSMiniStore
/// </summary>
[TestFixture]
public class TestNPOIFSMiniStore
{
private static POIDataSamples _inst = POIDataSamples.GetPOIFSInstance();
public TestNPOIFSMiniStore()
{
//
// TODO: Add constructor logic here
//
}
[Test]
public void TestNextBlock()
{
// It's the same on 512 byte and 4096 byte block files!
NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.GetFile("BlockSize512.zvi"));
NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize512.zvi"));
NPOIFSFileSystem fsC = new NPOIFSFileSystem(_inst.GetFile("BlockSize4096.zvi"));
NPOIFSFileSystem fsD = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize4096.zvi"));
foreach (NPOIFSFileSystem fs in new NPOIFSFileSystem[] { fsA, fsB, fsC, fsD })
{
NPOIFSMiniStore ministore = fs.GetMiniStore();
// 0 -> 51 is one stream
for (int i = 0; i < 50; i++)
{
Assert.AreEqual(i + 1, ministore.GetNextBlock(i));
}
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(50));
// 51 -> 103 is the next
for (int i = 51; i < 103; i++)
{
Assert.AreEqual(i + 1, ministore.GetNextBlock(i));
}
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(103));
// Then there are 3 one block ones
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(104));
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(105));
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(106));
// 107 -> 154 is the next
for (int i = 107; i < 154; i++)
{
Assert.AreEqual(i + 1, ministore.GetNextBlock(i));
}
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(154));
// 155 -> 160 is the next
for (int i = 155; i < 160; i++)
{
Assert.AreEqual(i + 1, ministore.GetNextBlock(i));
}
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(160));
// 161 -> 166 is the next
for (int i = 161; i < 166; i++)
{
Assert.AreEqual(i + 1, ministore.GetNextBlock(i));
}
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(166));
// 167 -> 172 is the next
for (int i = 167; i < 172; i++)
{
Assert.AreEqual(i + 1, ministore.GetNextBlock(i));
}
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(172));
// Now some short ones
Assert.AreEqual(174, ministore.GetNextBlock(173));
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(174));
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(175));
Assert.AreEqual(177, ministore.GetNextBlock(176));
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(177));
Assert.AreEqual(179, ministore.GetNextBlock(178));
Assert.AreEqual(180, ministore.GetNextBlock(179));
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(180));
// 181 onwards is free
for (int i = 181; i < fs.GetBigBlockSizeDetails().GetBATEntriesPerBlock(); i++)
{
Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(i));
}
fs.Close();
}
}
[Test]
public void TestGetBlock()
{
// It's the same on 512 byte and 4096 byte block files!
NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.GetFile("BlockSize512.zvi"));
NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize512.zvi"));
NPOIFSFileSystem fsC = new NPOIFSFileSystem(_inst.GetFile("BlockSize4096.zvi"));
NPOIFSFileSystem fsD = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize4096.zvi"));
foreach (NPOIFSFileSystem fs in new NPOIFSFileSystem[] { fsA, fsB, fsC, fsD })
{
// Mini stream should be at big block zero
Assert.AreEqual(0, fs.PropertyTable.Root.StartBlock);
// Grab the ministore
NPOIFSMiniStore ministore = fs.GetMiniStore();
ByteBuffer b;
// Runs from the start of the data section in 64 byte chungs
b = ministore.GetBlockAt(0);
Assert.AreEqual((byte)0x9e, b[0]);
Assert.AreEqual((byte)0x75, b[1]);
Assert.AreEqual((byte)0x97, b[2]);
Assert.AreEqual((byte)0xf6, b[3]);
Assert.AreEqual((byte)0xff, b[4]);
Assert.AreEqual((byte)0x21, b[5]);
Assert.AreEqual((byte)0xd2, b[6]);
Assert.AreEqual((byte)0x11, b[7]);
// And the next block
b = ministore.GetBlockAt(1);
Assert.AreEqual((byte)0x00, b[0]);
Assert.AreEqual((byte)0x00, b[1]);
Assert.AreEqual((byte)0x03, b[2]);
Assert.AreEqual((byte)0x00, b[3]);
Assert.AreEqual((byte)0x12, b[4]);
Assert.AreEqual((byte)0x02, b[5]);
Assert.AreEqual((byte)0x00, b[6]);
Assert.AreEqual((byte)0x00, b[7]);
// Check the last data block
b = ministore.GetBlockAt(180);
Assert.AreEqual((byte)0x30, b[0]);
Assert.AreEqual((byte)0x00, b[1]);
Assert.AreEqual((byte)0x00, b[2]);
Assert.AreEqual((byte)0x00, b[3]);
Assert.AreEqual((byte)0x00, b[4]);
Assert.AreEqual((byte)0x00, b[5]);
Assert.AreEqual((byte)0x00, b[6]);
Assert.AreEqual((byte)0x80, b[7]);
// And the rest until the end of the big block is zeros
for (int i = 181; i < 184; i++)
{
b = ministore.GetBlockAt(i);
Assert.AreEqual((byte)0, b[0]);
Assert.AreEqual((byte)0, b[1]);
Assert.AreEqual((byte)0, b[2]);
Assert.AreEqual((byte)0, b[3]);
Assert.AreEqual((byte)0, b[4]);
Assert.AreEqual((byte)0, b[5]);
Assert.AreEqual((byte)0, b[6]);
Assert.AreEqual((byte)0, b[7]);
}
fs.Close();
}
}
[Test]
public void TestGetFreeBlockWithSpare()
{
NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.GetFile("BlockSize512.zvi"));
NPOIFSMiniStore ministore = fs.GetMiniStore();
// Our 2nd SBAT block has spares
Assert.AreEqual(false, ministore.GetBATBlockAndIndex(0).Block.HasFreeSectors);
Assert.AreEqual(true, ministore.GetBATBlockAndIndex(128).Block.HasFreeSectors);
// First free one at 181
Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(181));
Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(182));
Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(183));
Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(184));
// Ask, will get 181
Assert.AreEqual(181, ministore.GetFreeBlock());
// Ask again, will still get 181 as not written to
Assert.AreEqual(181, ministore.GetFreeBlock());
// Allocate it, then ask again
ministore.SetNextBlock(181, POIFSConstants.END_OF_CHAIN);
Assert.AreEqual(182, ministore.GetFreeBlock());
fs.Close();
}
[Test]
public void TestGetFreeBlockWithNonSpare()
{
NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize512.zvi"));
NPOIFSMiniStore ministore = fs.GetMiniStore();
// We've spare ones from 181 to 255
for (int i = 181; i < 256; i++)
{
Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(i));
}
// Check our SBAT free stuff is correct
Assert.AreEqual(false, ministore.GetBATBlockAndIndex(0).Block.HasFreeSectors);
Assert.AreEqual(true, ministore.GetBATBlockAndIndex(128).Block.HasFreeSectors);
// Allocate all the spare ones
for (int i = 181; i < 256; i++)
{
ministore.SetNextBlock(i, POIFSConstants.END_OF_CHAIN);
}
// SBAT are now full, but there's only the two
Assert.AreEqual(false, ministore.GetBATBlockAndIndex(0).Block.HasFreeSectors);
Assert.AreEqual(false, ministore.GetBATBlockAndIndex(128).Block.HasFreeSectors);
try
{
Assert.AreEqual(false, ministore.GetBATBlockAndIndex(256).Block.HasFreeSectors);
Assert.Fail("Should only be two SBATs");
}
catch (ArgumentOutOfRangeException) { }
// Now ask for a free one, will need to extend the SBAT chain
Assert.AreEqual(256, ministore.GetFreeBlock());
Assert.AreEqual(false, ministore.GetBATBlockAndIndex(0).Block.HasFreeSectors);
Assert.AreEqual(false, ministore.GetBATBlockAndIndex(128).Block.HasFreeSectors);
Assert.AreEqual(true, ministore.GetBATBlockAndIndex(256).Block.HasFreeSectors);
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(254)); // 2nd SBAT
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(255)); // 2nd SBAT
Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(256)); // 3rd SBAT
Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(257)); // 3rd SBAT
fs.Close();
}
[Test]
public void TestCreateBlockIfNeeded()
{
NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize512.zvi"));
NPOIFSMiniStore ministore = fs.GetMiniStore();
// 178 -> 179 -> 180, 181+ is free
Assert.AreEqual(179, ministore.GetNextBlock(178));
Assert.AreEqual(180, ministore.GetNextBlock(179));
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(180));
for (int i = 181; i < 256; i++)
{
Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(i));
}
// However, the ministore data only covers blocks to 183
for (int i = 0; i <= 183; i++)
{
ministore.GetBlockAt(i);
}
try
{
ministore.GetBlockAt(184);
Assert.Fail("No block at 184");
}
catch (IndexOutOfRangeException) { }
// The ministore itself is made up of 23 big blocks
IEnumerator<ByteBuffer> it = new NPOIFSStream(fs, fs.Root.Property.StartBlock).GetBlockIterator();
int count = 0;
while (it.MoveNext())
{
count++;
//it.MoveNext();
}
Assert.AreEqual(23, count);
// Ask it to get block 184 with creating, it will do
ministore.CreateBlockIfNeeded(184);
// The ministore should be one big block bigger now
it = new NPOIFSStream(fs, fs.Root.Property.StartBlock).GetBlockIterator();
count = 0;
while (it.MoveNext())
{
count++;
//it.MoveNext();
}
Assert.AreEqual(24, count);
// The mini block block counts now run to 191
for (int i = 0; i <= 191; i++)
{
ministore.GetBlockAt(i);
}
try
{
ministore.GetBlockAt(192);
Assert.Fail("No block at 192");
}
catch (IndexOutOfRangeException) { }
// Now try writing through to 192, check that the SBAT and blocks are there
byte[] data = new byte[15 * 64];
NPOIFSStream stream = new NPOIFSStream(ministore, 178);
stream.UpdateContents(data);
// Check now
Assert.AreEqual(179, ministore.GetNextBlock(178));
Assert.AreEqual(180, ministore.GetNextBlock(179));
Assert.AreEqual(181, ministore.GetNextBlock(180));
Assert.AreEqual(182, ministore.GetNextBlock(181));
Assert.AreEqual(183, ministore.GetNextBlock(182));
Assert.AreEqual(184, ministore.GetNextBlock(183));
Assert.AreEqual(185, ministore.GetNextBlock(184));
Assert.AreEqual(186, ministore.GetNextBlock(185));
Assert.AreEqual(187, ministore.GetNextBlock(186));
Assert.AreEqual(188, ministore.GetNextBlock(187));
Assert.AreEqual(189, ministore.GetNextBlock(188));
Assert.AreEqual(190, ministore.GetNextBlock(189));
Assert.AreEqual(191, ministore.GetNextBlock(190));
Assert.AreEqual(192, ministore.GetNextBlock(191));
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, ministore.GetNextBlock(192));
for (int i = 193; i < 256; i++)
{
Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(i));
}
fs.Close();
}
}
}
| 42.17663 | 110 | 0.565427 | [
"Apache-2.0"
] | Neuzilla/NStorage | NStorage.Test/POIFS/FileSystem/TestNPOIFSMiniStore.cs | 15,523 | C# |
/*
* Copyright (c) 2013-2015, SteamDB. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
using System;
using System.IO;
using SteamKit2;
namespace SteamDatabaseBackend
{
static class Bootstrapper
{
private static bool CleaningUp;
public static void Main()
{
AppDomain.CurrentDomain.UnhandledException += OnSillyCrashHandler;
Console.Title = "Steam Database";
// Load settings file before logging as it can be enabled in settings
Settings.Load();
Log.WriteInfo("Bootstrapper", "Copyright (c) 2013-2015, SteamDB. See LICENSE file for more information.");
// Just create deepest folder we will use in the app
var filesDir = Path.Combine(Application.Path, "files", ".support", "chunks");
Directory.CreateDirectory(filesDir);
Settings.Initialize();
LocalConfig.Load();
if (Settings.Current.SteamKitDebug)
{
DebugLog.AddListener(new Log.SteamKitLogger());
DebugLog.Enabled = true;
}
Console.CancelKeyPress += OnCancelKey;
Application.Init();
}
private static void OnCancelKey(object sender, ConsoleCancelEventArgs e)
{
if (CleaningUp)
{
Log.WriteInfo("Bootstrapper", "Forcing exit");
Environment.Exit(0);
return;
}
e.Cancel = true;
CleaningUp = true;
Application.Cleanup();
}
private static void OnSillyCrashHandler(object sender, UnhandledExceptionEventArgs args)
{
var parentException = args.ExceptionObject as Exception;
if (parentException is AggregateException aggregateException)
{
aggregateException.Flatten().Handle(e =>
{
ErrorReporter.Notify("Bootstrapper", e);
return false;
});
}
else
{
ErrorReporter.Notify("Bootstrapper", parentException);
}
if (args.IsTerminating)
{
AppDomain.CurrentDomain.UnhandledException -= OnSillyCrashHandler;
IRC.Instance.SendOps("💀🔫 Backend process is going to crash, send help.");
Application.Cleanup();
}
}
}
}
| 27.784946 | 118 | 0.547601 | [
"BSD-3-Clause"
] | NotEnoughGames/SteamDatabaseBackend | Bootstrapper.cs | 2,592 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Elevator
{
public class Waitzone : MonoBehaviour
{
public Cover[] GetCover(float radius, LayerMask coverMask)
{
List<Cover> result = new List<Cover>();
Collider[] hits = Physics.OverlapSphere(transform.position, radius, coverMask, QueryTriggerInteraction.Ignore);
foreach (Collider col in hits)
{
Cover c = col.GetComponent<Cover>();
if (c != null)
{
if (!result.Contains(c))
result.Add(c);
}
}
return result.ToArray();
}
}
} | 26 | 123 | 0.533156 | [
"MIT"
] | Mfknudsen/Galaxy-War | Galaxy War/Assets/Scripts/Buildings/Elevator/Waitzone.cs | 756 | C# |
namespace CandidContributions.Core.Models.Configuration
{
public class SpreakerApiOptions
{
public bool Enabled { get; set; }
public int ShowId { get; set; }
}
}
| 17.545455 | 55 | 0.642487 | [
"MIT"
] | CandidContributions/CanConCloud | src/CandidContributions.Core/Models/Configuration/SpreakerApiOptions.cs | 195 | C# |
/*
*
* (c) Copyright Ascensio System Limited 2010-2020
*
* 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 ASC.Web.Studio.Utility;
using ASC.Web.Projects.Resources;
namespace ASC.Web.Projects
{
public partial class ProjectTeam : BasePage
{
protected override void PageLoad()
{
Title = HeaderStringHelper.GetPageTitle(ProjectResource.ProjectTeam);
}
}
} | 29.516129 | 81 | 0.718033 | [
"Apache-2.0"
] | Ektai-Solution-Pty-Ltd/CommunityServer | web/studio/ASC.Web.Studio/Products/Projects/ProjectTeam.aspx.cs | 915 | C# |
using Microsoft.Extensions.Logging;
using Netension.Extensions.Correlation;
using Netension.Extensions.Correlation.Defaults;
using Netension.Request.Abstraction.Requests;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Netension.Request.Http.Wrappers
{
public class HttpCorrelationWrapper : IHttpRequestWrapper
{
private readonly ICorrelationAccessor _correlationAccessor;
private readonly IHttpRequestWrapper _next;
private readonly ILogger<HttpCorrelationWrapper> _logger;
public HttpCorrelationWrapper(ICorrelationAccessor correlationAccessor, IHttpRequestWrapper next, ILogger<HttpCorrelationWrapper> logger)
{
_correlationAccessor = correlationAccessor;
_next = next;
_logger = logger;
}
public async Task<JsonContent> WrapAsync<TRequest>(TRequest request, CancellationToken cancellationToken)
where TRequest : IRequest
{
var response = await _next.WrapAsync(request, cancellationToken).ConfigureAwait(false);
_logger.LogDebug("Set {header} header to {correlationId}", CorrelationDefaults.CorrelationId, _correlationAccessor.CorrelationId);
response.Headers.SetCorrelationId(_correlationAccessor.CorrelationId);
_logger.LogDebug("Set {header} header to {causationId}", CorrelationDefaults.CausationId, _correlationAccessor.MessageId);
response.Headers.SetCausationId(_correlationAccessor.MessageId);
return response;
}
}
}
| 40.35 | 145 | 0.740397 | [
"MIT"
] | Netension/request | src/Netension.Request.Http/Wrappers/HttpCorrelationWrapper.cs | 1,616 | C# |
public class MultiplyFloat : IAccumulator<float>
{
public float Accumulate(float left, float right)
{
return left * right;
}
}
public class MultiplyInt : IAccumulator<int>
{
public int Accumulate(int left, int right)
{
return left * right;
}
}
| 17.8125 | 52 | 0.638596 | [
"Apache-2.0"
] | PKxD/RPGStatSystem | Assets/Scripts/Accumulators/Multiply.cs | 285 | C# |
namespace Adrichem.Serialization.Ameff.V31.Element
{
[System.Serializable()]
[System.Xml.Serialization.XmlType(Namespace = "http://www.opengroup.org/xsd/archimate/3.0/")]
public partial class ApplicationInteraction : RealElementType
{
}
}
| 28.888889 | 97 | 0.726923 | [
"MIT"
] | adrichem/AmeffSerializer | AmeffSerializer/V31/Element/ApplicationInteraction.cs | 262 | C# |
#nullable enable
using System;
using System.Collections.Generic;
using System.Text;
namespace GtirbSharp
{
// If this becomes mutable, add a change hook to SerializedDictionaryOffsetDirectives
public sealed class Directive
{
public string DirectiveString { get; private set; }
public IEnumerable<long> DirectiveValues { get; private set; }
public Guid DirectiveUuid { get; private set; }
public Directive(string directiveString, IEnumerable<long> directiveValues,
Guid directiveUuid)
{
this.DirectiveString = directiveString;
this.DirectiveValues = directiveValues;
this.DirectiveUuid = directiveUuid;
}
}
}
#nullable restore | 32.166667 | 90 | 0.656736 | [
"MIT"
] | SapientGuardian/GtirbSharp | GtirbSharp/Directive.cs | 774 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Text.Json
{
/// <summary>
/// Represents a specific JSON value within a <see cref="JsonDocument"/>.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public readonly partial struct JsonElement
{
private readonly JsonDocument _parent;
private readonly int _idx;
internal JsonElement(JsonDocument parent, int idx)
{
// parent is usually not null, but the Current property
// on the enumerators (when initialized as `default`) can
// get here with a null.
Debug.Assert(idx >= 0);
_parent = parent;
_idx = idx;
}
// Currently used only as an optimization by the serializer, which does not want to
// return elements that are based on the <see cref="JsonDocument.Dispose"/> pattern.
internal static JsonElement ParseValue(ref Utf8JsonReader reader)
{
bool ret = JsonDocument.TryParseValue(ref reader, out JsonDocument? document, shouldThrow: true, useArrayPools: false);
Debug.Assert(ret != false, "Parse returned false with shouldThrow: true.");
Debug.Assert(document != null, "null document returned with shouldThrow: true.");
return document.RootElement;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private JsonTokenType TokenType
{
get
{
return _parent?.GetJsonTokenType(_idx) ?? JsonTokenType.None;
}
}
/// <summary>
/// The <see cref="JsonValueKind"/> that the value is.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public JsonValueKind ValueKind => TokenType.ToValueKind();
/// <summary>
/// Get the value at a specified index when the current value is a
/// <see cref="JsonValueKind.Array"/>.
/// </summary>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Array"/>.
/// </exception>
/// <exception cref="IndexOutOfRangeException">
/// <paramref name="index"/> is not in the range [0, <see cref="GetArrayLength"/>()).
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public JsonElement this[int index]
{
get
{
CheckValidInstance();
return _parent.GetArrayIndexElement(_idx, index);
}
}
/// <summary>
/// Get the number of values contained within the current array value.
/// </summary>
/// <returns>The number of values contained within the current array value.</returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Array"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public int GetArrayLength()
{
CheckValidInstance();
return _parent.GetArrayLength(_idx);
}
/// <summary>
/// Gets a <see cref="JsonElement"/> representing the value of a required property identified
/// by <paramref name="propertyName"/>.
/// </summary>
/// <remarks>
/// Property name matching is performed as an ordinal, case-sensitive, comparison.
///
/// If a property is defined multiple times for the same object, the last such definition is
/// what is matched.
/// </remarks>
/// <param name="propertyName">Name of the property whose value to return.</param>
/// <returns>
/// A <see cref="JsonElement"/> representing the value of the requested property.
/// </returns>
/// <seealso cref="EnumerateObject"/>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Object"/>.
/// </exception>
/// <exception cref="KeyNotFoundException">
/// No property was found with the requested name.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="propertyName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public JsonElement GetProperty(string propertyName)
{
if (propertyName == null)
throw new ArgumentNullException(nameof(propertyName));
if (TryGetProperty(propertyName, out JsonElement property))
{
return property;
}
throw new KeyNotFoundException();
}
/// <summary>
/// Gets a <see cref="JsonElement"/> representing the value of a required property identified
/// by <paramref name="propertyName"/>.
/// </summary>
/// <remarks>
/// <para>
/// Property name matching is performed as an ordinal, case-sensitive, comparison.
/// </para>
///
/// <para>
/// If a property is defined multiple times for the same object, the last such definition is
/// what is matched.
/// </para>
/// </remarks>
/// <param name="propertyName">Name of the property whose value to return.</param>
/// <returns>
/// A <see cref="JsonElement"/> representing the value of the requested property.
/// </returns>
/// <seealso cref="EnumerateObject"/>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Object"/>.
/// </exception>
/// <exception cref="KeyNotFoundException">
/// No property was found with the requested name.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public JsonElement GetProperty(ReadOnlySpan<char> propertyName)
{
if (TryGetProperty(propertyName, out JsonElement property))
{
return property;
}
throw new KeyNotFoundException();
}
/// <summary>
/// Gets a <see cref="JsonElement"/> representing the value of a required property identified
/// by <paramref name="utf8PropertyName"/>.
/// </summary>
/// <remarks>
/// <para>
/// Property name matching is performed as an ordinal, case-sensitive, comparison.
/// </para>
///
/// <para>
/// If a property is defined multiple times for the same object, the last such definition is
/// what is matched.
/// </para>
/// </remarks>
/// <param name="utf8PropertyName">
/// The UTF-8 (with no Byte-Order-Mark (BOM)) representation of the name of the property to return.
/// </param>
/// <returns>
/// A <see cref="JsonElement"/> representing the value of the requested property.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Object"/>.
/// </exception>
/// <exception cref="KeyNotFoundException">
/// No property was found with the requested name.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
/// <seealso cref="EnumerateObject"/>
public JsonElement GetProperty(ReadOnlySpan<byte> utf8PropertyName)
{
if (TryGetProperty(utf8PropertyName, out JsonElement property))
{
return property;
}
throw new KeyNotFoundException();
}
/// <summary>
/// Looks for a property named <paramref name="propertyName"/> in the current object, returning
/// whether or not such a property existed. When the property exists <paramref name="value"/>
/// is assigned to the value of that property.
/// </summary>
/// <remarks>
/// <para>
/// Property name matching is performed as an ordinal, case-sensitive, comparison.
/// </para>
///
/// <para>
/// If a property is defined multiple times for the same object, the last such definition is
/// what is matched.
/// </para>
/// </remarks>
/// <param name="propertyName">Name of the property to find.</param>
/// <param name="value">Receives the value of the located property.</param>
/// <returns>
/// <see langword="true"/> if the property was found, <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Object"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="propertyName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
/// <seealso cref="EnumerateObject"/>
public bool TryGetProperty(string propertyName, out JsonElement value)
{
if (propertyName == null)
throw new ArgumentNullException(nameof(propertyName));
return TryGetProperty(propertyName.AsSpan(), out value);
}
/// <summary>
/// Looks for a property named <paramref name="propertyName"/> in the current object, returning
/// whether or not such a property existed. When the property exists <paramref name="value"/>
/// is assigned to the value of that property.
/// </summary>
/// <remarks>
/// <para>
/// Property name matching is performed as an ordinal, case-sensitive, comparison.
/// </para>
///
/// <para>
/// If a property is defined multiple times for the same object, the last such definition is
/// what is matched.
/// </para>
/// </remarks>
/// <param name="propertyName">Name of the property to find.</param>
/// <param name="value">Receives the value of the located property.</param>
/// <returns>
/// <see langword="true"/> if the property was found, <see langword="false"/> otherwise.
/// </returns>
/// <seealso cref="EnumerateObject"/>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Object"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool TryGetProperty(ReadOnlySpan<char> propertyName, out JsonElement value)
{
CheckValidInstance();
return _parent.TryGetNamedPropertyValue(_idx, propertyName, out value);
}
/// <summary>
/// Looks for a property named <paramref name="utf8PropertyName"/> in the current object, returning
/// whether or not such a property existed. When the property exists <paramref name="value"/>
/// is assigned to the value of that property.
/// </summary>
/// <remarks>
/// <para>
/// Property name matching is performed as an ordinal, case-sensitive, comparison.
/// </para>
///
/// <para>
/// If a property is defined multiple times for the same object, the last such definition is
/// what is matched.
/// </para>
/// </remarks>
/// <param name="utf8PropertyName">
/// The UTF-8 (with no Byte-Order-Mark (BOM)) representation of the name of the property to return.
/// </param>
/// <param name="value">Receives the value of the located property.</param>
/// <returns>
/// <see langword="true"/> if the property was found, <see langword="false"/> otherwise.
/// </returns>
/// <seealso cref="EnumerateObject"/>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Object"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool TryGetProperty(ReadOnlySpan<byte> utf8PropertyName, out JsonElement value)
{
CheckValidInstance();
return _parent.TryGetNamedPropertyValue(_idx, utf8PropertyName, out value);
}
/// <summary>
/// Gets the value of the element as a <see cref="bool"/>.
/// </summary>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <returns>The value of the element as a <see cref="bool"/>.</returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is neither <see cref="JsonValueKind.True"/> or
/// <see cref="JsonValueKind.False"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool GetBoolean()
{
// CheckValidInstance is redundant. Asking for the type will
// return None, which then throws the same exception in the return statement.
JsonTokenType type = TokenType;
return
type == JsonTokenType.True ? true :
type == JsonTokenType.False ? false :
throw ThrowHelper.GetJsonElementWrongTypeException(nameof(Boolean), type);
}
/// <summary>
/// Gets the value of the element as a <see cref="string"/>.
/// </summary>
/// <remarks>
/// This method does not create a string representation of values other than JSON strings.
/// </remarks>
/// <returns>The value of the element as a <see cref="string"/>.</returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is neither <see cref="JsonValueKind.String"/> nor <see cref="JsonValueKind.Null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
/// <seealso cref="ToString"/>
public string? GetString()
{
CheckValidInstance();
return _parent.GetString(_idx, JsonTokenType.String);
}
/// <summary>
/// Attempts to represent the current JSON string as bytes assuming it is Base64 encoded.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not create a byte[] representation of values other than base 64 encoded JSON strings.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the entire token value is encoded as valid Base64 text and can be successfully decoded to bytes.
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.String"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool TryGetBytesFromBase64([NotNullWhen(true)] out byte[]? value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the value of the element as bytes.
/// </summary>
/// <remarks>
/// This method does not create a byte[] representation of values other than Base64 encoded JSON strings.
/// </remarks>
/// <returns>The value decode to bytes.</returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.String"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value is not encoded as Base64 text and hence cannot be decoded to bytes.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
/// <seealso cref="ToString"/>
public byte[] GetBytesFromBase64()
{
if (TryGetBytesFromBase64(out byte[]? value))
{
return value;
}
throw ThrowHelper.GetFormatException();
}
/// <summary>
/// Attempts to represent the current JSON number as an <see cref="sbyte"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the number can be represented as an <see cref="sbyte"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
[CLSCompliant(false)]
public bool TryGetSByte(out sbyte value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the current JSON number as an <see cref="sbyte"/>.
/// </summary>
/// <returns>The current JSON number as an <see cref="sbyte"/>.</returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as an <see cref="sbyte"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
[CLSCompliant(false)]
public sbyte GetSByte()
{
if (TryGetSByte(out sbyte value))
{
return value;
}
throw new FormatException();
}
/// <summary>
/// Attempts to represent the current JSON number as a <see cref="byte"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the number can be represented as a <see cref="byte"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool TryGetByte(out byte value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the current JSON number as a <see cref="byte"/>.
/// </summary>
/// <returns>The current JSON number as a <see cref="byte"/>.</returns>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as a <see cref="byte"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public byte GetByte()
{
if (TryGetByte(out byte value))
{
return value;
}
throw new FormatException();
}
/// <summary>
/// Attempts to represent the current JSON number as an <see cref="short"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the number can be represented as an <see cref="short"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool TryGetInt16(out short value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the current JSON number as an <see cref="short"/>.
/// </summary>
/// <returns>The current JSON number as an <see cref="short"/>.</returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as an <see cref="short"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public short GetInt16()
{
if (TryGetInt16(out short value))
{
return value;
}
throw new FormatException();
}
/// <summary>
/// Attempts to represent the current JSON number as a <see cref="ushort"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the number can be represented as a <see cref="ushort"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
[CLSCompliant(false)]
public bool TryGetUInt16(out ushort value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the current JSON number as a <see cref="ushort"/>.
/// </summary>
/// <returns>The current JSON number as a <see cref="ushort"/>.</returns>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as a <see cref="ushort"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
[CLSCompliant(false)]
public ushort GetUInt16()
{
if (TryGetUInt16(out ushort value))
{
return value;
}
throw new FormatException();
}
/// <summary>
/// Attempts to represent the current JSON number as an <see cref="int"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the number can be represented as an <see cref="int"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool TryGetInt32(out int value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the current JSON number as an <see cref="int"/>.
/// </summary>
/// <returns>The current JSON number as an <see cref="int"/>.</returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as an <see cref="int"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public int GetInt32()
{
if (TryGetInt32(out int value))
{
return value;
}
throw ThrowHelper.GetFormatException();
}
/// <summary>
/// Attempts to represent the current JSON number as a <see cref="uint"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the number can be represented as a <see cref="uint"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
[CLSCompliant(false)]
public bool TryGetUInt32(out uint value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the current JSON number as a <see cref="uint"/>.
/// </summary>
/// <returns>The current JSON number as a <see cref="uint"/>.</returns>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as a <see cref="uint"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
[CLSCompliant(false)]
public uint GetUInt32()
{
if (TryGetUInt32(out uint value))
{
return value;
}
throw ThrowHelper.GetFormatException();
}
/// <summary>
/// Attempts to represent the current JSON number as a <see cref="long"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the number can be represented as a <see cref="long"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool TryGetInt64(out long value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the current JSON number as a <see cref="long"/>.
/// </summary>
/// <returns>The current JSON number as a <see cref="long"/>.</returns>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as a <see cref="long"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public long GetInt64()
{
if (TryGetInt64(out long value))
{
return value;
}
throw ThrowHelper.GetFormatException();
}
/// <summary>
/// Attempts to represent the current JSON number as a <see cref="ulong"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the number can be represented as a <see cref="ulong"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
[CLSCompliant(false)]
public bool TryGetUInt64(out ulong value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the current JSON number as a <see cref="ulong"/>.
/// </summary>
/// <returns>The current JSON number as a <see cref="ulong"/>.</returns>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as a <see cref="ulong"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
[CLSCompliant(false)]
public ulong GetUInt64()
{
if (TryGetUInt64(out ulong value))
{
return value;
}
throw ThrowHelper.GetFormatException();
}
/// <summary>
/// Attempts to represent the current JSON number as a <see cref="double"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// <para>
/// This method does not parse the contents of a JSON string value.
/// </para>
///
/// <para>
/// On .NET Core this method does not return <see langword="false"/> for values larger than
/// <see cref="double.MaxValue"/> (or smaller than <see cref="double.MinValue"/>),
/// instead <see langword="true"/> is returned and <see cref="double.PositiveInfinity"/> (or
/// <see cref="double.NegativeInfinity"/>) is emitted.
/// </para>
/// </remarks>
/// <returns>
/// <see langword="true"/> if the number can be represented as a <see cref="double"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool TryGetDouble(out double value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the current JSON number as a <see cref="double"/>.
/// </summary>
/// <returns>The current JSON number as a <see cref="double"/>.</returns>
/// <remarks>
/// <para>
/// This method does not parse the contents of a JSON string value.
/// </para>
///
/// <para>
/// On .NET Core this method returns <see cref="double.PositiveInfinity"/> (or
/// <see cref="double.NegativeInfinity"/>) for values larger than
/// <see cref="double.MaxValue"/> (or smaller than <see cref="double.MinValue"/>).
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as a <see cref="double"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public double GetDouble()
{
if (TryGetDouble(out double value))
{
return value;
}
throw ThrowHelper.GetFormatException();
}
/// <summary>
/// Attempts to represent the current JSON number as a <see cref="float"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// <para>
/// This method does not parse the contents of a JSON string value.
/// </para>
///
/// <para>
/// On .NET Core this method does not return <see langword="false"/> for values larger than
/// <see cref="float.MaxValue"/> (or smaller than <see cref="float.MinValue"/>),
/// instead <see langword="true"/> is returned and <see cref="float.PositiveInfinity"/> (or
/// <see cref="float.NegativeInfinity"/>) is emitted.
/// </para>
/// </remarks>
/// <returns>
/// <see langword="true"/> if the number can be represented as a <see cref="float"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool TryGetSingle(out float value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the current JSON number as a <see cref="float"/>.
/// </summary>
/// <returns>The current JSON number as a <see cref="float"/>.</returns>
/// <remarks>
/// <para>
/// This method does not parse the contents of a JSON string value.
/// </para>
///
/// <para>
/// On .NET Core this method returns <see cref="float.PositiveInfinity"/> (or
/// <see cref="float.NegativeInfinity"/>) for values larger than
/// <see cref="float.MaxValue"/> (or smaller than <see cref="float.MinValue"/>).
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as a <see cref="float"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public float GetSingle()
{
if (TryGetSingle(out float value))
{
return value;
}
throw ThrowHelper.GetFormatException();
}
/// <summary>
/// Attempts to represent the current JSON number as a <see cref="decimal"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the number can be represented as a <see cref="decimal"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
/// <seealso cref="GetRawText"/>
public bool TryGetDecimal(out decimal value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the current JSON number as a <see cref="decimal"/>.
/// </summary>
/// <returns>The current JSON number as a <see cref="decimal"/>.</returns>
/// <remarks>
/// This method does not parse the contents of a JSON string value.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Number"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as a <see cref="decimal"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
/// <seealso cref="GetRawText"/>
public decimal GetDecimal()
{
if (TryGetDecimal(out decimal value))
{
return value;
}
throw ThrowHelper.GetFormatException();
}
/// <summary>
/// Attempts to represent the current JSON string as a <see cref="DateTime"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not create a DateTime representation of values other than JSON strings.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the string can be represented as a <see cref="DateTime"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.String"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool TryGetDateTime(out DateTime value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the value of the element as a <see cref="DateTime"/>.
/// </summary>
/// <remarks>
/// This method does not create a DateTime representation of values other than JSON strings.
/// </remarks>
/// <returns>The value of the element as a <see cref="DateTime"/>.</returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.String"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as a <see cref="DateTime"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
/// <seealso cref="ToString"/>
public DateTime GetDateTime()
{
if (TryGetDateTime(out DateTime value))
{
return value;
}
throw ThrowHelper.GetFormatException();
}
/// <summary>
/// Attempts to represent the current JSON string as a <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not create a DateTimeOffset representation of values other than JSON strings.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the string can be represented as a <see cref="DateTimeOffset"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.String"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool TryGetDateTimeOffset(out DateTimeOffset value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the value of the element as a <see cref="DateTimeOffset"/>.
/// </summary>
/// <remarks>
/// This method does not create a DateTimeOffset representation of values other than JSON strings.
/// </remarks>
/// <returns>The value of the element as a <see cref="DateTimeOffset"/>.</returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.String"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as a <see cref="DateTimeOffset"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
/// <seealso cref="ToString"/>
public DateTimeOffset GetDateTimeOffset()
{
if (TryGetDateTimeOffset(out DateTimeOffset value))
{
return value;
}
throw ThrowHelper.GetFormatException();
}
/// <summary>
/// Attempts to represent the current JSON string as a <see cref="Guid"/>.
/// </summary>
/// <param name="value">Receives the value.</param>
/// <remarks>
/// This method does not create a Guid representation of values other than JSON strings.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the string can be represented as a <see cref="Guid"/>,
/// <see langword="false"/> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.String"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public bool TryGetGuid(out Guid value)
{
CheckValidInstance();
return _parent.TryGetValue(_idx, out value);
}
/// <summary>
/// Gets the value of the element as a <see cref="Guid"/>.
/// </summary>
/// <remarks>
/// This method does not create a Guid representation of values other than JSON strings.
/// </remarks>
/// <returns>The value of the element as a <see cref="Guid"/>.</returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.String"/>.
/// </exception>
/// <exception cref="FormatException">
/// The value cannot be represented as a <see cref="Guid"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
/// <seealso cref="ToString"/>
public Guid GetGuid()
{
if (TryGetGuid(out Guid value))
{
return value;
}
throw ThrowHelper.GetFormatException();
}
internal string GetPropertyName()
{
CheckValidInstance();
return _parent.GetNameOfPropertyValue(_idx);
}
/// <summary>
/// Gets the original input data backing this value, returning it as a <see cref="string"/>.
/// </summary>
/// <returns>
/// The original input data backing this value, returning it as a <see cref="string"/>.
/// </returns>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public string GetRawText()
{
CheckValidInstance();
return _parent.GetRawValueAsString(_idx);
}
internal string GetPropertyRawText()
{
CheckValidInstance();
return _parent.GetPropertyRawValueAsString(_idx);
}
/// <summary>
/// Compares <paramref name="text" /> to the string value of this element.
/// </summary>
/// <param name="text">The text to compare against.</param>
/// <returns>
/// <see langword="true" /> if the string value of this element matches <paramref name="text"/>,
/// <see langword="false" /> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.String"/>.
/// </exception>
/// <remarks>
/// This method is functionally equal to doing an ordinal comparison of <paramref name="text" /> and
/// the result of calling <see cref="GetString" />, but avoids creating the string instance.
/// </remarks>
public bool ValueEquals(string? text)
{
// CheckValidInstance is done in the helper
if (TokenType == JsonTokenType.Null)
{
return text == null;
}
return TextEqualsHelper(text.AsSpan(), isPropertyName: false);
}
/// <summary>
/// Compares the text represented by <paramref name="utf8Text" /> to the string value of this element.
/// </summary>
/// <param name="utf8Text">The UTF-8 encoded text to compare against.</param>
/// <returns>
/// <see langword="true" /> if the string value of this element has the same UTF-8 encoding as
/// <paramref name="utf8Text" />, <see langword="false" /> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.String"/>.
/// </exception>
/// <remarks>
/// This method is functionally equal to doing an ordinal comparison of the string produced by UTF-8 decoding
/// <paramref name="utf8Text" /> with the result of calling <see cref="GetString" />, but avoids creating the
/// string instances.
/// </remarks>
public bool ValueEquals(ReadOnlySpan<byte> utf8Text)
{
// CheckValidInstance is done in the helper
if (TokenType == JsonTokenType.Null)
{
// This is different than Length == 0, in that it tests true for null, but false for ""
return utf8Text == default;
}
return TextEqualsHelper(utf8Text, isPropertyName: false, shouldUnescape: true);
}
/// <summary>
/// Compares <paramref name="text" /> to the string value of this element.
/// </summary>
/// <param name="text">The text to compare against.</param>
/// <returns>
/// <see langword="true" /> if the string value of this element matches <paramref name="text"/>,
/// <see langword="false" /> otherwise.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.String"/>.
/// </exception>
/// <remarks>
/// This method is functionally equal to doing an ordinal comparison of <paramref name="text" /> and
/// the result of calling <see cref="GetString" />, but avoids creating the string instance.
/// </remarks>
public bool ValueEquals(ReadOnlySpan<char> text)
{
// CheckValidInstance is done in the helper
if (TokenType == JsonTokenType.Null)
{
// This is different than Length == 0, in that it tests true for null, but false for ""
return text == default;
}
return TextEqualsHelper(text, isPropertyName: false);
}
internal bool TextEqualsHelper(ReadOnlySpan<byte> utf8Text, bool isPropertyName, bool shouldUnescape)
{
CheckValidInstance();
return _parent.TextEquals(_idx, utf8Text, isPropertyName, shouldUnescape);
}
internal bool TextEqualsHelper(ReadOnlySpan<char> text, bool isPropertyName)
{
CheckValidInstance();
return _parent.TextEquals(_idx, text, isPropertyName);
}
/// <summary>
/// Write the element into the provided writer as a JSON value.
/// </summary>
/// <param name="writer">The writer.</param>
/// <exception cref="ArgumentNullException">
/// The <paramref name="writer"/> parameter is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is <see cref="JsonValueKind.Undefined"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public void WriteTo(Utf8JsonWriter writer)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
CheckValidInstance();
_parent.WriteElementTo(_idx, writer);
}
/// <summary>
/// Get an enumerator to enumerate the values in the JSON array represented by this JsonElement.
/// </summary>
/// <returns>
/// An enumerator to enumerate the values in the JSON array represented by this JsonElement.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Array"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public ArrayEnumerator EnumerateArray()
{
CheckValidInstance();
JsonTokenType tokenType = TokenType;
if (tokenType != JsonTokenType.StartArray)
{
throw ThrowHelper.GetJsonElementWrongTypeException(JsonTokenType.StartArray, tokenType);
}
return new ArrayEnumerator(this);
}
/// <summary>
/// Get an enumerator to enumerate the properties in the JSON object represented by this JsonElement.
/// </summary>
/// <returns>
/// An enumerator to enumerate the properties in the JSON object represented by this JsonElement.
/// </returns>
/// <exception cref="InvalidOperationException">
/// This value's <see cref="ValueKind"/> is not <see cref="JsonValueKind.Object"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public ObjectEnumerator EnumerateObject()
{
CheckValidInstance();
JsonTokenType tokenType = TokenType;
if (tokenType != JsonTokenType.StartObject)
{
throw ThrowHelper.GetJsonElementWrongTypeException(JsonTokenType.StartObject, tokenType);
}
return new ObjectEnumerator(this);
}
/// <summary>
/// Gets a string representation for the current value appropriate to the value type.
/// </summary>
/// <remarks>
/// <para>
/// For JsonElement built from <see cref="JsonDocument"/>:
/// </para>
///
/// <para>
/// For <see cref="JsonValueKind.Null"/>, <see cref="string.Empty"/> is returned.
/// </para>
///
/// <para>
/// For <see cref="JsonValueKind.True"/>, <see cref="bool.TrueString"/> is returned.
/// </para>
///
/// <para>
/// For <see cref="JsonValueKind.False"/>, <see cref="bool.FalseString"/> is returned.
/// </para>
///
/// <para>
/// For <see cref="JsonValueKind.String"/>, the value of <see cref="GetString"/>() is returned.
/// </para>
///
/// <para>
/// For other types, the value of <see cref="GetRawText"/>() is returned.
/// </para>
/// </remarks>
/// <returns>
/// A string representation for the current value appropriate to the value type.
/// </returns>
/// <exception cref="ObjectDisposedException">
/// The parent <see cref="JsonDocument"/> has been disposed.
/// </exception>
public override string? ToString()
{
switch (TokenType)
{
case JsonTokenType.None:
case JsonTokenType.Null:
return string.Empty;
case JsonTokenType.True:
return bool.TrueString;
case JsonTokenType.False:
return bool.FalseString;
case JsonTokenType.Number:
case JsonTokenType.StartArray:
case JsonTokenType.StartObject:
{
// null parent should have hit the None case
Debug.Assert(_parent != null);
return ((JsonDocument)_parent).GetRawValueAsString(_idx);
}
case JsonTokenType.String:
return GetString();
case JsonTokenType.Comment:
case JsonTokenType.EndArray:
case JsonTokenType.EndObject:
default:
Debug.Fail($"No handler for {nameof(JsonTokenType)}.{TokenType}");
return string.Empty;
}
}
/// <summary>
/// Get a JsonElement which can be safely stored beyond the lifetime of the
/// original <see cref="JsonDocument"/>.
/// </summary>
/// <returns>
/// A JsonElement which can be safely stored beyond the lifetime of the
/// original <see cref="JsonDocument"/>.
/// </returns>
/// <remarks>
/// <para>
/// If this JsonElement is itself the output of a previous call to Clone, or
/// a value contained within another JsonElement which was the output of a previous
/// call to Clone, this method results in no additional memory allocation.
/// </para>
/// </remarks>
public JsonElement Clone()
{
CheckValidInstance();
if (!_parent.IsDisposable)
{
return this;
}
return _parent.CloneElement(_idx);
}
private void CheckValidInstance()
{
if (_parent == null)
{
throw new InvalidOperationException();
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string DebuggerDisplay => $"ValueKind = {ValueKind} : \"{ToString()}\"";
}
}
| 40.850136 | 136 | 0.550827 | [
"MIT"
] | ahsonkhan/runtime | src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs | 59,968 | C# |
namespace Synergy.Recruitment.Data.Models
{
public class CandidateJobAdvertisment
{
public long Id { get; set; }
public long CandidateId { get; set; }
public long JobAdvertismentId { get; set; }
public virtual Candidate Candidate { get; set; }
public virtual JobAdvertisement JobAdvertisment { get; set; }
}
}
| 22.9375 | 69 | 0.645777 | [
"MIT"
] | StanislavChankov/Recruitment | src/Synergy.Recruitment.Data.Models/CandidateJobAdvertisement.cs | 369 | C# |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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 NakedObjects.Facade.Interface;
namespace NakedObjects.Facade.Impl {
// for testing only
public class NullStringHasher : IStringHasher {
#region IStringHasher Members
public string GetHash(string toHash) {
return null;
}
#endregion
}
} | 43.857143 | 136 | 0.730727 | [
"Apache-2.0"
] | Giovanni-Russo-Boscoli/NakedObjectsFramework | Rest/NakedObjects.Rest.Test.Data/NullStringHasher.cs | 923 | C# |
using System.Collections.Specialized;
namespace Merchello.Core.Models
{
using System;
using System.Reflection;
using System.Runtime.Serialization;
using Merchello.Core.Models.EntityBase;
using Merchello.Core.Models.Interfaces;
///// TODO SR - This is just a scaffold for example. Do whatever you need to do =)
/// <summary>
/// The digital media.
/// </summary>
[Serializable]
[DataContract(IsReference = true)]
internal class DigitalMedia : Entity, IDigitalMedia
{
#region Fields
/// <summary>
/// The name selector.
/// </summary>
/// <remarks>
/// </remarks>
private static readonly PropertyInfo FirstAccessedSelector = ExpressionHelper.GetPropertyInfo<DigitalMedia, DateTime?>(x => x.FirstAccessed);
private static readonly PropertyInfo ProductVariantSelector = ExpressionHelper.GetPropertyInfo<DigitalMedia, Guid>(x => x.ProductVariantKey);
private static readonly PropertyInfo ExtendedDataChangedSelector = ExpressionHelper.GetPropertyInfo<LineItemBase, ExtendedDataCollection>(x => x.ExtendedData);
private void ExtendedDataChanged(object sender, NotifyCollectionChangedEventArgs e)
{
OnPropertyChanged(ExtendedDataChangedSelector);
}
/// <summary>
/// This is immutable
/// </summary>
private DateTime? _firstAccessed;
private Guid _productVariantKey;
private ExtendedDataCollection _extendedData;
#endregion
[DataMember]
public Guid ProductVariantKey
{
get
{
return _productVariantKey;
}
set
{
SetPropertyValueAndDetectChanges(
o =>
{
_productVariantKey = value;
return _productVariantKey;
},
_productVariantKey,
ProductVariantSelector);
}
}
[DataMember]
public DateTime? FirstAccessed
{
get
{
return _firstAccessed;
}
set
{
SetPropertyValueAndDetectChanges(
o =>
{
_firstAccessed = value;
return _firstAccessed;
},
_firstAccessed,
FirstAccessedSelector);
}
}
/// <summary>
/// A collection for storing custom/extended line item data
/// </summary>
[DataMember]
public ExtendedDataCollection ExtendedData
{
get { return _extendedData; }
internal set
{
_extendedData = value;
_extendedData.CollectionChanged += ExtendedDataChanged;
}
}
}
} | 27.851852 | 167 | 0.538564 | [
"MIT"
] | ryanology/Merchello | src/Merchello.Core/Models/DigitalMedia.cs | 3,010 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using LibrarySystem.Web.Models;
namespace LibrarySystem.Web.Controllers
{
[Authorize]
public class ManageController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public ManageController()
{
}
public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Manage/Index
public async Task<ActionResult> Index(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var userId = User.Identity.GetUserId();
var model = new IndexViewModel
{
HasPassword = HasPassword(),
PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
Logins = await UserManager.GetLoginsAsync(userId),
BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey)
{
ManageMessageId? message;
var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return RedirectToAction("ManageLogins", new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public ActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number);
if (UserManager.SmsService != null)
{
var message = new IdentityMessage
{
Destination = model.Number,
Body = "Your security code is: " + code
};
await UserManager.SmsService.SendAsync(message);
}
return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EnableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DisableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber);
// Send an SMS through the SMS provider to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess });
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "Failed to verify phone");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RemovePhoneNumber()
{
var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null);
if (!result.Succeeded)
{
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess });
}
//
// GET: /Manage/ChangePassword
public ActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
//
// GET: /Manage/SetPassword
public ActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SetPassword(SetPasswordViewModel model)
{
if (ModelState.IsValid)
{
var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Manage/ManageLogins
public async Task<ActionResult> ManageLogins(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user == null)
{
return View("Error");
}
var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId());
var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList();
ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId());
}
//
// GET: /Manage/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback()
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null)
{
return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
protected override void Dispose(bool disposing)
{
if (disposing && _userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
private bool HasPhoneNumber()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PhoneNumber != null;
}
return false;
}
public enum ManageMessageId
{
AddPhoneSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
#endregion
}
} | 36.33419 | 175 | 0.567072 | [
"Unlicense"
] | danielpenchew/MVC-Test-Project | LibrarySystem/Web/LibrarySystem.Web/Controllers/ManageController.cs | 14,136 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#nullable enable
namespace Microsoft.EntityFrameworkCore.Metadata.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class InternalSkipNavigationBuilder : InternalPropertyBaseBuilder<SkipNavigation>, IConventionSkipNavigationBuilder
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public InternalSkipNavigationBuilder([NotNull] SkipNavigation metadata, [NotNull] InternalModelBuilder modelBuilder)
: base(metadata, modelBuilder)
{
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public new virtual InternalSkipNavigationBuilder? HasField([CanBeNull] string? fieldName, ConfigurationSource configurationSource)
=> (InternalSkipNavigationBuilder?)base.HasField(fieldName, configurationSource);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public new virtual InternalSkipNavigationBuilder? HasField([CanBeNull] FieldInfo? fieldInfo, ConfigurationSource configurationSource)
=> (InternalSkipNavigationBuilder?)base.HasField(fieldInfo, configurationSource);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public new virtual InternalSkipNavigationBuilder? UsePropertyAccessMode(
PropertyAccessMode? propertyAccessMode,
ConfigurationSource configurationSource)
=> (InternalSkipNavigationBuilder?)base.UsePropertyAccessMode(propertyAccessMode, configurationSource);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual InternalSkipNavigationBuilder? HasForeignKey(
[CanBeNull] ForeignKey? foreignKey,
ConfigurationSource configurationSource)
{
if (!CanSetForeignKey(foreignKey, configurationSource))
{
return null;
}
if (foreignKey != null)
{
foreignKey.UpdateConfigurationSource(configurationSource);
if (Metadata.Inverse?.JoinEntityType != null
&& Metadata.Inverse.JoinEntityType
!= (Metadata.IsOnDependent ? foreignKey.PrincipalEntityType : foreignKey.DeclaringEntityType))
{
Metadata.Inverse.Builder.HasForeignKey(null, configurationSource);
}
}
var oldForeignKey = Metadata.ForeignKey;
Metadata.SetForeignKey(foreignKey, configurationSource);
if (oldForeignKey?.IsInModel == true
&& oldForeignKey != foreignKey
&& oldForeignKey.ReferencingSkipNavigations?.Any() != true)
{
oldForeignKey.DeclaringEntityType.Builder.HasNoRelationship(oldForeignKey, ConfigurationSource.Convention);
}
return this;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual bool CanSetForeignKey([CanBeNull] ForeignKey? foreignKey, ConfigurationSource? configurationSource)
{
if (!configurationSource.Overrides(Metadata.GetForeignKeyConfigurationSource()))
{
return Equals(Metadata.ForeignKey, foreignKey);
}
if (foreignKey == null)
{
return true;
}
if (Metadata.DeclaringEntityType
!= (Metadata.IsOnDependent ? foreignKey.DeclaringEntityType : foreignKey.PrincipalEntityType))
{
return false;
}
if (Metadata.Inverse?.JoinEntityType == null)
{
return true;
}
return Metadata.Inverse.JoinEntityType
== (Metadata.IsOnDependent ? foreignKey.PrincipalEntityType : foreignKey.DeclaringEntityType)
|| Metadata.Inverse.Builder.CanSetForeignKey(null, configurationSource);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual InternalSkipNavigationBuilder? HasInverse(
[CanBeNull] SkipNavigation? inverse,
ConfigurationSource configurationSource)
{
if (!CanSetInverse(inverse, configurationSource))
{
return null;
}
if (inverse != null)
{
inverse.UpdateConfigurationSource(configurationSource);
}
using (var batch = Metadata.DeclaringEntityType.Model.DelayConventions())
{
if (Metadata.Inverse != null
&& Metadata.Inverse != inverse)
{
Metadata.Inverse.SetInverse(null, configurationSource);
}
Metadata.SetInverse(inverse, configurationSource);
if (inverse != null)
{
inverse.SetInverse(Metadata, configurationSource);
}
}
return this;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual bool CanSetInverse(
[CanBeNull] SkipNavigation? inverse,
ConfigurationSource? configurationSource)
{
if (!configurationSource.Overrides(Metadata.GetInverseConfigurationSource())
|| (inverse != null
&& !configurationSource.Overrides(inverse.GetInverseConfigurationSource())))
{
return Equals(Metadata.Inverse, inverse);
}
if (inverse == null)
{
return true;
}
return Metadata.TargetEntityType == inverse.DeclaringEntityType
&& Metadata.DeclaringEntityType == inverse.TargetEntityType
&& (Metadata.JoinEntityType == null
|| inverse.JoinEntityType == null
|| Metadata.JoinEntityType == inverse.JoinEntityType);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual InternalSkipNavigationBuilder? Attach(
[CanBeNull] InternalEntityTypeBuilder? entityTypeBuilder = null,
[CanBeNull] EntityType? targetEntityType = null,
[CanBeNull] InternalSkipNavigationBuilder? inverseBuilder = null)
{
if (entityTypeBuilder is null)
{
if (Metadata.DeclaringEntityType.IsInModel)
{
entityTypeBuilder = Metadata.DeclaringEntityType.Builder;
}
else if (Metadata.DeclaringEntityType.Model.FindEntityType(Metadata.DeclaringEntityType.Name) is EntityType entityType)
{
entityTypeBuilder = entityType.Builder;
}
else
{
return null;
}
}
targetEntityType ??= Metadata.TargetEntityType;
if (!targetEntityType.IsInModel)
{
targetEntityType = Metadata.DeclaringEntityType.Model.FindEntityType(targetEntityType.Name);
if (targetEntityType == null)
{
return null;
}
}
var newSkipNavigationBuilder = entityTypeBuilder.HasSkipNavigation(
Metadata.CreateMemberIdentity(),
targetEntityType,
Metadata.GetConfigurationSource(),
Metadata.IsCollection,
Metadata.IsOnDependent);
if (newSkipNavigationBuilder == null)
{
return null;
}
newSkipNavigationBuilder.MergeAnnotationsFrom(Metadata);
var foreignKeyConfigurationSource = Metadata.GetForeignKeyConfigurationSource();
if (foreignKeyConfigurationSource.HasValue)
{
var foreignKey = Metadata.ForeignKey!;
if (!foreignKey.IsInModel)
{
foreignKey = InternalForeignKeyBuilder.FindCurrentForeignKeyBuilder(
foreignKey.PrincipalEntityType,
foreignKey.DeclaringEntityType,
foreignKey.DependentToPrincipal?.CreateMemberIdentity(),
foreignKey.PrincipalToDependent?.CreateMemberIdentity(),
dependentProperties: foreignKey.Properties,
principalProperties: foreignKey.PrincipalKey.Properties)?.Metadata;
}
if (foreignKey != null)
{
newSkipNavigationBuilder.HasForeignKey(foreignKey, foreignKeyConfigurationSource.Value);
}
}
var inverseConfigurationSource = Metadata.GetInverseConfigurationSource();
if (inverseConfigurationSource.HasValue)
{
var inverse = Metadata.Inverse!;
if (!inverse.IsInModel)
{
inverse = inverse.DeclaringEntityType.FindSkipNavigation(inverse.Name);
}
if (inverseBuilder != null)
{
inverse = inverseBuilder.Attach(targetEntityType.Builder, entityTypeBuilder.Metadata)?.Metadata
?? inverse;
}
if (inverse != null)
{
newSkipNavigationBuilder.HasInverse(inverse, inverseConfigurationSource.Value);
}
}
var propertyAccessModeConfigurationSource = Metadata.GetPropertyAccessModeConfigurationSource();
if (propertyAccessModeConfigurationSource.HasValue)
{
newSkipNavigationBuilder.UsePropertyAccessMode(
((IReadOnlySkipNavigation)Metadata).GetPropertyAccessMode(), propertyAccessModeConfigurationSource.Value);
}
var oldFieldInfoConfigurationSource = Metadata.GetFieldInfoConfigurationSource();
if (oldFieldInfoConfigurationSource.HasValue
&& newSkipNavigationBuilder.CanSetField(Metadata.FieldInfo, oldFieldInfoConfigurationSource))
{
newSkipNavigationBuilder.HasField(Metadata.FieldInfo, oldFieldInfoConfigurationSource.Value);
}
return newSkipNavigationBuilder;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual bool CanSetAutoInclude(bool? autoInclude, ConfigurationSource configurationSource)
{
IConventionSkipNavigation conventionNavigation = Metadata;
return configurationSource.Overrides(conventionNavigation.GetIsEagerLoadedConfigurationSource())
|| conventionNavigation.IsEagerLoaded == autoInclude;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual InternalSkipNavigationBuilder? AutoInclude(bool? autoInclude, ConfigurationSource configurationSource)
{
if (CanSetAutoInclude(autoInclude, configurationSource))
{
if (configurationSource == ConfigurationSource.Explicit)
{
((IMutableSkipNavigation)Metadata).SetIsEagerLoaded(autoInclude);
}
else
{
((IConventionSkipNavigation)Metadata).SetIsEagerLoaded(
autoInclude, configurationSource == ConfigurationSource.DataAnnotation);
}
return this;
}
return null;
}
IConventionPropertyBase IConventionPropertyBaseBuilder.Metadata
{
[DebuggerStepThrough] get => Metadata;
}
IConventionSkipNavigation IConventionSkipNavigationBuilder.Metadata
{
[DebuggerStepThrough]
get => Metadata;
}
/// <inheritdoc />
[DebuggerStepThrough]
IConventionPropertyBaseBuilder? IConventionPropertyBaseBuilder.HasField(string? fieldName, bool fromDataAnnotation)
=> HasField(
fieldName,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
IConventionPropertyBaseBuilder? IConventionPropertyBaseBuilder.HasField(FieldInfo? fieldInfo, bool fromDataAnnotation)
=> HasField(
fieldInfo,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
IConventionSkipNavigationBuilder? IConventionSkipNavigationBuilder.HasField(string? fieldName, bool fromDataAnnotation)
=> HasField(
fieldName,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
IConventionSkipNavigationBuilder? IConventionSkipNavigationBuilder.HasField(FieldInfo? fieldInfo, bool fromDataAnnotation)
=> HasField(
fieldInfo,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
bool IConventionPropertyBaseBuilder.CanSetField(string? fieldName, bool fromDataAnnotation)
=> CanSetField(
fieldName,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
bool IConventionPropertyBaseBuilder.CanSetField(FieldInfo? fieldInfo, bool fromDataAnnotation)
=> CanSetField(
fieldInfo,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
IConventionPropertyBaseBuilder? IConventionPropertyBaseBuilder.UsePropertyAccessMode(
PropertyAccessMode? propertyAccessMode,
bool fromDataAnnotation)
=> UsePropertyAccessMode(
propertyAccessMode,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
IConventionSkipNavigationBuilder? IConventionSkipNavigationBuilder.UsePropertyAccessMode(
PropertyAccessMode? propertyAccessMode,
bool fromDataAnnotation)
=> UsePropertyAccessMode(
propertyAccessMode,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
bool IConventionPropertyBaseBuilder.CanSetPropertyAccessMode(
PropertyAccessMode? propertyAccessMode,
bool fromDataAnnotation)
=> CanSetPropertyAccessMode(
propertyAccessMode,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
IConventionSkipNavigationBuilder? IConventionSkipNavigationBuilder.HasForeignKey(
IConventionForeignKey? foreignKey,
bool fromDataAnnotation)
=> HasForeignKey(
(ForeignKey?)foreignKey,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
bool IConventionSkipNavigationBuilder.CanSetForeignKey(
IConventionForeignKey? foreignKey,
bool fromDataAnnotation)
=> CanSetForeignKey(
(ForeignKey?)foreignKey,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
IConventionSkipNavigationBuilder? IConventionSkipNavigationBuilder.HasInverse(
IConventionSkipNavigation? inverse,
bool fromDataAnnotation)
=> HasInverse(
(SkipNavigation?)inverse,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
bool IConventionSkipNavigationBuilder.CanSetInverse(
IConventionSkipNavigation? inverse,
bool fromDataAnnotation)
=> CanSetInverse(
(SkipNavigation?)inverse,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
bool IConventionSkipNavigationBuilder.CanSetAutoInclude(bool? autoInclude, bool fromDataAnnotation)
=> CanSetAutoInclude(autoInclude, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
IConventionSkipNavigationBuilder? IConventionSkipNavigationBuilder.AutoInclude(bool? autoInclude, bool fromDataAnnotation)
=> AutoInclude(autoInclude, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
}
}
| 47.557173 | 141 | 0.635454 | [
"Apache-2.0"
] | Emill/efcore | src/EFCore/Metadata/Internal/InternalSkipNavigationBuilder.cs | 22,875 | C# |
using System;
using MikhailKhalizev.Processor.x86.BinToCSharp;
namespace MikhailKhalizev.Max.Program
{
public partial class RawProgram
{
[MethodInfo("0x1007_6844-812796ce")]
public void my_ctor_0x101b_38d0()
{
ii(0x1007_6844, 5); push(0x28); /* push 0x28 */
ii(0x1007_6849, 5); call(Definitions.sys_check_available_stack_size, 0xe_f504);/* call 0x10165d52 */
ii(0x1007_684e, 1); push(ebx); /* push ebx */
ii(0x1007_684f, 1); push(ecx); /* push ecx */
ii(0x1007_6850, 1); push(edx); /* push edx */
ii(0x1007_6851, 1); push(esi); /* push esi */
ii(0x1007_6852, 1); push(edi); /* push edi */
ii(0x1007_6853, 1); push(ebp); /* push ebp */
ii(0x1007_6854, 2); mov(ebp, esp); /* mov ebp, esp */
ii(0x1007_6856, 6); sub(esp, 0xc); /* sub esp, 0xc */
ii(0x1007_685c, 3); mov(memd[ss, ebp - 4], eax); /* mov [ebp-0x4], eax */
ii(0x1007_685f, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1007_6862, 5); call(Definitions.my_ctor_0x101b_6edc, 0x5dd);/* call 0x10076e44 */
ii(0x1007_6867, 3); mov(memd[ss, ebp - 4], eax); /* mov [ebp-0x4], eax */
ii(0x1007_686a, 3); lea(eax, memd[ss, ebp - 4]); /* lea eax, [ebp-0x4] */
ii(0x1007_686d, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */
ii(0x1007_6870, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */
ii(0x1007_6873, 3); mov(memd[ss, ebp - 12], eax); /* mov [ebp-0xc], eax */
ii(0x1007_6876, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */
ii(0x1007_6879, 2); mov(esp, ebp); /* mov esp, ebp */
ii(0x1007_687b, 1); pop(ebp); /* pop ebp */
ii(0x1007_687c, 1); pop(edi); /* pop edi */
ii(0x1007_687d, 1); pop(esi); /* pop esi */
ii(0x1007_687e, 1); pop(edx); /* pop edx */
ii(0x1007_687f, 1); pop(ecx); /* pop ecx */
ii(0x1007_6880, 1); pop(ebx); /* pop ebx */
ii(0x1007_6881, 1); ret(); /* ret */
}
}
}
| 67 | 114 | 0.411358 | [
"Apache-2.0"
] | mikhail-khalizev/max | source/MikhailKhalizev.Max/source/Program/Auto/z-1007-6844-my_ctor_0x101b_38d0.cs | 2,747 | C# |
// -----------------------------------------------------------------------
// <copyright file="AsyncLock.cs" company="OSharp开源团队">
// Copyright (c) 2014-2016 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2016-03-31 20:48</last-date>
// -----------------------------------------------------------------------
using System;
using System.Threading;
using System.Threading.Tasks;
namespace OSharp.Threading.Asyncs
{
/// <summary>
/// 异步锁
/// </summary>
public class AsyncLock
{
private readonly Task<Releaser> _releaser;
private readonly AsyncSemaphore _semaphore;
/// <summary>
/// 初始化一个<see cref="AsyncLock"/>类型的新实例
/// </summary>
public AsyncLock()
{
_semaphore = new AsyncSemaphore(1);
_releaser = Task.FromResult(new Releaser(this));
}
/// <summary>
/// 异步锁定
/// </summary>
public Task<Releaser> LockAsync()
{
var wait = _semaphore.WaitAsync();
return wait.IsCompleted
? _releaser
: wait.ContinueWith((_, state) => new Releaser((AsyncLock)state),
this,
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
/// <summary>
/// 释放资源的包装
/// </summary>
public struct Releaser : IDisposable
{
private readonly AsyncLock _toRelease;
internal Releaser(AsyncLock toRelease)
{
_toRelease = toRelease;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
if (_toRelease != null)
{
_toRelease._semaphore.Release();
}
}
}
}
} | 29.92 | 121 | 0.469697 | [
"Apache-2.0"
] | 0xflotus/osharp | src/OSharp/Threading/Asyncs/AsyncLock.cs | 2,310 | C# |
namespace StreamFlow.Configuration
{
public interface IQueueOptionsBuilder
{
IQueueOptionsBuilder Durable(bool durable = true);
IQueueOptionsBuilder Exclusive(bool exclusive = true);
IQueueOptionsBuilder AutoDelete(bool autoDelete = true);
IQueueOptionsBuilder Argument(string key, object value);
IQueueOptionsBuilder Quorum(int? initialGroupSize = null, bool enabled = true);
}
}
| 37 | 88 | 0.709459 | [
"Apache-2.0"
] | mentalist-dev/StreamFlow | sources/StreamFlow/Configuration/IQueueOptionsBuilder.cs | 444 | C# |
using System.Text.Json.Serialization;
namespace Swashbuckle.AspNetCore.SwaggerGen.Test
{
public class TypeWithPropertiesSetViaConstructor
{
public TypeWithPropertiesSetViaConstructor(int id, string desc)
{
Id = id;
Description = desc;
}
public int Id { get; }
[JsonPropertyName("Desc")]
public string Description { get; }
}
}
| 21.789474 | 71 | 0.620773 | [
"MIT"
] | AlexeiScherbakov/Swashbuckle.AspNetCore | test/Swashbuckle.AspNetCore.SwaggerGen.Test/Fixtures/TypeWithPropertiesSetViaConstructor.cs | 416 | C# |
using HSDRawViewer.GUI;
using mexTool.Core;
using mexTool.GUI.Controls;
using System;
using System.Windows.Forms;
namespace mexTool.GUI.Pages
{
public partial class StagePage : UserControl
{
private MXPropertyGrid _propertyGrid;
private ItemEditor _itemEditor;
private PlaylistEditor _playListEditor;
public StagePage()
{
InitializeComponent();
_propertyGrid = new MXPropertyGrid();
_propertyGrid.Visible = false;
_propertyGrid.Dock = DockStyle.Fill;
_propertyGrid.PropertySort = PropertySort.Categorized;
contentPanel.Controls.Add(_propertyGrid);
_itemEditor = new ItemEditor();
_itemEditor.Visible = false;
_itemEditor.Dock = DockStyle.Fill;
contentPanel.Controls.Add(_itemEditor);
_playListEditor = new PlaylistEditor();
_playListEditor.Visible = false;
_playListEditor.Dock = DockStyle.Fill;
contentPanel.Controls.Add(_playListEditor);
listBoxStage.DataSource = Core.MEX.Stages;
SelectTab(buttonGeneralTab, null);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void SelectTab(object sender, EventArgs args)
{
buttonGeneralTab.BackFillColor = ThemeColors.TabColor;
buttonItemTab.BackFillColor = ThemeColors.TabColor;
buttonPlaylistTab.BackFillColor = ThemeColors.TabColor;
((MXButton)sender).BackFillColor = ThemeColors.TabColorSelected;
ShowEditor();
}
/// <summary>
///
/// </summary>
private void ShowEditor()
{
_propertyGrid.Visible = false;
_itemEditor.Visible = false;
_playListEditor.Visible = false;
if (listBoxStage.SelectedItem is MEXStage stage)
{
if (buttonGeneralTab.BackFillColor == ThemeColors.TabColorSelected)
{
_propertyGrid.Visible = true;
_propertyGrid.SelectedObject = stage;
}
if (buttonItemTab.BackFillColor == ThemeColors.TabColorSelected)
{
_itemEditor.Visible = true;
_itemEditor.DataSource = stage.Items;
}
if (buttonPlaylistTab.BackFillColor == ThemeColors.TabColorSelected)
{
_playListEditor.Visible = true;
_playListEditor.SetPlaylist(stage.Playlist);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBoxStage_SelectedValueChanged(object sender, EventArgs e)
{
ShowEditor();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemove_Click(object sender, EventArgs e)
{
if (listBoxStage.SelectedItem is MEXStage stage)
{
if (stage.IsMEXStage &&
MessageBox.Show($"Are you sure you want to delete {stage.ToString()}?", "Delete Stage", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
MEX.Stages.Remove(stage);
else
{
MessageBox.Show("Cannot delete base game stage.", "Delete Stage", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonClone_Click(object sender, EventArgs e)
{
if (listBoxStage.SelectedItem is MEXStage stage)
{
var clone = stage.Copy();
clone.StageName += "Clone";
clone.SoundBank = stage.SoundBank;
MEX.Stages.Add(clone);
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void importButton_Click(object sender, EventArgs e)
{
using (OpenFileDialog d = new OpenFileDialog())
{
d.Filter = "MEX Stage (*.zip)|*.zip";
if (d.ShowDialog() == DialogResult.OK)
{
MEXStage.InstallStageFromFile(d.FileName);
listBoxStage.Invalidate();
}
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonExport_Click(object sender, EventArgs e)
{
if (listBoxStage.SelectedItem is MEXStage stage)
{
using (SaveFileDialog d = new SaveFileDialog())
{
d.Filter = "MEX Stage (*.zip)|*.zip";
if (d.ShowDialog() == DialogResult.OK)
{
stage.SaveStageToPackage(d.FileName);
}
}
}
}
}
}
| 31.182857 | 159 | 0.510903 | [
"MIT"
] | blooz/mexTool | mexTool/GUI/Pages/StagePage.cs | 5,459 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace LoRaWan.NetworkServer.Test
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using LoRaTools.CommonAPI;
using LoRaTools.LoRaMessage;
using LoRaTools.Regions;
using LoRaTools.Utils;
using LoRaWan.NetworkServer;
using LoRaWan.Test.Shared;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Shared;
using Microsoft.Extensions.Caching.Memory;
using Moq;
using Xunit;
// End to end tests without external dependencies (IoT Hub, Service Facade Function)
// Class C device tests
public class MessageProcessor_End2End_NoDep_ClassC_Tests : MessageProcessorTestBase
{
public MessageProcessor_End2End_NoDep_ClassC_Tests()
{
}
[Theory]
[InlineData(null, 0U, 0U)]
[InlineData(null, 0U, 9U)]
[InlineData(null, 5U, 5U)]
[InlineData(null, 5U, 14U)]
[InlineData(ServerGatewayID, 0U, 0U)]
[InlineData(ServerGatewayID, 0U, 19U)]
[InlineData(ServerGatewayID, 5U, 5U)]
[InlineData(ServerGatewayID, 5U, 24U)]
public async Task When_ABP_Sends_Upstream_Followed_By_DirectMethod_Should_Send_Upstream_And_Downstream(string deviceGatewayID, uint fcntDownFromTwin, uint fcntDelta)
{
const uint payloadFcnt = 2; // to avoid relax mode reset
var simDevice = new SimulatedDevice(TestDeviceInfo.CreateABPDevice(1, gatewayID: deviceGatewayID, deviceClassType: 'c'), frmCntDown: fcntDownFromTwin);
this.LoRaDeviceClient.Setup(x => x.UpdateReportedPropertiesAsync(It.IsNotNull<TwinCollection>()))
.ReturnsAsync(true);
var twin = simDevice.CreateABPTwin(reportedProperties: new Dictionary<string, object>
{
{ TwinProperty.Region, LoRaRegionType.EU868.ToString() }
});
this.LoRaDeviceClient.Setup(x => x.GetTwinAsync())
.ReturnsAsync(twin);
this.LoRaDeviceClient.Setup(x => x.SendEventAsync(It.IsNotNull<LoRaDeviceTelemetry>(), null))
.ReturnsAsync(true);
this.LoRaDeviceClient.Setup(x => x.ReceiveAsync(It.IsNotNull<TimeSpan>()))
.ReturnsAsync((Message)null);
this.LoRaDeviceApi.Setup(x => x.SearchByDevAddrAsync(simDevice.DevAddr))
.ReturnsAsync(new SearchDevicesResult(new IoTHubDeviceInfo(simDevice.DevAddr, simDevice.DevEUI, "123").AsList()));
if (deviceGatewayID == null)
{
this.LoRaDeviceApi.Setup(x => x.ExecuteFunctionBundlerAsync(simDevice.DevEUI, It.IsNotNull<FunctionBundlerRequest>()))
.ReturnsAsync(new FunctionBundlerResult());
}
var deviceRegistry = new LoRaDeviceRegistry(this.ServerConfiguration, this.NewMemoryCache(), this.LoRaDeviceApi.Object, this.LoRaDeviceFactory);
var messageDispatcher = new MessageDispatcher(
this.ServerConfiguration,
deviceRegistry,
this.FrameCounterUpdateStrategyProvider);
var request = this.CreateWaitableRequest(simDevice.CreateUnconfirmedMessageUplink("1", fcnt: payloadFcnt).Rxpk[0]);
messageDispatcher.DispatchRequest(request);
Assert.True(await request.WaitCompleteAsync());
Assert.True(request.ProcessingSucceeded);
// wait until cache has been updated
await Task.Delay(50);
// Adds fcntdown to device, simulating multiple downstream calls
Assert.True(deviceRegistry.InternalGetCachedDevicesForDevAddr(simDevice.DevAddr).TryGetValue(simDevice.DevEUI, out var loRaDevice));
loRaDevice.SetFcntDown(fcntDelta + loRaDevice.FCntDown);
var classCSender = new DefaultClassCDevicesMessageSender(
this.ServerConfiguration,
deviceRegistry,
this.PacketForwarder,
this.FrameCounterUpdateStrategyProvider);
var c2d = new ReceivedLoRaCloudToDeviceMessage()
{
DevEUI = simDevice.DevEUI,
MessageId = Guid.NewGuid().ToString(),
Payload = "aaaa",
Fport = 18,
};
var expectedFcntDown = fcntDownFromTwin + Constants.MAX_FCNT_UNSAVED_DELTA + fcntDelta;
if (string.IsNullOrEmpty(deviceGatewayID))
{
this.LoRaDeviceApi.Setup(x => x.NextFCntDownAsync(simDevice.DevEUI, fcntDownFromTwin + fcntDelta, 0, this.ServerConfiguration.GatewayID))
.ReturnsAsync((ushort)expectedFcntDown);
}
Assert.True(await classCSender.SendAsync(c2d));
Assert.Single(this.PacketForwarder.DownlinkMessages);
var downstreamMsg = this.PacketForwarder.DownlinkMessages[0];
byte[] downstreamPayloadBytes = Convert.FromBase64String(downstreamMsg.Txpk.Data);
var downstreamPayload = new LoRaPayloadData(downstreamPayloadBytes);
Assert.Equal(expectedFcntDown, downstreamPayload.GetFcnt());
Assert.Equal(c2d.Fport, downstreamPayload.GetFPort());
Assert.Equal(downstreamPayload.DevAddr.ToArray(), ConversionHelper.StringToByteArray(simDevice.DevAddr));
var decryptedPayload = downstreamPayload.GetDecryptedPayload(simDevice.AppSKey);
Assert.Equal(c2d.Payload, Encoding.UTF8.GetString(decryptedPayload));
Assert.Equal(expectedFcntDown, loRaDevice.FCntDown);
Assert.Equal(payloadFcnt, loRaDevice.FCntUp);
Assert.False(loRaDevice.HasFrameCountChanges);
this.LoRaDeviceApi.VerifyAll();
this.LoRaDeviceClient.VerifyAll();
}
[Theory]
[InlineData(null)]
[InlineData(ServerGatewayID)]
public async Task When_OTAA_Join_Then_Sends_Upstream_DirectMethod_Should_Send_Downstream(string deviceGatewayID)
{
var simDevice = new SimulatedDevice(TestDeviceInfo.CreateOTAADevice(1, deviceClassType: 'c', gatewayID: deviceGatewayID));
this.LoRaDeviceClient.Setup(x => x.GetTwinAsync())
.ReturnsAsync(simDevice.CreateOTAATwin());
var savedAppSKey = string.Empty;
var savedNwkSKey = string.Empty;
var savedDevAddr = string.Empty;
this.LoRaDeviceClient.Setup(x => x.UpdateReportedPropertiesAsync(It.IsNotNull<TwinCollection>()))
.ReturnsAsync(true)
.Callback<TwinCollection>((t) =>
{
savedAppSKey = t[TwinProperty.AppSKey];
savedNwkSKey = t[TwinProperty.NwkSKey];
savedDevAddr = t[TwinProperty.DevAddr];
Assert.NotEmpty(savedAppSKey);
Assert.NotEmpty(savedNwkSKey);
Assert.NotEmpty(savedDevAddr);
});
this.LoRaDeviceClient.Setup(x => x.SendEventAsync(It.IsNotNull<LoRaDeviceTelemetry>(), null))
.ReturnsAsync(true);
this.LoRaDeviceClient.Setup(x => x.ReceiveAsync(It.IsNotNull<TimeSpan>()))
.ReturnsAsync((Message)null);
if (deviceGatewayID == null)
{
this.LoRaDeviceApi.Setup(x => x.ExecuteFunctionBundlerAsync(simDevice.DevEUI, It.IsNotNull<FunctionBundlerRequest>()))
.ReturnsAsync(new FunctionBundlerResult());
}
this.LoRaDeviceApi.Setup(x => x.SearchAndLockForJoinAsync(this.ServerConfiguration.GatewayID, simDevice.DevEUI, simDevice.AppEUI, It.IsNotNull<string>()))
.ReturnsAsync(new SearchDevicesResult(new IoTHubDeviceInfo(simDevice.DevAddr, simDevice.DevEUI, "123").AsList()));
var deviceRegistry = new LoRaDeviceRegistry(this.ServerConfiguration, this.NewMemoryCache(), this.LoRaDeviceApi.Object, this.LoRaDeviceFactory);
var messageDispatcher = new MessageDispatcher(
this.ServerConfiguration,
deviceRegistry,
this.FrameCounterUpdateStrategyProvider);
var joinRxpk = simDevice.CreateJoinRequest().SerializeUplink(simDevice.AppKey).Rxpk[0];
var joinRequest = this.CreateWaitableRequest(joinRxpk);
messageDispatcher.DispatchRequest(joinRequest);
Assert.True(await joinRequest.WaitCompleteAsync());
Assert.True(joinRequest.ProcessingSucceeded);
simDevice.SetupJoin(savedAppSKey, savedNwkSKey, savedDevAddr);
var request = this.CreateWaitableRequest(simDevice.CreateUnconfirmedMessageUplink("1").Rxpk[0]);
messageDispatcher.DispatchRequest(request);
Assert.True(await request.WaitCompleteAsync());
Assert.True(request.ProcessingSucceeded);
var classCSender = new DefaultClassCDevicesMessageSender(
this.ServerConfiguration,
deviceRegistry,
this.PacketForwarder,
this.FrameCounterUpdateStrategyProvider);
var c2d = new ReceivedLoRaCloudToDeviceMessage()
{
DevEUI = simDevice.DevEUI,
MessageId = Guid.NewGuid().ToString(),
Payload = "aaaa",
Fport = 14,
};
if (string.IsNullOrEmpty(deviceGatewayID))
{
this.LoRaDeviceApi.Setup(x => x.NextFCntDownAsync(simDevice.DevEUI, simDevice.FrmCntDown, 0, this.ServerConfiguration.GatewayID))
.ReturnsAsync((ushort)(simDevice.FrmCntDown + 1));
}
Assert.True(await classCSender.SendAsync(c2d));
Assert.Equal(2, this.PacketForwarder.DownlinkMessages.Count);
var downstreamMsg = this.PacketForwarder.DownlinkMessages[1];
TestLogger.Log($"appSKey: {simDevice.AppSKey}, nwkSKey: {simDevice.NwkSKey}");
byte[] downstreamPayloadBytes = Convert.FromBase64String(downstreamMsg.Txpk.Data);
var downstreamPayload = new LoRaPayloadData(downstreamPayloadBytes);
Assert.Equal(1, downstreamPayload.GetFcnt());
Assert.Equal(c2d.Fport, downstreamPayload.GetFPort());
Assert.Equal(downstreamPayload.DevAddr.ToArray(), ConversionHelper.StringToByteArray(savedDevAddr));
var decryptedPayload = downstreamPayload.GetDecryptedPayload(simDevice.AppSKey);
Assert.Equal(c2d.Payload, Encoding.UTF8.GetString(decryptedPayload));
this.LoRaDeviceApi.VerifyAll();
this.LoRaDeviceClient.VerifyAll();
}
[Fact]
public async Task Unconfirmed_Cloud_To_Device_From_Decoder_Should_Call_ClassC_Message_Sender()
{
const uint PayloadFcnt = 10;
const uint InitialDeviceFcntUp = 9;
const uint InitialDeviceFcntDown = 20;
var simulatedDevice = new SimulatedDevice(
TestDeviceInfo.CreateABPDevice(1, gatewayID: this.ServerConfiguration.GatewayID),
frmCntUp: InitialDeviceFcntUp,
frmCntDown: InitialDeviceFcntDown);
var loraDevice = this.CreateLoRaDevice(simulatedDevice);
this.LoRaDeviceClient.Setup(x => x.SendEventAsync(It.IsNotNull<LoRaDeviceTelemetry>(), null))
.ReturnsAsync(true);
this.LoRaDeviceClient.Setup(x => x.ReceiveAsync(It.IsAny<TimeSpan>()))
.ReturnsAsync((Message)null);
var decoderResult = new DecodePayloadResult("1")
{
CloudToDeviceMessage = new ReceivedLoRaCloudToDeviceMessage()
{
Fport = 1,
MessageId = "123",
Payload = "12",
DevEUI = "0000000000000002",
},
};
var payloadDecoder = new Mock<ILoRaPayloadDecoder>(MockBehavior.Strict);
payloadDecoder.Setup(x => x.DecodeMessageAsync(simulatedDevice.DevEUI, It.IsNotNull<byte[]>(), 1, It.IsAny<string>()))
.ReturnsAsync(decoderResult);
this.PayloadDecoder.SetDecoder(payloadDecoder.Object);
var deviceRegistry = new LoRaDeviceRegistry(this.ServerConfiguration, this.NewNonEmptyCache(loraDevice), this.LoRaDeviceApi.Object, this.LoRaDeviceFactory);
var c2dMessageSent = new SemaphoreSlim(0);
var classCMessageSender = new Mock<IClassCDeviceMessageSender>(MockBehavior.Strict);
classCMessageSender.Setup(x => x.SendAsync(It.IsNotNull<IReceivedLoRaCloudToDeviceMessage>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(true)
.Callback<IReceivedLoRaCloudToDeviceMessage, CancellationToken>((m, _) =>
{
Assert.False(m.Confirmed);
Assert.Equal("0000000000000002", m.DevEUI);
c2dMessageSent.Release();
});
this.RequestHandlerImplementation.SetClassCMessageSender(classCMessageSender.Object);
// Send to message processor
var messageProcessor = new MessageDispatcher(
this.ServerConfiguration,
deviceRegistry,
this.FrameCounterUpdateStrategyProvider);
var payload = simulatedDevice.CreateUnconfirmedDataUpMessage("1234", fcnt: PayloadFcnt);
var rxpk = payload.SerializeUplink(simulatedDevice.AppSKey, simulatedDevice.NwkSKey).Rxpk[0];
var request = this.CreateWaitableRequest(rxpk);
messageProcessor.DispatchRequest(request);
Assert.True(await request.WaitCompleteAsync());
// Expectations
// 1. Message was sent to IoT Hub
this.LoRaDeviceClient.VerifyAll();
this.LoRaDeviceApi.VerifyAll();
// 2. No downstream message for the current device is sent
Assert.Null(request.ResponseDownlink);
Assert.True(request.ProcessingSucceeded);
// 4. Frame counter up was updated
Assert.Equal(PayloadFcnt, loraDevice.FCntUp);
// 5. Frame counter down is unchanged
Assert.Equal(InitialDeviceFcntDown, loraDevice.FCntDown);
// 6. Frame count has pending changes
Assert.True(loraDevice.HasFrameCountChanges);
// Ensure the message was sent
Assert.True(await c2dMessageSent.WaitAsync(10 * 1000));
payloadDecoder.VerifyAll();
classCMessageSender.VerifyAll();
}
[Theory]
[CombinatorialData]
public async Task When_Joining_Should_Save_Region_And_Preferred_Gateway(
[CombinatorialValues(null, ServerGatewayID)] string deviceGatewayID,
[CombinatorialValues(null, ServerGatewayID, "another-gateway")] string initialPreferredGatewayID,
[CombinatorialValues(null, LoRaRegionType.EU868, LoRaRegionType.US915)] LoRaRegionType? initialLoRaRegion)
{
var simDevice = new SimulatedDevice(TestDeviceInfo.CreateOTAADevice(1, deviceClassType: 'c', gatewayID: deviceGatewayID));
var customReportedProperties = new Dictionary<string, object>();
// reported: { 'PreferredGateway': '' } -> if device is for multiple gateways and one initial was defined
if (string.IsNullOrEmpty(deviceGatewayID) && !string.IsNullOrEmpty(initialPreferredGatewayID))
customReportedProperties[TwinProperty.PreferredGatewayID] = initialPreferredGatewayID;
if (initialLoRaRegion.HasValue)
customReportedProperties[TwinProperty.Region] = initialLoRaRegion.Value.ToString();
this.LoRaDeviceClient.Setup(x => x.GetTwinAsync())
.ReturnsAsync(simDevice.CreateOTAATwin(reportedProperties: customReportedProperties));
var shouldSavePreferredGateway = string.IsNullOrEmpty(deviceGatewayID) && initialPreferredGatewayID != ServerGatewayID;
var shouldSaveRegion = !initialLoRaRegion.HasValue || initialLoRaRegion.Value != LoRaRegionType.EU868;
var savedAppSKey = string.Empty;
var savedNwkSKey = string.Empty;
var savedDevAddr = string.Empty;
this.LoRaDeviceClient.Setup(x => x.UpdateReportedPropertiesAsync(It.IsNotNull<TwinCollection>()))
.ReturnsAsync(true)
.Callback<TwinCollection>((t) =>
{
savedAppSKey = t[TwinProperty.AppSKey];
savedNwkSKey = t[TwinProperty.NwkSKey];
savedDevAddr = t[TwinProperty.DevAddr];
Assert.NotEmpty(savedAppSKey);
Assert.NotEmpty(savedNwkSKey);
Assert.NotEmpty(savedDevAddr);
if (shouldSaveRegion)
Assert.Equal(LoRaRegionType.EU868.ToString(), t[TwinProperty.Region].Value as string);
else
Assert.False(t.Contains(TwinProperty.Region));
// Only save preferred gateway if device does not have one assigned
if (shouldSavePreferredGateway)
Assert.Equal(this.ServerConfiguration.GatewayID, t[TwinProperty.PreferredGatewayID].Value as string);
else
Assert.False(t.Contains(TwinProperty.PreferredGatewayID));
});
this.LoRaDeviceApi.Setup(x => x.SearchAndLockForJoinAsync(this.ServerConfiguration.GatewayID, simDevice.DevEUI, simDevice.AppEUI, It.IsNotNull<string>()))
.ReturnsAsync(new SearchDevicesResult(new IoTHubDeviceInfo(simDevice.DevAddr, simDevice.DevEUI, "123").AsList()));
var deviceRegistry = new LoRaDeviceRegistry(this.ServerConfiguration, this.NewMemoryCache(), this.LoRaDeviceApi.Object, this.LoRaDeviceFactory);
var messageDispatcher = new MessageDispatcher(
this.ServerConfiguration,
deviceRegistry,
this.FrameCounterUpdateStrategyProvider);
var joinRxpk = simDevice.CreateJoinRequest().SerializeUplink(simDevice.AppKey).Rxpk[0];
var joinRequest = this.CreateWaitableRequest(joinRxpk);
messageDispatcher.DispatchRequest(joinRequest);
Assert.True(await joinRequest.WaitCompleteAsync());
Assert.True(joinRequest.ProcessingSucceeded);
var devices = deviceRegistry.InternalGetCachedDevicesForDevAddr(savedDevAddr);
Assert.True(devices.TryGetValue(simDevice.DevEUI, out var loRaDevice));
Assert.Equal(LoRaDeviceClassType.C, loRaDevice.ClassType);
if (string.IsNullOrEmpty(simDevice.LoRaDevice.GatewayID))
Assert.Equal(this.ServerConfiguration.GatewayID, loRaDevice.PreferredGatewayID);
else
Assert.Empty(loRaDevice.PreferredGatewayID);
Assert.Equal(LoRaRegionType.EU868, loRaDevice.LoRaRegion);
this.LoRaDeviceApi.VerifyAll();
this.LoRaDeviceClient.VerifyAll();
}
[Theory]
[CombinatorialData]
public async Task When_Processing_Data_Request_Should_Compute_Preferred_Gateway_And_Region(
[CombinatorialValues(null, ServerGatewayID)] string deviceGatewayID,
[CombinatorialValues(null, ServerGatewayID, "another-gateway")] string initialPreferredGatewayID,
[CombinatorialValues(ServerGatewayID, "another-gateway")] string preferredGatewayID,
[CombinatorialValues(null, LoRaRegionType.EU868, LoRaRegionType.US915)] LoRaRegionType? initialLoRaRegion)
{
const uint PayloadFcnt = 10;
const uint InitialDeviceFcntUp = 9;
const uint InitialDeviceFcntDown = 20;
var simulatedDevice = new SimulatedDevice(
TestDeviceInfo.CreateABPDevice(1, gatewayID: deviceGatewayID, deviceClassType: 'c'),
frmCntUp: InitialDeviceFcntUp,
frmCntDown: InitialDeviceFcntDown);
var loraDevice = this.CreateLoRaDevice(simulatedDevice);
loraDevice.UpdatePreferredGatewayID(initialPreferredGatewayID, acceptChanges: true);
if (initialLoRaRegion.HasValue)
loraDevice.UpdateRegion(initialLoRaRegion.Value, acceptChanges: true);
var shouldSavePreferredGateway = string.IsNullOrEmpty(deviceGatewayID) && initialPreferredGatewayID != preferredGatewayID && preferredGatewayID == ServerGatewayID;
var shouldSaveRegion = (!initialLoRaRegion.HasValue || initialLoRaRegion.Value != LoRaRegionType.EU868) && (preferredGatewayID == ServerGatewayID || deviceGatewayID != null);
var bundlerResult = new FunctionBundlerResult()
{
PreferredGatewayResult = new PreferredGatewayResult()
{
DevEUI = simulatedDevice.DevEUI,
PreferredGatewayID = preferredGatewayID,
CurrentFcntUp = PayloadFcnt,
RequestFcntUp = PayloadFcnt,
}
};
if (string.IsNullOrEmpty(deviceGatewayID))
{
this.LoRaDeviceApi.Setup(x => x.ExecuteFunctionBundlerAsync(simulatedDevice.DevEUI, It.IsNotNull<FunctionBundlerRequest>()))
.Callback<string, FunctionBundlerRequest>((devEUI, bundlerRequest) =>
{
Assert.Equal(PayloadFcnt, bundlerRequest.ClientFCntUp);
Assert.Equal(ServerGatewayID, bundlerRequest.GatewayId);
Assert.Equal(FunctionBundlerItemType.PreferredGateway, bundlerRequest.FunctionItems);
})
.ReturnsAsync(bundlerResult);
}
if (shouldSavePreferredGateway || shouldSaveRegion)
{
this.LoRaDeviceClient.Setup(x => x.UpdateReportedPropertiesAsync(It.IsNotNull<TwinCollection>()))
.Callback<TwinCollection>((savedTwin) =>
{
if (shouldSavePreferredGateway)
Assert.Equal(ServerGatewayID, savedTwin[TwinProperty.PreferredGatewayID].Value as string);
else
Assert.False(savedTwin.Contains(TwinProperty.PreferredGatewayID));
if (shouldSaveRegion)
Assert.Equal(LoRaRegionType.EU868.ToString(), savedTwin[TwinProperty.Region].Value as string);
else
Assert.False(savedTwin.Contains(TwinProperty.Region));
})
.ReturnsAsync(true);
}
this.LoRaDeviceClient.Setup(x => x.SendEventAsync(It.IsNotNull<LoRaDeviceTelemetry>(), null))
.ReturnsAsync(true);
this.LoRaDeviceClient.Setup(x => x.ReceiveAsync(It.IsAny<TimeSpan>()))
.ReturnsAsync((Message)null);
var deviceRegistry = new LoRaDeviceRegistry(this.ServerConfiguration, this.NewNonEmptyCache(loraDevice), this.LoRaDeviceApi.Object, this.LoRaDeviceFactory);
// Send to message processor
var messageProcessor = new MessageDispatcher(
this.ServerConfiguration,
deviceRegistry,
this.FrameCounterUpdateStrategyProvider);
var payload = simulatedDevice.CreateUnconfirmedDataUpMessage("1234", fcnt: PayloadFcnt);
var rxpk = payload.SerializeUplink(simulatedDevice.AppSKey, simulatedDevice.NwkSKey).Rxpk[0];
var request = this.CreateWaitableRequest(rxpk);
messageProcessor.DispatchRequest(request);
Assert.True(await request.WaitCompleteAsync());
// Expectations
// 1. Message was sent to IoT Hub
this.LoRaDeviceClient.VerifyAll();
this.LoRaDeviceApi.VerifyAll();
// 2. No downstream message for the current device is sent
Assert.Null(request.ResponseDownlink);
Assert.True(request.ProcessingSucceeded);
if (!string.IsNullOrEmpty(deviceGatewayID))
Assert.Equal(initialPreferredGatewayID, loraDevice.PreferredGatewayID);
else
Assert.Equal(preferredGatewayID, loraDevice.PreferredGatewayID);
Assert.Equal(LoRaRegionType.EU868, loraDevice.LoRaRegion);
}
[Fact]
public async Task When_Updating_PreferredGateway_And_FcntUp_Should_Save_Twin_Once()
{
const uint PayloadFcnt = 10;
const uint InitialDeviceFcntUp = 9;
const uint InitialDeviceFcntDown = 20;
var simulatedDevice = new SimulatedDevice(
TestDeviceInfo.CreateABPDevice(1, deviceClassType: 'c'),
frmCntUp: InitialDeviceFcntUp,
frmCntDown: InitialDeviceFcntDown);
var loraDevice = this.CreateLoRaDevice(simulatedDevice);
loraDevice.UpdatePreferredGatewayID("another-gateway", acceptChanges: true);
var bundlerResult = new FunctionBundlerResult()
{
PreferredGatewayResult = new PreferredGatewayResult()
{
DevEUI = simulatedDevice.DevEUI,
PreferredGatewayID = ServerGatewayID,
CurrentFcntUp = PayloadFcnt,
RequestFcntUp = PayloadFcnt,
}
};
this.LoRaDeviceApi.Setup(x => x.ExecuteFunctionBundlerAsync(simulatedDevice.DevEUI, It.IsNotNull<FunctionBundlerRequest>()))
.Callback<string, FunctionBundlerRequest>((devEUI, bundlerRequest) =>
{
Assert.Equal(PayloadFcnt, bundlerRequest.ClientFCntUp);
Assert.Equal(ServerGatewayID, bundlerRequest.GatewayId);
Assert.Equal(FunctionBundlerItemType.PreferredGateway, bundlerRequest.FunctionItems);
})
.ReturnsAsync(bundlerResult);
this.LoRaDeviceClient.Setup(x => x.UpdateReportedPropertiesAsync(It.IsNotNull<TwinCollection>()))
.Callback<TwinCollection>((savedTwin) =>
{
Assert.Equal(ServerGatewayID, savedTwin[TwinProperty.PreferredGatewayID].Value as string);
Assert.Equal(LoRaRegionType.EU868.ToString(), savedTwin[TwinProperty.Region].Value as string);
Assert.Equal(PayloadFcnt, (uint)savedTwin[TwinProperty.FCntUp].Value);
})
.ReturnsAsync(true);
this.LoRaDeviceClient.Setup(x => x.SendEventAsync(It.IsNotNull<LoRaDeviceTelemetry>(), null))
.ReturnsAsync(true);
this.LoRaDeviceClient.Setup(x => x.ReceiveAsync(It.IsAny<TimeSpan>()))
.ReturnsAsync((Message)null);
var deviceRegistry = new LoRaDeviceRegistry(this.ServerConfiguration, this.NewNonEmptyCache(loraDevice), this.LoRaDeviceApi.Object, this.LoRaDeviceFactory);
// Send to message processor
var messageProcessor = new MessageDispatcher(
this.ServerConfiguration,
deviceRegistry,
this.FrameCounterUpdateStrategyProvider);
var payload = simulatedDevice.CreateUnconfirmedDataUpMessage("1234", fcnt: PayloadFcnt);
var rxpk = payload.SerializeUplink(simulatedDevice.AppSKey, simulatedDevice.NwkSKey).Rxpk[0];
var request = this.CreateWaitableRequest(rxpk);
messageProcessor.DispatchRequest(request);
Assert.True(await request.WaitCompleteAsync());
// Expectations
// 1. Message was sent to IoT Hub
this.LoRaDeviceClient.VerifyAll();
this.LoRaDeviceApi.VerifyAll();
// 2. No downstream message for the current device is sent
Assert.Null(request.ResponseDownlink);
Assert.True(request.ProcessingSucceeded);
Assert.Equal(ServerGatewayID, loraDevice.PreferredGatewayID);
Assert.Equal(LoRaRegionType.EU868, loraDevice.LoRaRegion);
Assert.Equal(PayloadFcnt, loraDevice.FCntUp);
this.LoRaDeviceClient.Verify(x => x.UpdateReportedPropertiesAsync(It.IsNotNull<TwinCollection>()), Times.Once());
}
}
} | 49.044521 | 186 | 0.639411 | [
"MIT"
] | LauraDamianTNA/iotedge-lorawan-starterkit | LoRaEngine/test/LoRaWanNetworkServer.Test/MessageProcessor_End2End_NoDep_ClassC_Tests.cs | 28,644 | C# |
// <copyright file="CauchyTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2014 Math.NET
//
// 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.
// </copyright>
using System;
using System.Linq;
using MathNet.Numerics.Distributions;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.DistributionTests.Continuous
{
/// <summary>
/// Cauchy distribution tests.
/// </summary>
[TestFixture, Category("Distributions")]
public class CauchyTests
{
/// <summary>
/// Can create Cauchy.
/// </summary>
[Test]
public void CanCreateCauchy()
{
var n = new Cauchy();
Assert.AreEqual(0.0, n.Location);
Assert.AreEqual(1.0, n.Scale);
}
/// <summary>
/// Can create Cauchy.
/// </summary>
/// <param name="location">Location value.</param>
/// <param name="scale">Scale value.</param>
[TestCase(0.0, 0.1)]
[TestCase(0.0, 1.0)]
[TestCase(0.0, 10.0)]
[TestCase(10.0, 11.0)]
[TestCase(-5.0, 100.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void CanCreateCauchy(double location, double scale)
{
var n = new Cauchy(location, scale);
Assert.AreEqual(location, n.Location);
Assert.AreEqual(scale, n.Scale);
}
/// <summary>
/// Cauchy create fails with bad parameters.
/// </summary>
/// <param name="location">Location value.</param>
/// <param name="scale">Scale value.</param>
[TestCase(Double.NaN, 1.0)]
[TestCase(1.0, Double.NaN)]
[TestCase(Double.NaN, Double.NaN)]
[TestCase(1.0, 0.0)]
public void CauchyCreateFailsWithBadParameters(double location, double scale)
{
Assert.That(() => new Cauchy(location, scale), Throws.ArgumentException);
}
/// <summary>
/// Validate ToString.
/// </summary>
[Test]
public void ValidateToString()
{
var n = new Cauchy(1d, 2d);
Assert.AreEqual("Cauchy(x0 = 1, γ = 2)", n.ToString());
}
/// <summary>
/// Validate entropy.
/// </summary>
/// <param name="location">Location value.</param>
/// <param name="scale">Scale value.</param>
[TestCase(-0.0, 2.0)]
[TestCase(0.0, 2.0)]
[TestCase(0.1, 4.0)]
[TestCase(1.0, 10.0)]
[TestCase(10.0, 11.0)]
public void ValidateEntropy(double location, double scale)
{
var n = new Cauchy(location, scale);
Assert.AreEqual(Math.Log(4.0 * Constants.Pi * scale), n.Entropy);
}
/// <summary>
/// Validate skewness throws <c>NotSupportedException</c>.
/// </summary>
[Test]
public void ValidateSkewnessThrowsNotSupportedException()
{
var n = new Cauchy(-0.0, 2.0);
Assert.Throws<NotSupportedException>(() => { var s = n.Skewness; });
}
/// <summary>
/// Validate mode.
/// </summary>
/// <param name="location">Location value.</param>
/// <param name="scale">Scale value.</param>
[TestCase(-0.0, 2.0)]
[TestCase(0.0, 2.0)]
[TestCase(0.1, 4.0)]
[TestCase(1.0, 10.0)]
[TestCase(10.0, 11.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateMode(double location, double scale)
{
var n = new Cauchy(location, scale);
Assert.AreEqual(location, n.Mode);
}
/// <summary>
/// Validate median.
/// </summary>
/// <param name="location">Location value.</param>
/// <param name="scale">Scale value.</param>
[TestCase(-0.0, 2.0)]
[TestCase(0.0, 2.0)]
[TestCase(0.1, 4.0)]
[TestCase(1.0, 10.0)]
[TestCase(10.0, 11.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateMedian(double location, double scale)
{
var n = new Cauchy(location, scale);
Assert.AreEqual(location, n.Median);
}
/// <summary>
/// Validate minimum.
/// </summary>
/// <param name="location">Location value.</param>
/// <param name="scale">Scale value.</param>
[TestCase(-0.0, 2.0)]
[TestCase(0.0, 2.0)]
[TestCase(0.1, 4.0)]
[TestCase(1.0, 10.0)]
[TestCase(10.0, 11.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateMinimum(double location, double scale)
{
var n = new Cauchy(location, scale);
Assert.AreEqual(Double.NegativeInfinity, n.Minimum);
}
/// <summary>
/// Validate maximum.
/// </summary>
/// <param name="location">Location value.</param>
/// <param name="scale">Scale value.</param>
[TestCase(-0.0, 2.0)]
[TestCase(0.0, 2.0)]
[TestCase(0.1, 4.0)]
[TestCase(1.0, 10.0)]
[TestCase(10.0, 11.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateMaximum(double location, double scale)
{
var n = new Cauchy(location, scale);
Assert.AreEqual(Double.PositiveInfinity, n.Maximum);
}
/// <summary>
/// Validate density.
/// </summary>
/// <param name="location">Location value.</param>
/// <param name="scale">Scale value.</param>
[TestCase(0.0, 0.1)]
[TestCase(0.0, 1.0)]
[TestCase(0.0, 10.0)]
[TestCase(-5.0, 100.0)]
[TestCase(0.0, Double.PositiveInfinity)]
[TestCase(Double.PositiveInfinity, 1.0)]
public void ValidateDensity(double location, double scale)
{
var n = new Cauchy(location, scale);
for (var i = 0; i < 11; i++)
{
var x = i - 5.0;
double expected = 1.0 / ((Constants.Pi * scale) * (1.0 + (((x - location) / scale) * ((x - location) / scale))));
Assert.AreEqual(expected, n.Density(x));
Assert.AreEqual(expected, Cauchy.PDF(location, scale, x));
}
}
/// <summary>
/// Validate density log.
/// </summary>
/// <param name="location">Location value.</param>
/// <param name="scale">Scale value.</param>
[TestCase(0.0, 0.1)]
[TestCase(0.0, 1.0)]
[TestCase(0.0, 10.0)]
[TestCase(-5.0, 100.0)]
[TestCase(0.0, Double.PositiveInfinity)]
[TestCase(Double.PositiveInfinity, 1.0)]
public void ValidateDensityLn(double location, double scale)
{
var n = new Cauchy(location, scale);
for (var i = 0; i < 11; i++)
{
var x = i - 5.0;
double expected = -Math.Log((Constants.Pi * scale) * (1.0 + (((x - location) / scale) * ((x - location) / scale))));
Assert.AreEqual(expected, n.DensityLn(x));
Assert.AreEqual(expected, Cauchy.PDFLn(location, scale, x));
}
}
/// <summary>
/// Can sample.
/// </summary>
[Test]
public void CanSample()
{
var n = new Cauchy();
n.Sample();
}
/// <summary>
/// Can sample sequence.
/// </summary>
[Test]
public void CanSampleSequence()
{
var n = new Cauchy();
var ied = n.Samples();
GC.KeepAlive(ied.Take(5).ToArray());
}
/// <summary>
/// Validate cumulative distribution.
/// </summary>
/// <param name="location">Location value.</param>
/// <param name="scale">Scale value.</param>
[TestCase(0.0, 0.1)]
[TestCase(0.0, 1.0)]
[TestCase(0.0, 10.0)]
[TestCase(-5.0, 100.0)]
[TestCase(0.0, Double.PositiveInfinity)]
public void ValidateCumulativeDistribution(double location, double scale)
{
var n = new Cauchy(location, scale);
for (var i = 0; i < 11; i++)
{
var x = i - 5.0;
double expected = (Math.Atan((x - location)/scale))/Math.PI + 0.5;
Assert.AreEqual(expected, n.CumulativeDistribution(x), 1e-12);
Assert.AreEqual(expected, Cauchy.CDF(location, scale, x), 1e-12);
}
}
/// <summary>
/// Validate inverse cumulative distribution.
/// </summary>
/// <param name="location">Location value.</param>
/// <param name="scale">Scale value.</param>
[TestCase(0.0, 0.1)]
[TestCase(0.0, 1.0)]
[TestCase(0.0, 10.0)]
[TestCase(-5.0, 100.0)]
public void ValidateInverseCumulativeDistribution(double location, double scale)
{
var n = new Cauchy(location, scale);
for (var i = 0; i < 11; i++)
{
var x = i - 5.0;
double expected = (Math.Atan((x - location)/scale))/Math.PI + 0.5;
Assert.AreEqual(x, n.InverseCumulativeDistribution(expected), 1e-12);
Assert.AreEqual(x, Cauchy.InvCDF(location, scale, expected), 1e-12);
}
}
}
}
| 35.072848 | 132 | 0.540691 | [
"MIT"
] | MattHeffron/mathnet-numerics | src/UnitTests/DistributionTests/Continuous/CauchyTests.cs | 10,595 | C# |
using ChampsRoom.Helpers;
using ChampsRoom.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace ChampsRoom.Controllers
{
[Authorize]
[RoutePrefix("account")]
public class AccountController : Controller
{
private DataContext db = new DataContext();
public AccountController()
: this(new UserManager<User>(new UserStore<User>(new DataContext())))
{
}
public AccountController(UserManager<User> userManager)
{
UserManager = userManager;
UserManager.PasswordValidator = new PasswordValidator
{
RequireDigit = false,
RequiredLength = 2,
RequireNonLetterOrDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
}
public UserManager<User> UserManager { get; private set; }
[AllowAnonymous]
[Route("login")]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[Route("login")]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
[AllowAnonymous]
[Route("register")]
public ActionResult Register()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[Route("register")]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (!await IsNameAvailable(model.UserName))
ModelState.AddModelError(String.Empty, "Name is not available");
if (ModelState.IsValid)
{
var user = new User() { UserName = model.UserName, Slug = model.UserName.ToFriendlyUrl() };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
[Route("edit")]
public async Task<ActionResult> Edit()
{
var userid = User.Identity.GetUserId();
var user = await db.Users.FirstOrDefaultAsync(q => q.Id == userid);
if (user == null)
return HttpNotFound();
var viewmodel = new UserEditViewModel()
{
ImageUrl = user.ImageUrl,
UserName = user.UserName
};
return View(viewmodel);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("edit")]
public async Task<ActionResult> Edit(UserEditViewModel model)
{
var userid = User.Identity.GetUserId();
var user = await db.Users.FirstOrDefaultAsync(q => q.Id == userid);
if (user == null)
return HttpNotFound();
if (!await IsNameAvailable(model.UserName, user.UserName))
ModelState.AddModelError(String.Empty, "Name is not available");
if (ModelState.IsValid)
{
user.ImageUrl = model.ImageUrl;
user.UserName = model.UserName;
user.Slug = model.UserName.ToFriendlyUrl();
db.Entry(user).State = EntityState.Modified;
await db.SaveChangesAsync();
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Manage");
}
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Disassociate(string loginProvider, string providerKey)
{
ManageMessageId? message = null;
IdentityResult result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return RedirectToAction("Manage", new { Message = message });
}
public async Task<ActionResult> Manage(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
ViewBag.HasLocalPassword = HasPassword();
ViewBag.ReturnUrl = Url.Action("Manage");
var userid = User.Identity.GetUserId();
ViewBag.Leagues = await db.Users
.Include(i => i.Leagues)
.Where(q => q.Id == userid)
.SelectMany(s => s.Leagues)
.ToListAsync();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Manage(ChangePasswordViewModel model)
{
bool hasPassword = HasPassword();
ViewBag.HasLocalPassword = hasPassword;
ViewBag.ReturnUrl = Url.Action("Manage");
if (hasPassword)
{
if (ModelState.IsValid)
{
IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
AddErrors(result);
}
}
}
else
{
// User does not have a password so remove any validation errors caused by a missing OldPassword field
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (result.Succeeded)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
}
else
{
AddErrors(result);
}
}
}
//var userId = User.Identity.GetUserId();
//ViewBag.Leagues = db.Leagues.Where(q => q.Users.Any(u => u.Id == userId)).ToList();
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var user = await UserManager.FindAsync(loginInfo.Login);
if (user != null)
{
await OnExternalLoginAuth(user);
await SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
else
{
if (!String.IsNullOrWhiteSpace(loginInfo.DefaultUserName))
{
user = new User() { UserName = loginInfo.DefaultUserName, Slug = loginInfo.DefaultUserName.ToFriendlyUrl() };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);
if (result.Succeeded)
{
await OnExternalLoginAuth(user);
await SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
}
}
// If the user does not have an account, then prompt the user to create an account - and if the automatically create failed
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { UserName = loginInfo.DefaultUserName });
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
return new ChallengeResult(provider, Url.Action("LinkLoginCallback", "Account"), User.Identity.GetUserId());
}
public async Task<ActionResult> LinkLoginCallback()
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
if (result.Succeeded)
{
return RedirectToAction("Manage");
}
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new User() { UserName = model.UserName, Slug = model.UserName.ToFriendlyUrl() };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await OnExternalLoginAuth(user);
await SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
return RedirectToAction("Index", "Home");
}
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
[ChildActionOnly]
public ActionResult RemoveAccountList()
{
var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId());
ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts);
}
protected override void Dispose(bool disposing)
{
if (disposing && UserManager != null)
{
UserManager.Dispose();
UserManager = null;
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private async Task SignInAsync(User user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim("ImageUrl", user.GetImageUrl()));
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
public enum ManageMessageId
{
ChangePasswordSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
Error
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
private class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
private async Task<bool> IsNameAvailable(string name, string currentName = "")
{
if (String.IsNullOrWhiteSpace(name))
return false;
var notAllowed = new string[] {
"account",
"result",
"results",
"league",
"leagues",
"team",
"teams",
"user",
"users",
"player",
"players",
"admin",
"index",
"create",
"edit",
"details",
"delete",
"put",
"get",
"post",
"script",
"scripts",
"views",
"content",
"contents",
"image",
"images",
"url",
"slug",
"css",
"js",
"home"
};
var friendlyName = name.ToFriendlyUrl();
if (friendlyName.Equals(currentName.ToFriendlyUrl()))
return true;
if (notAllowed.Count(q => q.Equals(name, StringComparison.InvariantCultureIgnoreCase)) > 0)
return false;
var count = await db.Users.CountAsync(q => q.Slug.Equals(name, StringComparison.InvariantCultureIgnoreCase));
return count == 0;
}
private async Task SetTwitterProfileImage(string userId, IEnumerable<Claim> claims)
{
// Retrieve the twitter access token and claim
var accessTokenClaim = claims.FirstOrDefault(x => x.Type == "urn:twitter:accesstoken");
var accessTokenSecretClaim = claims.FirstOrDefault(x => x.Type == "urn:twitter:accesstokensecret");
if (accessTokenClaim != null && accessTokenSecretClaim != null)
{
var service = new TweetSharp.TwitterService("ztVUp8CwG0jyYZZoDKGXg", "jyFWNjzApKtogHMnRVvdvBqWJF2gPHNldjvopHZSoE", accessTokenClaim.Value, accessTokenSecretClaim.Value);
var profile = service.GetUserProfile(new TweetSharp.GetUserProfileOptions());
if (profile != null && !String.IsNullOrWhiteSpace(profile.ProfileImageUrl))
{
var user = db.Users.Find(userId);
user.ImageUrl = profile.ProfileImageUrl.Replace("_normal", "_bigger");
db.Entry(user).State = System.Data.Entity.EntityState.Modified;
await db.SaveChangesAsync();
}
}
}
private async Task OnExternalLoginAuth(User user)
{
var externalIdentity = await HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
if (externalIdentity != null)
{
foreach (var item in externalIdentity.Claims)
{
if (item.Type == ClaimTypes.NameIdentifier)
continue;
await UserManager.RemoveClaimAsync(user.Id, item);
await UserManager.AddClaimAsync(user.Id, item);
}
await SetTwitterProfileImage(user.Id, externalIdentity.Claims);
}
}
}
} | 35.636519 | 185 | 0.516449 | [
"MIT"
] | ellern/champs-room | src/Controllers/AccountController.cs | 20,885 | C# |
using System.Collections.Generic;
namespace Dblp.Domain.Interfaces.Entities
{
public class Conference
{
public Conference()
{
}
public Conference(string conferenceTitle, string key)
{
ConferenceTitle = conferenceTitle;
Key = key;
Events = new List<ConferenceEvent>();
}
public string Key { get; set; }
public string Abbr { get; set; }
public string ConferenceTitle { get; set; }
public List<ConferenceEvent> Events { get; set; }
public override string ToString()
{
return ConferenceTitle + "; Events: " + Events.Count;
}
}
} | 24.344828 | 65 | 0.555241 | [
"MIT"
] | Nexusger/GetTheBibTeX2 | Dblp.Domain.Interfaces/Entities/Conference.cs | 708 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.Spark.Interop.Ipc;
namespace Microsoft.Spark.Sql
{
/// <summary>
/// Provides statistic functions for <see cref="DataFrame"/>.
/// </summary>
public sealed class DataFrameStatFunctions : IJvmObjectReferenceProvider
{
private readonly JvmObjectReference _jvmObject;
internal DataFrameStatFunctions(JvmObjectReference jvmObject)
{
_jvmObject = jvmObject;
}
JvmObjectReference IJvmObjectReferenceProvider.Reference => _jvmObject;
/// <summary>
/// Calculates the approximate quantiles of a numerical column of a DataFrame.
/// </summary>
/// <remarks>
/// This method implements a variation of the Greenwald-Khanna algorithm
/// (with some speed optimizations).
/// </remarks>
/// <param name="columnName">Column name</param>
/// <param name="probabilities">A list of quantile probabilities</param>
/// <param name="relativeError">
/// The relative target precision to achieve (greater than or equal to 0)
/// </param>
/// <returns>The approximate quantiles at the given probabilities</returns>
public double[] ApproxQuantile(
string columnName,
IEnumerable<double> probabilities,
double relativeError) =>
(double[])_jvmObject.Invoke(
"approxQuantile", columnName, probabilities, relativeError);
/// <summary>
/// Calculate the sample covariance of two numerical columns of a DataFrame.
/// </summary>
/// <param name="colName1">First column name</param>
/// <param name="colName2">Second column name</param>
/// <returns>The covariance of the two columns</returns>
public double Cov(string colName1, string colName2) =>
(double)_jvmObject.Invoke("cov", colName1, colName2);
/// <summary>
/// Calculates the correlation of two columns of a DataFrame.
/// </summary>
/// <remarks>
/// Currently only the Pearson Correlation Coefficient is supported.
/// </remarks>
/// <param name="colName1">First column name</param>
/// <param name="colName2">Second column name</param>
/// <param name="method">Method name for calculating correlation</param>
/// <returns>The Pearson Correlation Coefficient</returns>
public double Corr(string colName1, string colName2, string method) =>
(double)_jvmObject.Invoke("corr", colName1, colName2, method);
/// <summary>
/// Calculates the Pearson Correlation Coefficient of two columns of a DataFrame.
/// </summary>
/// <param name="colName1">First column name</param>
/// <param name="colName2">Second column name</param>
/// <returns>The Pearson Correlation Coefficient</returns>
public double Corr(string colName1, string colName2) =>
(double)_jvmObject.Invoke("corr", colName1, colName2);
/// <summary>
/// Computes a pair-wise frequency table of the given columns, also known as
/// a contingency table.
/// </summary>
/// <param name="colName1">First column name</param>
/// <param name="colName2">Second column name</param>
/// <returns>DataFrame object</returns>
public DataFrame Crosstab(string colName1, string colName2) =>
WrapAsDataFrame(_jvmObject.Invoke("crosstab", colName1, colName2));
/// <summary>
/// Finding frequent items for columns, possibly with false positives.
/// </summary>
/// <param name="columnNames">Column names</param>
/// <param name="support">
/// The minimum frequency for an item to be considered frequent.
/// Should be greater than 1e-4.
/// </param>
/// <returns>DataFrame object</returns>
public DataFrame FreqItems(IEnumerable<string> columnNames, double support) =>
WrapAsDataFrame(_jvmObject.Invoke("freqItems", columnNames, support));
/// <summary>
/// Finding frequent items for columns, possibly with false positives with
/// a default support of 1%.
/// </summary>
/// <param name="columnNames">Column names</param>
/// <returns>DataFrame object</returns>
public DataFrame FreqItems(IEnumerable<string> columnNames) =>
WrapAsDataFrame(_jvmObject.Invoke("freqItems", columnNames));
/// <summary>
/// Returns a stratified sample without replacement based on the fraction given
/// on each stratum.
/// </summary>
/// <typeparam name="T">Stratum type</typeparam>
/// <param name="columnName">Column name that defines strata</param>
/// <param name="fractions">
/// Sampling fraction for each stratum. If a stratum is not specified, we treat
/// its fraction as zero.
/// </param>
/// <param name="seed">Random seed</param>
/// <returns>DataFrame object</returns>
public DataFrame SampleBy<T>(
string columnName,
IDictionary<T, double> fractions,
long seed) =>
WrapAsDataFrame(_jvmObject.Invoke("sampleBy", columnName, fractions, seed));
/// <summary>
/// Returns a stratified sample without replacement based on the fraction given
/// on each stratum.
/// </summary>
/// <typeparam name="T">Stratum type</typeparam>
/// <param name="column">Column that defines strata</param>
/// <param name="fractions">
/// Sampling fraction for each stratum. If a stratum is not specified, we treat
/// its fraction as zero.
/// </param>
/// <param name="seed">Random seed</param>
/// <returns>DataFrame object</returns>
[Since(Versions.V3_0_0)]
public DataFrame SampleBy<T>(Column column, IDictionary<T, double> fractions, long seed) =>
WrapAsDataFrame(_jvmObject.Invoke("sampleBy", column, fractions, seed));
private DataFrame WrapAsDataFrame(object obj) => new DataFrame((JvmObjectReference)obj);
}
}
| 45.041958 | 99 | 0.624903 | [
"MIT"
] | Ibasa/spark | src/csharp/Microsoft.Spark/Sql/DataFrameStatFunctions.cs | 6,441 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace System.Linq
{
public static partial class AsyncEnumerable
{
public static ValueTask<int> CountAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
{
if (source == null)
throw Error.ArgumentNull(nameof(source));
return source switch
{
ICollection<TSource> collection => new ValueTask<int>(collection.Count),
IAsyncIListProvider<TSource> listProv => listProv.GetCountAsync(onlyIfCheap: false, cancellationToken),
ICollection collection => new ValueTask<int>(collection.Count),
_ => Core(source, cancellationToken),
};
static async ValueTask<int> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
{
var count = 0;
await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
checked
{
count++;
}
}
return count;
}
}
public static ValueTask<int> CountAsync<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken = default)
{
if (source == null)
throw Error.ArgumentNull(nameof(source));
if (predicate == null)
throw Error.ArgumentNull(nameof(predicate));
return Core(source, predicate, cancellationToken);
static async ValueTask<int> Core(IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
{
var count = 0;
await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
if (predicate(item))
{
checked
{
count++;
}
}
}
return count;
}
}
internal static ValueTask<int> CountAwaitAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
{
if (source == null)
throw Error.ArgumentNull(nameof(source));
if (predicate == null)
throw Error.ArgumentNull(nameof(predicate));
return Core(source, predicate, cancellationToken);
static async ValueTask<int> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<bool>> predicate, CancellationToken cancellationToken)
{
var count = 0;
await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
if (await predicate(item).ConfigureAwait(false))
{
checked
{
count++;
}
}
}
return count;
}
}
#if !NO_DEEP_CANCELLATION
internal static ValueTask<int> CountAwaitWithCancellationAsyncCore<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken = default)
{
if (source == null)
throw Error.ArgumentNull(nameof(source));
if (predicate == null)
throw Error.ArgumentNull(nameof(predicate));
return Core(source, predicate, cancellationToken);
static async ValueTask<int> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<bool>> predicate, CancellationToken cancellationToken)
{
var count = 0;
await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
if (await predicate(item, cancellationToken).ConfigureAwait(false))
{
checked
{
count++;
}
}
}
return count;
}
}
#endif
}
}
| 37.415385 | 230 | 0.55037 | [
"Apache-2.0"
] | bartholinie/reactive | Ix.NET/Source/System.Linq.Async/System/Linq/Operators/Count.cs | 4,866 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.