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 UnityEditor.IMGUI.Controls;
using UnityEditor.ShortcutManagement;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Rendering.Universal;
using static UnityEditorInternal.EditMode;
namespace UnityEditor.Rendering.Universal
{
[CustomEditor(typeof(DecalProjector))]
[CanEditMultipleObjects]
partial class DecalProjectorEditor : Editor
{
const float k_Limit = 100000f;
const float k_LimitInv = 1f / k_Limit;
static Color fullColor
{
get
{
Color c = s_LastColor;
c.a = 1f;
return c;
}
}
static Color s_LastColor;
static void UpdateColorsInHandlesIfRequired()
{
Color c = new Color(1f, 1f, 1f, 0.2f);
if (c != s_LastColor)
{
if (s_BoxHandle != null && !s_BoxHandle.Equals(null))
s_BoxHandle = null;
if (s_uvHandles != null && !s_uvHandles.Equals(null))
s_uvHandles.baseColor = c;
s_LastColor = c;
}
}
MaterialEditor m_MaterialEditor = null;
SerializedProperty m_MaterialProperty;
SerializedProperty m_DrawDistanceProperty;
SerializedProperty m_FadeScaleProperty;
SerializedProperty m_StartAngleFadeProperty;
SerializedProperty m_EndAngleFadeProperty;
SerializedProperty m_UVScaleProperty;
SerializedProperty m_UVBiasProperty;
SerializedProperty m_ScaleMode;
SerializedProperty m_Size;
SerializedProperty[] m_SizeValues;
SerializedProperty m_Offset;
SerializedProperty[] m_OffsetValues;
SerializedProperty m_FadeFactor;
int layerMask => (target as Component).gameObject.layer;
bool layerMaskHasMultipleValues
{
get
{
if (targets.Length < 2)
return false;
int layerMask = (targets[0] as Component).gameObject.layer;
for (int index = 1; index < targets.Length; ++index)
{
if ((targets[index] as Component).gameObject.layer != layerMask)
return true;
}
return false;
}
}
static HierarchicalBox s_BoxHandle;
static HierarchicalBox boxHandle
{
get
{
if (s_BoxHandle == null || s_BoxHandle.Equals(null))
{
Color c = fullColor;
s_BoxHandle = new HierarchicalBox(s_LastColor, new[] { c, c, c, c, c, c });
s_BoxHandle.SetBaseColor(s_LastColor);
s_BoxHandle.monoHandle = false;
}
return s_BoxHandle;
}
}
static DisplacableRectHandles s_uvHandles;
static DisplacableRectHandles uvHandles
{
get
{
if (s_uvHandles == null || s_uvHandles.Equals(null))
s_uvHandles = new DisplacableRectHandles(s_LastColor);
return s_uvHandles;
}
}
static readonly BoxBoundsHandle s_AreaLightHandle =
new BoxBoundsHandle { axes = PrimitiveBoundsHandle.Axes.X | PrimitiveBoundsHandle.Axes.Y };
const SceneViewEditMode k_EditShapeWithoutPreservingUV = (SceneViewEditMode)90;
const SceneViewEditMode k_EditShapePreservingUV = (SceneViewEditMode)91;
const SceneViewEditMode k_EditUVAndPivot = (SceneViewEditMode)92;
static readonly SceneViewEditMode[] k_EditVolumeModes = new SceneViewEditMode[]
{
k_EditShapeWithoutPreservingUV,
k_EditShapePreservingUV,
k_EditUVAndPivot,
};
static Func<Vector3, Quaternion, Vector3> s_DrawPivotHandle;
static GUIContent[] k_EditVolumeLabels = null;
static GUIContent[] editVolumeLabels => k_EditVolumeLabels ?? (k_EditVolumeLabels = new GUIContent[]
{
EditorGUIUtility.TrIconContent("d_ScaleTool", k_EditShapeWithoutPreservingUVTooltip),
EditorGUIUtility.TrIconContent("d_RectTool", k_EditShapePreservingUVTooltip),
EditorGUIUtility.TrIconContent("d_MoveTool", k_EditUVTooltip),
});
static List<DecalProjectorEditor> s_Instances = new List<DecalProjectorEditor>();
static DecalProjectorEditor FindEditorFromSelection()
{
GameObject[] selection = Selection.gameObjects;
DecalProjector[] selectionTargets = Selection.GetFiltered<DecalProjector>(SelectionMode.Unfiltered);
foreach (DecalProjectorEditor editor in s_Instances)
{
if (selectionTargets.Length != editor.targets.Length)
continue;
bool allOk = true;
foreach (DecalProjector selectionTarget in selectionTargets)
{
if (!Array.Find(editor.targets, t => t == selectionTarget))
{
allOk = false;
break;
}
}
if (!allOk)
continue;
return editor;
}
return null;
}
private void OnEnable()
{
s_Instances.Add(this);
// Create an instance of the MaterialEditor
UpdateMaterialEditor();
// Fetch serialized properties
m_MaterialProperty = serializedObject.FindProperty("m_Material");
m_DrawDistanceProperty = serializedObject.FindProperty("m_DrawDistance");
m_FadeScaleProperty = serializedObject.FindProperty("m_FadeScale");
m_StartAngleFadeProperty = serializedObject.FindProperty("m_StartAngleFade");
m_EndAngleFadeProperty = serializedObject.FindProperty("m_EndAngleFade");
m_UVScaleProperty = serializedObject.FindProperty("m_UVScale");
m_UVBiasProperty = serializedObject.FindProperty("m_UVBias");
m_ScaleMode = serializedObject.FindProperty("m_ScaleMode");
m_Size = serializedObject.FindProperty("m_Size");
m_SizeValues = new[]
{
m_Size.FindPropertyRelative("x"),
m_Size.FindPropertyRelative("y"),
m_Size.FindPropertyRelative("z"),
};
m_Offset = serializedObject.FindProperty("m_Offset");
m_OffsetValues = new[]
{
m_Offset.FindPropertyRelative("x"),
m_Offset.FindPropertyRelative("y"),
m_Offset.FindPropertyRelative("z"),
};
m_FadeFactor = serializedObject.FindProperty("m_FadeFactor");
ReinitSavedRatioSizePivotPosition();
}
private void OnDisable()
{
s_Instances.Remove(this);
}
private void OnDestroy() =>
DestroyImmediate(m_MaterialEditor);
public bool HasFrameBounds()
{
return true;
}
public Bounds OnGetFrameBounds()
{
DecalProjector decalProjector = target as DecalProjector;
return new Bounds(decalProjector.transform.position, boxHandle.size);
}
public void UpdateMaterialEditor()
{
int validMaterialsCount = 0;
for (int index = 0; index < targets.Length; ++index)
{
DecalProjector decalProjector = (targets[index] as DecalProjector);
if ((decalProjector != null) && (decalProjector.material != null))
validMaterialsCount++;
}
// Update material editor with the new material
UnityEngine.Object[] materials = new UnityEngine.Object[validMaterialsCount];
validMaterialsCount = 0;
for (int index = 0; index < targets.Length; ++index)
{
DecalProjector decalProjector = (targets[index] as DecalProjector);
if ((decalProjector != null) && (decalProjector.material != null))
materials[validMaterialsCount++] = (targets[index] as DecalProjector).material;
}
m_MaterialEditor = (MaterialEditor)CreateEditor(materials);
}
void OnSceneGUI()
{
//called on each targets
DrawHandles();
}
void DrawBoxTransformationHandles(DecalProjector decalProjector)
{
Vector3 scale = decalProjector.effectiveScale;
using (new Handles.DrawingScope(fullColor, Matrix4x4.TRS(decalProjector.transform.position, decalProjector.transform.rotation, scale)))
{
Vector3 centerStart = decalProjector.pivot;
boxHandle.center = centerStart;
boxHandle.size = decalProjector.size;
Vector3 boundsSizePreviousOS = boxHandle.size;
Vector3 boundsMinPreviousOS = boxHandle.size * -0.5f + boxHandle.center;
EditorGUI.BeginChangeCheck();
boxHandle.DrawHandle();
if (EditorGUI.EndChangeCheck())
{
// Adjust decal transform if handle changed.
Undo.RecordObject(decalProjector, "Decal Projector Change");
bool xChangeIsValid = scale.x != 0f;
bool yChangeIsValid = scale.y != 0f;
bool zChangeIsValid = scale.z != 0f;
// Preserve serialized state for axes with scale 0.
decalProjector.size = new Vector3(
xChangeIsValid ? boxHandle.size.x : decalProjector.size.x,
yChangeIsValid ? boxHandle.size.y : decalProjector.size.y,
zChangeIsValid ? boxHandle.size.z : decalProjector.size.z);
decalProjector.pivot = new Vector3(
xChangeIsValid ? boxHandle.center.x : decalProjector.pivot.x,
yChangeIsValid ? boxHandle.center.y : decalProjector.pivot.y,
zChangeIsValid ? boxHandle.center.z : decalProjector.pivot.z);
Vector3 boundsSizeCurrentOS = boxHandle.size;
Vector3 boundsMinCurrentOS = boxHandle.size * -0.5f + boxHandle.center;
if (editMode == k_EditShapePreservingUV)
{
// Treat decal projector bounds as a crop tool, rather than a scale tool.
// Compute a new uv scale and bias terms to pin decal projection pixels in world space, irrespective of projector bounds.
// Preserve serialized state for axes with scale 0.
Vector2 uvScale = decalProjector.uvScale;
Vector2 uvBias = decalProjector.uvBias;
if (xChangeIsValid)
{
uvScale.x *= Mathf.Max(k_LimitInv, boundsSizeCurrentOS.x) / Mathf.Max(k_LimitInv, boundsSizePreviousOS.x);
uvBias.x += (boundsMinCurrentOS.x - boundsMinPreviousOS.x) / Mathf.Max(k_LimitInv, boundsSizeCurrentOS.x) * uvScale.x;
}
if (yChangeIsValid)
{
uvScale.y *= Mathf.Max(k_LimitInv, boundsSizeCurrentOS.y) / Mathf.Max(k_LimitInv, boundsSizePreviousOS.y);
uvBias.y += (boundsMinCurrentOS.y - boundsMinPreviousOS.y) / Mathf.Max(k_LimitInv, boundsSizeCurrentOS.y) * uvScale.y;
}
decalProjector.uvScale = uvScale;
decalProjector.uvBias = uvBias;
}
if (PrefabUtility.IsPartOfNonAssetPrefabInstance(decalProjector))
{
PrefabUtility.RecordPrefabInstancePropertyModifications(decalProjector);
}
}
}
}
void DrawPivotHandles(DecalProjector decalProjector)
{
Vector3 scale = decalProjector.effectiveScale;
Vector3 scaledPivot = Vector3.Scale(decalProjector.pivot, scale);
Vector3 scaledSize = Vector3.Scale(decalProjector.size, scale);
using (new Handles.DrawingScope(fullColor, Matrix4x4.TRS(Vector3.zero, decalProjector.transform.rotation, Vector3.one)))
{
EditorGUI.BeginChangeCheck();
Vector3 newPosition = ProjectedTransform.DrawHandles(decalProjector.transform.position, .5f * scaledSize.z - scaledPivot.z, decalProjector.transform.rotation);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObjects(new UnityEngine.Object[] { decalProjector, decalProjector.transform }, "Decal Projector Change");
scaledPivot += Quaternion.Inverse(decalProjector.transform.rotation) * (decalProjector.transform.position - newPosition);
decalProjector.pivot = new Vector3(
scale.x != 0f ? scaledPivot.x / scale.x : decalProjector.pivot.x,
scale.y != 0f ? scaledPivot.y / scale.y : decalProjector.pivot.y,
scale.z != 0f ? scaledPivot.z / scale.z : decalProjector.pivot.z);
decalProjector.transform.position = newPosition;
ReinitSavedRatioSizePivotPosition();
}
}
}
void DrawUVHandles(DecalProjector decalProjector)
{
Vector3 scale = decalProjector.effectiveScale;
Vector3 scaledPivot = Vector3.Scale(decalProjector.pivot, scale);
Vector3 scaledSize = Vector3.Scale(decalProjector.size, scale);
using (new Handles.DrawingScope(Matrix4x4.TRS(decalProjector.transform.position + decalProjector.transform.rotation * (scaledPivot - .5f * scaledSize), decalProjector.transform.rotation, scale)))
{
Vector2 uvScale = decalProjector.uvScale;
Vector2 uvBias = decalProjector.uvBias;
Vector2 uvSize = new Vector2(
(uvScale.x > k_Limit || uvScale.x < -k_Limit) ? 0f : decalProjector.size.x / uvScale.x,
(uvScale.y > k_Limit || uvScale.y < -k_Limit) ? 0f : decalProjector.size.y / uvScale.y
);
Vector2 uvCenter = uvSize * .5f - new Vector2(uvBias.x * uvSize.x, uvBias.y * uvSize.y);
uvHandles.center = uvCenter;
uvHandles.size = uvSize;
EditorGUI.BeginChangeCheck();
uvHandles.DrawHandle();
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(decalProjector, "Decal Projector Change");
for (int channel = 0; channel < 2; channel++)
{
// Preserve serialized state for axes with the scaled size 0.
if (scaledSize[channel] != 0f)
{
float handleSize = uvHandles.size[channel];
float minusNewUVStart = .5f * handleSize - uvHandles.center[channel];
float decalSize = decalProjector.size[channel];
float limit = k_LimitInv * decalSize;
if (handleSize > limit || handleSize < -limit)
{
uvScale[channel] = decalSize / handleSize;
uvBias[channel] = minusNewUVStart / handleSize;
}
else
{
// TODO: Decide if uvHandles.size should ever have negative value. It can't currently.
uvScale[channel] = k_Limit * Mathf.Sign(handleSize);
uvBias[channel] = k_Limit * minusNewUVStart / decalSize;
}
}
}
decalProjector.uvScale = uvScale;
decalProjector.uvBias = uvBias;
}
}
}
void DrawHandles()
{
DecalProjector decalProjector = target as DecalProjector;
if (editMode == k_EditShapePreservingUV || editMode == k_EditShapeWithoutPreservingUV)
DrawBoxTransformationHandles(decalProjector);
else if (editMode == k_EditUVAndPivot)
{
DrawPivotHandles(decalProjector);
DrawUVHandles(decalProjector);
}
}
[DrawGizmo(GizmoType.Selected | GizmoType.Active)]
static void DrawGizmosSelected(DecalProjector decalProjector, GizmoType gizmoType)
{
UpdateColorsInHandlesIfRequired();
const float k_DotLength = 5f;
// Draw them with scale applied to size and pivot instead of the matrix to keep the proportions of the arrow and lines.
using (new Handles.DrawingScope(fullColor, Matrix4x4.TRS(decalProjector.transform.position, decalProjector.transform.rotation, Vector3.one)))
{
Vector3 scale = decalProjector.effectiveScale;
Vector3 scaledPivot = Vector3.Scale(decalProjector.pivot, scale);
Vector3 scaledSize = Vector3.Scale(decalProjector.size, scale);
boxHandle.center = scaledPivot;
boxHandle.size = scaledSize;
bool isVolumeEditMode = editMode == k_EditShapePreservingUV || editMode == k_EditShapeWithoutPreservingUV;
bool isPivotEditMode = editMode == k_EditUVAndPivot;
boxHandle.DrawHull(isVolumeEditMode);
Vector3 pivot = Vector3.zero;
Vector3 projectedPivot = new Vector3(0, 0, scaledPivot.z - .5f * scaledSize.z);
if (isPivotEditMode)
{
Handles.DrawDottedLines(new[] { projectedPivot, pivot }, k_DotLength);
}
else
{
float arrowSize = scaledSize.z * 0.25f;
Handles.ArrowHandleCap(0, projectedPivot, Quaternion.identity, arrowSize, EventType.Repaint);
}
//draw UV and bolder edges
using (new Handles.DrawingScope(Matrix4x4.TRS(decalProjector.transform.position + decalProjector.transform.rotation * new Vector3(scaledPivot.x, scaledPivot.y, scaledPivot.z - .5f * scaledSize.z), decalProjector.transform.rotation, Vector3.one)))
{
Vector2 UVSize = new Vector2(
(decalProjector.uvScale.x > k_Limit || decalProjector.uvScale.x < -k_Limit) ? 0f : scaledSize.x / decalProjector.uvScale.x,
(decalProjector.uvScale.y > k_Limit || decalProjector.uvScale.y < -k_Limit) ? 0f : scaledSize.y / decalProjector.uvScale.y
);
Vector2 UVCenter = UVSize * .5f - new Vector2(decalProjector.uvBias.x * UVSize.x, decalProjector.uvBias.y * UVSize.y) - (Vector2)scaledSize * .5f;
uvHandles.center = UVCenter;
uvHandles.size = UVSize;
uvHandles.DrawRect(dottedLine: true, screenSpaceSize: k_DotLength);
uvHandles.center = default;
uvHandles.size = scaledSize;
uvHandles.DrawRect(dottedLine: false, thickness: 3f);
}
}
}
static Func<Bounds> GetBoundsGetter(DecalProjector decalProjector)
{
return () =>
{
var bounds = new Bounds();
var decalTransform = decalProjector.transform;
bounds.Encapsulate(decalTransform.position);
return bounds;
};
}
// Temporarily save ratio between size and pivot position while editing in inspector.
// null or NaN is used to say that there is no saved ratio.
// Aim is to keep proportion while sliding the value to 0 in Inspector and then go back to something else.
// Current solution only works for the life of this editor, but is enough in most cases.
// Which means if you go to there, selection something else and go back on it, pivot position is thus null.
Dictionary<DecalProjector, Vector3> ratioSizePivotPositionSaved = null;
void ReinitSavedRatioSizePivotPosition()
{
ratioSizePivotPositionSaved = null;
}
void UpdateSize(int axe, float newSize)
{
void UpdateSizeOfOneTarget(DecalProjector currentTarget)
{
//lazy init on demand as targets array cannot be accessed from OnSceneGUI so in edit mode.
if (ratioSizePivotPositionSaved == null)
{
ratioSizePivotPositionSaved = new Dictionary<DecalProjector, Vector3>();
foreach (DecalProjector projector in targets)
ratioSizePivotPositionSaved[projector] = new Vector3(float.NaN, float.NaN, float.NaN);
}
// Save old ratio if not registered
// Either or are NaN or no one, check only first
Vector3 saved = ratioSizePivotPositionSaved[currentTarget];
if (float.IsNaN(saved[axe]))
{
float oldSize = currentTarget.m_Size[axe];
saved[axe] = Mathf.Abs(oldSize) <= Mathf.Epsilon ? 0f : currentTarget.m_Offset[axe] / oldSize;
ratioSizePivotPositionSaved[currentTarget] = saved;
}
currentTarget.m_Size[axe] = newSize;
currentTarget.m_Offset[axe] = saved[axe] * newSize;
// refresh DecalProjector to update projection
currentTarget.OnValidate();
}
// Manually register Undo as we work directly on the target
Undo.RecordObjects(targets, "Change DecalProjector Size or Depth");
// Apply any change on target first
serializedObject.ApplyModifiedProperties();
// update each target
foreach (DecalProjector decalProjector in targets)
UpdateSizeOfOneTarget(decalProjector);
// update again serialize object to register change in targets
serializedObject.Update();
// change was not tracked by SerializeReference so force repaint the scene views and game views
UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
// strange: we need to force it throu serialization to update multiple differente value state (value are right but still detected as different)
if (m_SizeValues[axe].hasMultipleDifferentValues)
m_SizeValues[axe].floatValue = newSize;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
bool materialChanged = false;
bool isDefaultMaterial = false;
bool isValidDecalMaterial = true;
bool isDecalSupported = DecalProjector.isSupported;
if (!isDecalSupported)
{
EditorGUILayout.HelpBox("No renderer has a Decal Renderer Feature added.", MessageType.Warning);
}
EditorGUI.BeginChangeCheck();
{
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
DoInspectorToolbar(k_EditVolumeModes, editVolumeLabels, GetBoundsGetter(target as DecalProjector), this);
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
// Info box for tools
GUIStyle style = new GUIStyle(EditorStyles.miniLabel);
style.richText = true;
GUILayout.BeginVertical(EditorStyles.helpBox);
string helpText = k_BaseSceneEditingToolText;
if (EditMode.editMode == k_EditShapeWithoutPreservingUV && EditMode.IsOwner(this))
helpText = k_EditShapeWithoutPreservingUVName;
if (EditMode.editMode == k_EditShapePreservingUV && EditMode.IsOwner(this))
helpText = k_EditShapePreservingUVName;
if (EditMode.editMode == k_EditUVAndPivot && EditMode.IsOwner(this))
helpText = k_EditUVAndPivotName;
GUILayout.Label(helpText, style);
GUILayout.EndVertical();
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_ScaleMode, k_ScaleMode);
bool negativeScale = false;
foreach (var target in targets)
{
var decalProjector = target as DecalProjector;
float combinedScale = decalProjector.transform.lossyScale.x * decalProjector.transform.lossyScale.y * decalProjector.transform.lossyScale.z;
negativeScale |= combinedScale < 0 && decalProjector.scaleMode == DecalScaleMode.InheritFromHierarchy;
}
if (negativeScale)
{
EditorGUILayout.HelpBox("Does not work with negative odd scaling (When there are odd number of scale components)", MessageType.Warning);
}
var widthRect = EditorGUILayout.GetControlRect();
EditorGUI.BeginProperty(widthRect, k_WidthContent, m_SizeValues[0]);
EditorGUI.BeginChangeCheck();
float newSizeX = EditorGUI.FloatField(widthRect, k_WidthContent, m_SizeValues[0].floatValue);
if (EditorGUI.EndChangeCheck())
UpdateSize(0, Mathf.Max(0, newSizeX));
EditorGUI.EndProperty();
var heightRect = EditorGUILayout.GetControlRect();
EditorGUI.BeginProperty(heightRect, k_HeightContent, m_SizeValues[1]);
EditorGUI.BeginChangeCheck();
float newSizeY = EditorGUI.FloatField(heightRect, k_HeightContent, m_SizeValues[1].floatValue);
if (EditorGUI.EndChangeCheck())
UpdateSize(1, Mathf.Max(0, newSizeY));
EditorGUI.EndProperty();
var projectionRect = EditorGUILayout.GetControlRect();
EditorGUI.BeginProperty(projectionRect, k_ProjectionDepthContent, m_SizeValues[2]);
EditorGUI.BeginChangeCheck();
float newSizeZ = EditorGUI.FloatField(projectionRect, k_ProjectionDepthContent, m_SizeValues[2].floatValue);
if (EditorGUI.EndChangeCheck())
UpdateSize(2, Mathf.Max(0, newSizeZ));
EditorGUI.EndProperty();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_Offset, k_Offset);
if (EditorGUI.EndChangeCheck())
ReinitSavedRatioSizePivotPosition();
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_MaterialProperty, k_MaterialContent);
materialChanged = EditorGUI.EndChangeCheck();
foreach (var target in targets)
{
var decalProjector = target as DecalProjector;
var mat = decalProjector.material;
isDefaultMaterial |= decalProjector.material == DecalProjector.defaultMaterial;
isValidDecalMaterial &= decalProjector.IsValid();
}
if (m_MaterialEditor && !isValidDecalMaterial)
{
CoreEditorUtils.DrawFixMeBox("Decal only work with Decal Material. Use default material or create from decal shader graph sub target.", () =>
{
m_MaterialProperty.objectReferenceValue = DecalProjector.defaultMaterial;
materialChanged = true;
});
}
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_UVScaleProperty, k_UVScaleContent);
EditorGUILayout.PropertyField(m_UVBiasProperty, k_UVBiasContent);
EditorGUILayout.PropertyField(m_FadeFactor, k_OpacityContent);
EditorGUI.indentLevel--;
bool angleFadeSupport = false;
foreach (var decalProjector in targets)
{
var mat = (decalProjector as DecalProjector).material;
if (mat == null)
continue;
angleFadeSupport = mat.HasProperty("_DecalAngleFadeSupported");
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_DrawDistanceProperty, k_DistanceContent);
if (EditorGUI.EndChangeCheck() && m_DrawDistanceProperty.floatValue < 0f)
m_DrawDistanceProperty.floatValue = 0f;
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_FadeScaleProperty, k_FadeScaleContent);
EditorGUI.indentLevel--;
using (new EditorGUI.DisabledScope(!angleFadeSupport))
{
float angleFadeMinValue = m_StartAngleFadeProperty.floatValue;
float angleFadeMaxValue = m_EndAngleFadeProperty.floatValue;
EditorGUI.BeginChangeCheck();
EditorGUILayout.MinMaxSlider(k_AngleFadeContent, ref angleFadeMinValue, ref angleFadeMaxValue, 0.0f, 180.0f);
if (EditorGUI.EndChangeCheck())
{
m_StartAngleFadeProperty.floatValue = angleFadeMinValue;
m_EndAngleFadeProperty.floatValue = angleFadeMaxValue;
}
}
if (!angleFadeSupport && isValidDecalMaterial)
{
EditorGUILayout.HelpBox($"Decal Angle Fade is not enabled in Shader. In ShaderGraph enable Angle Fade option.", MessageType.Info);
}
EditorGUILayout.Space();
}
if (EditorGUI.EndChangeCheck())
serializedObject.ApplyModifiedProperties();
if (materialChanged)
UpdateMaterialEditor();
if (layerMaskHasMultipleValues || layerMask != (target as Component).gameObject.layer)
{
foreach (var decalProjector in targets)
{
(decalProjector as DecalProjector).OnValidate();
}
}
if (m_MaterialEditor != null)
{
// We need to prevent the user to edit default decal materials
if (isValidDecalMaterial)
{
using (new DecalProjectorScope())
{
using (new EditorGUI.DisabledGroupScope(isDefaultMaterial))
{
// Draw the material's foldout and the material shader field
// Required to call m_MaterialEditor.OnInspectorGUI ();
m_MaterialEditor.DrawHeader();
// Draw the material properties
// Works only if the foldout of m_MaterialEditor.DrawHeader () is open
m_MaterialEditor.OnInspectorGUI();
}
}
}
}
}
[Shortcut("URP/Decal: Handle changing size stretching UV", typeof(SceneView), KeyCode.Keypad1, ShortcutModifiers.Action)]
static void EnterEditModeWithoutPreservingUV(ShortcutArguments args)
{
//If editor is not there, then the selected GameObject does not contains a DecalProjector
DecalProjector activeDecalProjector = Selection.activeGameObject?.GetComponent<DecalProjector>();
if (activeDecalProjector == null || activeDecalProjector.Equals(null))
return;
ChangeEditMode(k_EditShapeWithoutPreservingUV, GetBoundsGetter(activeDecalProjector)(), FindEditorFromSelection());
}
[Shortcut("URP/Decal: Handle changing size cropping UV", typeof(SceneView), KeyCode.Keypad2, ShortcutModifiers.Action)]
static void EnterEditModePreservingUV(ShortcutArguments args)
{
//If editor is not there, then the selected GameObject does not contains a DecalProjector
DecalProjector activeDecalProjector = Selection.activeGameObject?.GetComponent<DecalProjector>();
if (activeDecalProjector == null || activeDecalProjector.Equals(null))
return;
ChangeEditMode(k_EditShapePreservingUV, GetBoundsGetter(activeDecalProjector)(), FindEditorFromSelection());
}
[Shortcut("URP/Decal: Handle changing pivot position and UVs", typeof(SceneView), KeyCode.Keypad3, ShortcutModifiers.Action)]
static void EnterEditModePivotPreservingUV(ShortcutArguments args)
{
//If editor is not there, then the selected GameObject does not contains a DecalProjector
DecalProjector activeDecalProjector = Selection.activeGameObject?.GetComponent<DecalProjector>();
if (activeDecalProjector == null || activeDecalProjector.Equals(null))
return;
ChangeEditMode(k_EditUVAndPivot, GetBoundsGetter(activeDecalProjector)(), FindEditorFromSelection());
}
[Shortcut("URP/Decal: Handle swap between cropping and stretching UV", typeof(SceneView), KeyCode.Keypad4, ShortcutModifiers.Action)]
static void SwappingEditUVMode(ShortcutArguments args)
{
//If editor is not there, then the selected GameObject does not contains a DecalProjector
DecalProjector activeDecalProjector = Selection.activeGameObject?.GetComponent<DecalProjector>();
if (activeDecalProjector == null || activeDecalProjector.Equals(null))
return;
SceneViewEditMode targetMode = SceneViewEditMode.None;
switch (editMode)
{
case k_EditShapePreservingUV:
case k_EditUVAndPivot:
targetMode = k_EditShapeWithoutPreservingUV;
break;
case k_EditShapeWithoutPreservingUV:
targetMode = k_EditShapePreservingUV;
break;
}
if (targetMode != SceneViewEditMode.None)
ChangeEditMode(targetMode, GetBoundsGetter(activeDecalProjector)(), FindEditorFromSelection());
}
[Shortcut("URP/Decal: Stop Editing", typeof(SceneView), KeyCode.Keypad0, ShortcutModifiers.Action)]
static void ExitEditMode(ShortcutArguments args)
{
//If editor is not there, then the selected GameObject does not contains a DecalProjector
DecalProjector activeDecalProjector = Selection.activeGameObject?.GetComponent<DecalProjector>();
if (activeDecalProjector == null || activeDecalProjector.Equals(null))
return;
QuitEditMode();
}
}
}
| 46.054124 | 262 | 0.580586 | [
"MIT"
] | Liaoer/ToonShader | Packages/com.unity.render-pipelines.universal@12.1.3/Editor/Decal/DecalProjectorEditor.cs | 35,738 | C# |
namespace Yaskawa.Ext
{
public class Version : API.Version
{
public Version(int major, int minor, int patch, string release="", string build="")
{
Nmajor = (short)major;
Nminor = (short)minor;
Npatch = (short)patch;
if (!string.IsNullOrEmpty(release))
Release = release;
if (!string.IsNullOrEmpty(build))
Build = build;
}
public Version(API.Version v)
{
Nmajor = v.Nmajor;
Nminor = v.Nminor;
Npatch = v.Npatch;
if (!string.IsNullOrEmpty(v.Release))
Release = v.Release;
if (!string.IsNullOrEmpty(v.Build))
Build = v.Build;
}
public override string ToString()
{
return Nmajor.ToString()+"."+Nminor.ToString()+"."+Npatch.ToString()
+ (__isset.release ? "-"+Release : "")
+ (__isset.build ? "+"+Build : "");
}
}
}
| 28.027027 | 91 | 0.47541 | [
"Apache-2.0"
] | JurgenKuyper/SmartPendantSDK | csharp/Yaskawa/Ext/Version.cs | 1,037 | C# |
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace FrameworkContainers.Network
{
internal readonly struct HttpTimeoutResult : IDisposable
{
public bool IsComplete { get; }
public HttpResponseMessage Message { get; }
public bool IsTimeout { get; }
public bool IsFaulted { get; }
public HttpTimeoutResult(Task<HttpResponseMessage> task)
{
IsComplete = false;
Message = null;
IsTimeout = task.IsCanceled;
IsFaulted = task.IsFaulted;
if (!task.IsCanceled && !task.IsFaulted)
{
IsComplete = true;
Message = task.Result;
}
}
public async Task<string> TryGetBody()
{
if (Message?.Content == null) return String.Empty;
try { return await Message.Content.ReadAsStringAsync() ?? string.Empty; }
catch (Exception) { return string.Empty; }
}
public void Dispose() => Message?.Dispose();
}
}
| 27.973684 | 85 | 0.571966 | [
"MIT"
] | Matthew-Dove/FrameworkContainers | src/FrameworkContainers/Network/HttpTimeoutResult.cs | 1,065 | C# |
/*<FILE_LICENSE>
* Azos (A to Z Application Operating System) Framework
* The A to Z Foundation (a.k.a. Azist) licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
</FILE_LICENSE>*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Azos.CodeAnalysis.Source;
namespace Azos.CodeAnalysis.Laconfig
{
/// <summary>
/// Represents Laconic + Config = Laconfig terse configuration language
/// </summary>
public sealed class LaconfigLanguage : Language
{
public static readonly LaconfigLanguage Instance = new LaconfigLanguage();
private LaconfigLanguage() : base() {}
public override LanguageFamily Family
{
get { return LanguageFamily.StructuredConfig; }
}
public override IEnumerable<string> FileExtensions
{
get
{
yield return "lac";
yield return "lacon";
yield return "laconf";
yield return "laconfig";
yield return "rschema";
yield return "amb";
}
}
public override ILexer MakeLexer(IAnalysisContext context, SourceCodeRef srcRef, ISourceText source, MessageList messages = null, bool throwErrors = false)
{
return new LaconfigLexer(context, srcRef, source, messages, throwErrors);
}
}
}
| 27.38 | 159 | 0.674945 | [
"MIT"
] | chadfords/azos | src/Azos/CodeAnalysis/Laconfig/LaconfigLanguage.cs | 1,369 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace BriskChat.DataAccess.Migrations
{
public partial class UserDomain : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "UserDomains",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CreatedOn = table.Column<DateTime>(nullable: false),
DeletedOn = table.Column<DateTime>(nullable: true),
DomainId = table.Column<Guid>(nullable: false),
ModifiedOn = table.Column<DateTime>(nullable: false),
RoleId = table.Column<Guid>(nullable: false),
UserId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserDomains", x => x.Id);
table.ForeignKey(
name: "FK_UserDomains_Domains_DomainId",
column: x => x.DomainId,
principalTable: "Domains",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_UserDomains_Roles_RoleId",
column: x => x.RoleId,
principalTable: "Roles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_UserDomains_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_UserDomains_DomainId",
table: "UserDomains",
column: "DomainId");
migrationBuilder.CreateIndex(
name: "IX_UserDomains_RoleId",
table: "UserDomains",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_UserDomains_UserId",
table: "UserDomains",
column: "UserId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "UserDomains");
}
}
}
| 38.588235 | 73 | 0.488948 | [
"MIT"
] | Saibamen/BriskChat | BriskChat.DataAccess/Migrations/20170818084130_UserDomain.cs | 2,626 | C# |
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Palaso.BuildTasks.StampAssemblies
{
public class StampAssemblies : Task
{
public class VersionParts
{
public string[] parts = new string[4];
public override string ToString()
{
return string.Format("{0}.{1}.{2}.{3}", parts[0], parts[1], parts[2], parts[3]);
}
}
[Required]
public ITaskItem[] InputAssemblyPaths { get; set; }
[Required]
public string Version { get; set; }
public string FileVersion { get; set; }
public override bool Execute()
{
foreach (var inputAssemblyPath in InputAssemblyPaths)
{
var path = inputAssemblyPath.ItemSpec;
var contents = File.ReadAllText(path);
SafeLog("StampAssemblies: Stamping {0}", inputAssemblyPath);
//SafeLog("StampAssemblies: Contents: {0}",contents);
File.WriteAllText(path, GetModifiedContents(contents, Version, FileVersion));
}
return true;
}
public string GetModifiedContents(string contents, string incomingVersion, string incomingFileVersion)
{
var versionTemplateInFile = GetExistingAssemblyVersion(contents);
var fileVersionTemplateInFile = GetExistingAssemblyFileVersion(contents);
var versionTemplateInBuildScript = ParseVersionString(incomingVersion);
VersionParts fileVersionTemplateInScript = null;
fileVersionTemplateInScript = incomingFileVersion != null ? ParseVersionString(incomingFileVersion)
: versionTemplateInBuildScript;
var newVersion = MergeTemplates(versionTemplateInBuildScript, versionTemplateInFile);
var newFileVersion = MergeTemplates(fileVersionTemplateInScript, fileVersionTemplateInFile);
SafeLog("StampAssemblies: Merging existing {0} with incoming {1} to produce {2}.",
versionTemplateInFile.ToString(), incomingVersion, newVersion);
SafeLog("StampAssemblies: Merging existing {0} with incoming {1} to produce {2}.",
fileVersionTemplateInFile.ToString(), incomingFileVersion, newFileVersion);
var replacement = string.Format(
"[assembly: AssemblyVersion(\"{0}\")]",
newVersion);
contents = Regex.Replace(contents, @"\[assembly: AssemblyVersion\("".*""\)\]", replacement);
replacement = string.Format(
"[assembly: AssemblyFileVersion(\"{0}\")]",
newFileVersion);
contents = Regex.Replace(contents, @"\[assembly: AssemblyFileVersion\("".*""\)\]", replacement);
return contents;
}
private void SafeLog(string msg, params object[] args)
{
try
{
Debug.WriteLine(string.Format(msg,args));
Log.LogMessage(msg,args);
}
catch (Exception)
{
//swallow... logging fails in the unit test environment, where the log isn't really set up
}
}
public string MergeTemplates(VersionParts incoming, VersionParts existing)
{
string result = "";
for (int i = 0; i < 4; i++)
{
//SafeLog("StampAssemblies: incoming[{0}]={1}", i, incoming.parts[i]);
//SafeLog("StampAssemblies: existing[{0}]={1}", i, existing.parts[i]);
if(incoming.parts[i] != "*")
{
result += incoming.parts[i] + ".";
}
else
{
if(existing.parts[i] == "*")
{
//SafeLog("StampAssemblies: existing.parts[i] == '*'");
result += "0.";
}
else
{
result += existing.parts[i] + ".";
}
}
}
return result.TrimEnd(new char[] {'.'});
}
public VersionParts GetExistingAssemblyVersion(string contents)
{
try
{
var result = Regex.Match(contents, @"\[assembly\: AssemblyVersion\(""(.+)""");
return ParseVersionString(result.Groups[1].Value);
}
catch (Exception e)
{
Log.LogError("Could not parse the AssemblyVersion attribute, which should be something like 0.7.*.* or 1.0.0.0");
Log.LogErrorFromException(e);
throw e;
}
}
public VersionParts GetExistingAssemblyFileVersion(string contents)
{
try
{
var result = Regex.Match(contents, @"\[assembly\: AssemblyFileVersion\(""(.+)""");
return ParseVersionString(result.Groups[1].Value);
}
catch (Exception e)
{
Log.LogError("Could not parse the AssemblyVersion attribute, which should be something like 0.7.*.* or 1.0.0.0");
Log.LogErrorFromException(e);
throw e;
}
}
public VersionParts ParseVersionString(string contents)
{
var result = Regex.Match(contents, @"(.+)\.(.+)\.(.+)\.(.+)");
if(!result.Success)
{
//handle 1.0.* (I'm not good enough with regex to
//overcome greediness and get a single pattern to work for both situations).
result = Regex.Match(contents, @"(.+)\.(.+)\.(\*)");
}
if (!result.Success)
{
//handle 0.0.12
result = Regex.Match(contents, @"(.+)\.(.+)\.(.+)");
}
var v = new VersionParts();
v.parts[0] = result.Groups[1].Value;
v.parts[1] = result.Groups[2].Value;
v.parts[2] = result.Groups[3].Value;
v.parts[3] = result.Groups[4].Value;
for (int i = 0; i < 4; i++)
{
if(string.IsNullOrEmpty(v.parts[i]))
{
v.parts[i] = "*";
}
}
//can't propogate a hash code, though it's nice (for build server display purposes)
//to send it through to us. So for now, we just strip it out.
if(v.parts[3].IndexOfAny(new char[]{'a','b','c','d','e','f'}) >-1)
{
v.parts[3] = "0";
}
return v;
}
}
} | 29.569061 | 117 | 0.655643 | [
"MIT"
] | marksvc/libpalaso | Palaso.MSBuildTasks/StampAssemblies/StampAssemblies.cs | 5,352 | C# |
using System.Runtime.Serialization;
namespace GhostSharper.Models
{
[DataContract]
public class ContentPreview
{
[DataMember(Name = "name", EmitDefaultValue = false)]
public string Name { get; set; }
[DataMember(Name = "path", EmitDefaultValue = false)]
public string Path { get; set; }
[DataMember(Name = "itemInSet", EmitDefaultValue = false)]
public bool ItemInSet { get; set; }
[DataMember(Name = "setTag", EmitDefaultValue = false)]
public string SetTag { get; set; }
[DataMember(Name = "setNesting", EmitDefaultValue = false)]
public long SetNesting { get; set; }
[DataMember(Name = "useSetId", EmitDefaultValue = false)]
public long UseSetId { get; set; }
public override bool Equals(object input)
{
return this.Equals(input as ContentPreview);
}
public bool Equals(ContentPreview input)
{
if (input == null) return false;
return
(
Name == input.Name ||
(Name != null && Name.Equals(input.Name))
) &&
(
Path == input.Path ||
(Path != null && Path.Equals(input.Path))
) &&
(
ItemInSet == input.ItemInSet ||
(ItemInSet != null && ItemInSet.Equals(input.ItemInSet))
) &&
(
SetTag == input.SetTag ||
(SetTag != null && SetTag.Equals(input.SetTag))
) &&
(
SetNesting == input.SetNesting ||
(SetNesting.Equals(input.SetNesting))
) &&
(
UseSetId == input.UseSetId ||
(UseSetId.Equals(input.UseSetId))
) ;
}
}
}
| 30 | 76 | 0.473333 | [
"MIT",
"BSD-3-Clause"
] | joshhunt/GhostSharper | BungieNetApi/Models/ContentPreview.cs | 1,950 | C# |
using UnityEngine;
using Epitome;
using Epitome.LogSystem;
public class LogConfig : MonoSingleton<LogConfig>
{
private void Awake()
{
DontDestroyOnLoad();
// 启用日志
Log.EnableLog(true);
// 设置日志级别
Log.LogLevel(LogLevel.ALL);
// 设置日志输出
Log.LoadAppenders(AppenderType.MobileGUI);
Log.Trace("开启日志系统");
// 注册Unity日志的监听
Log.RegisterLogMessage();
Debug.Log("注册Unity日志的监听");
}
protected override void OnDestroy()
{
// 注销Unity日志的监听
Log.UnRegisterLogMessage();
base.OnDestroy();
}
} | 18.441176 | 50 | 0.574163 | [
"MIT"
] | yangjiqiu/Epitome | Assets/Epitome/Epitome.LogSystem/LogConfig.cs | 713 | C# |
// Copyright 2017 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Steeltoe.Management.Endpoint.Middleware;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Steeltoe.Management.Endpoint.ThreadDump
{
public class ThreadDumpEndpointMiddleware : EndpointMiddleware<List<ThreadInfo>>
{
private RequestDelegate _next;
public ThreadDumpEndpointMiddleware(RequestDelegate next, ThreadDumpEndpoint endpoint, IEnumerable<IManagementOptions> mgmtOptions, ILogger<ThreadDumpEndpointMiddleware> logger = null)
: base(endpoint, mgmtOptions, logger: logger)
{
_next = next;
}
[Obsolete]
public ThreadDumpEndpointMiddleware(RequestDelegate next, ThreadDumpEndpoint endpoint, ILogger<ThreadDumpEndpointMiddleware> logger = null)
: base(endpoint, logger: logger)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (RequestVerbAndPathMatch(context.Request.Method, context.Request.Path.Value))
{
await HandleThreadDumpRequestAsync(context);
}
else
{
await _next(context);
}
}
protected internal async Task HandleThreadDumpRequestAsync(HttpContext context)
{
var serialInfo = HandleRequest();
_logger?.LogDebug("Returning: {0}", serialInfo);
context.Response.Headers.Add("Content-Type", "application/vnd.spring-boot.actuator.v1+json");
await context.Response.WriteAsync(serialInfo);
}
}
}
| 36.596774 | 192 | 0.684002 | [
"ECL-2.0",
"Apache-2.0"
] | SteeltoeOSS/Management | src/Steeltoe.Management.EndpointCore/ThreadDump/ThreadDumpEndpointMiddleware.cs | 2,271 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class DiagnosticAnalyzerService
{
public class AnalysisData
{
public static readonly AnalysisData Empty = new AnalysisData(VersionStamp.Default, VersionStamp.Default, ImmutableArray<DiagnosticData>.Empty);
public readonly VersionStamp TextVersion;
public readonly VersionStamp DataVersion;
public readonly ImmutableArray<DiagnosticData> OldItems;
public readonly ImmutableArray<DiagnosticData> Items;
public AnalysisData(VersionStamp textVersion, VersionStamp dataVersion, ImmutableArray<DiagnosticData> items)
{
this.TextVersion = textVersion;
this.DataVersion = dataVersion;
this.Items = items;
}
public AnalysisData(VersionStamp textVersion, VersionStamp dataVersion, ImmutableArray<DiagnosticData> oldItems, ImmutableArray<DiagnosticData> newItems) :
this(textVersion, dataVersion, newItems)
{
this.OldItems = oldItems;
}
public AnalysisData ToPersistData()
{
return new AnalysisData(TextVersion, DataVersion, Items);
}
public bool FromCache
{
get { return this.OldItems.IsDefault; }
}
}
public struct SolutionArgument
{
public readonly Solution Solution;
public readonly ProjectId ProjectId;
public readonly DocumentId DocumentId;
public SolutionArgument(Solution solution, ProjectId projectId, DocumentId documentId)
{
this.Solution = solution;
this.ProjectId = projectId;
this.DocumentId = documentId;
}
public SolutionArgument(Document document) :
this(document.Project.Solution, document.Id.ProjectId, document.Id)
{ }
public SolutionArgument(Project project) :
this(project.Solution, project.Id, null)
{ }
}
public struct VersionArgument
{
public readonly VersionStamp TextVersion;
public readonly VersionStamp DataVersion;
public readonly VersionStamp ProjectVersion;
public VersionArgument(VersionStamp textVersion, VersionStamp dataVersion) :
this(textVersion, dataVersion, VersionStamp.Default)
{
}
public VersionArgument(VersionStamp textVersion, VersionStamp dataVersion, VersionStamp projectVersion)
{
this.TextVersion = textVersion;
this.DataVersion = dataVersion;
this.ProjectVersion = projectVersion;
}
}
public class ArgumentKey
{
public readonly int ProviderId;
public readonly StateType StateTypeId;
public readonly object Key;
public ArgumentKey(int providerId, StateType stateTypeId, object key)
{
this.ProviderId = providerId;
this.StateTypeId = stateTypeId;
this.Key = key;
}
public override bool Equals(object obj)
{
var other = obj as ArgumentKey;
if (other == null)
{
return false;
}
return ProviderId == other.ProviderId && StateTypeId == other.StateTypeId && Key == other.Key;
}
public override int GetHashCode()
{
return Hash.Combine(Key, Hash.Combine(ProviderId, (int)StateTypeId));
}
}
}
}
| 35.078261 | 167 | 0.58825 | [
"Apache-2.0"
] | DavidKarlas/roslyn | src/Features/Core/Diagnostics/DiagnosticAnalyzerService.NestedTypes.cs | 4,036 | C# |
namespace Okex.Net.V5.Enums
{
public enum OkexApiErrorCodes
{
Unknown = -1,
RequestTooFrequentHttpCode = 429,
SystemUpgrading = 503,
InvalidParams = 51000,
RequestTooFrequent = 50011,
InvalidAuthorization = 50114,
OrderOverPricing = 51116,
LowBalance = 51119,
OrderDoesNotExist = 51603,
SystemMaintenance = 50001,
RequestTimeout = 50004,
ApiOffline = 50005,
AccountBlocked = 50007,
AccountBlockedByLiquidation = 50009,
AccountStatusInvalid = 50012,
SystemIsBusy = 50013,
SystemError = 50026,
InvalidOKAccessTimestamp = 50112,
InvalidInstrument = 51001,
OrderAmountExceedsCurrentTierLimit = 51004,
OrderAmountExceedsTheLimit = 51005,
OrderPriceOutOfTheLimit = 51006,
OrderMinAmount = 51007,
OrderLowBalance = 51008,
OrderPlacementBLocked = 51009,
OperationIsNotSupported = 51010,
NotMatchInstrumentType = 51015,
OrderAmountMustBeGreaterAvailableBalance = 51020,
InstrumentExpired = 51027,
OrderQuantityLess = 51120,
OrderCountMustBeInteger = 51121,
OrderPriceHigherThenMinPrice = 51122,
InsufficientBalance = 51131,
MarketOrderSizeToLarge = 51201,
OrderAmountExceedsMax = 51202,
OrderAmountExceedsLimit = 51203,
OrderAlreadyCompleted = 51402,
}
}
| 25.061224 | 51 | 0.76873 | [
"MIT"
] | chislovMax/OKEx.Net | Okex.Net/V5/Enums/OkexApiErrorCodes.cs | 1,228 | C# |
using System.Collections;
namespace WellEngineered.CruiseControl.Core.Util
{
/// <summary>
///
/// </summary>
public interface IMultiTransformer
{
/// <summary>
/// Transforms the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <param name="transformerFileNames">The transformer file names.</param>
/// <param name="xsltArgs">The XSLT args.</param>
/// <returns></returns>
/// <remarks></remarks>
string Transform(string input, string[] transformerFileNames, Hashtable xsltArgs);
}
}
| 28.571429 | 84 | 0.611667 | [
"MIT"
] | wellengineered-us/cruisecontrol | src/WellEngineered.CruiseControl.Core/Util/IMultiTransformer.cs | 600 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
namespace Microsoft.Xrm.Sdk.Metadata
{
/// <summary>Contains all the metadata for an entity attribute.</summary>
[KnownType(typeof(DateTimeAttributeMetadata))]
[KnownType(typeof(StateAttributeMetadata))]
[KnownType(typeof(StatusAttributeMetadata))]
[KnownType(typeof(MemoAttributeMetadata))]
[KnownType(typeof(BooleanAttributeMetadata))]
[KnownType(typeof(DecimalAttributeMetadata))]
[KnownType(typeof(DoubleAttributeMetadata))]
[KnownType(typeof(EntityNameAttributeMetadata))]
[KnownType(typeof(ManagedPropertyAttributeMetadata))]
[KnownType(typeof(IntegerAttributeMetadata))]
[KnownType(typeof(BigIntAttributeMetadata))]
[KnownType(typeof(LookupAttributeMetadata))]
[KnownType(typeof(ImageAttributeMetadata))]
[KnownType(typeof(MoneyAttributeMetadata))]
[KnownType(typeof(PicklistAttributeMetadata))]
[DataContract(Name = "AttributeMetadata", Namespace = "http://schemas.microsoft.com/xrm/2011/Metadata")]
[KnownType(typeof(StringAttributeMetadata))]
public class AttributeMetadata : MetadataBase
{
private string _attributeOf;
private AttributeTypeCode? _attributeType;
private AttributeTypeDisplayName _attributeTypeDisplayName;
private int? _columnNumber;
private Label _description;
private Label _displayName;
private string _entityLogicalName;
private BooleanManagedProperty _isAuditEnabled;
private bool? _isCustomAttribute;
private bool? _isPrimaryId;
private bool? _isPrimaryAttribute;
private Guid? _linkedAttributeId;
private string _logicalName;
private string _schemaName;
private bool? _validForCreate;
private bool? _validForRead;
private bool? _validForUpdate;
private bool? _isSecured;
private bool? _canBeSecuredForRead;
private bool? _canBeSecuredForCreate;
private bool? _canBeSecuredForUpdate;
private bool? _isManaged;
private string _deprecatedVersion;
private string _introducedVersion;
private BooleanManagedProperty _isCustomizable;
private BooleanManagedProperty _isRenameable;
private BooleanManagedProperty _isValidForAdvancedFind;
private AttributeRequiredLevelManagedProperty _requiredLevel;
private BooleanManagedProperty _canModifyAdditionalSettings;
private string _aggregateOf;
private bool? _isLogical;
private int _displayMask;
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.Xrm.Sdk.Metadata.AttributeMetadata"></see> class.</summary>
public AttributeMetadata()
{
}
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.Xrm.Sdk.Metadata.AttributeMetadata"></see> class.</summary>
/// <param name="attributeType">Type: <see cref="T:Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode"></see>. Sets the type for the attribute.</param>
protected AttributeMetadata(AttributeTypeCode attributeType)
: this()
{
this.AttributeType = new AttributeTypeCode?(attributeType);
this.AttributeTypeName = this.GetAttributeTypeDisplayName(attributeType);
}
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.Xrm.Sdk.Metadata.AttributeMetadata"></see> class.</summary>
/// <param name="attributeType">Type: <see cref="T:Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode"></see>. Sets the type for the attribute.</param>
/// <param name="schemaName">Type: Returns_String. Sets the schema name of the attribute.</param>
protected AttributeMetadata(AttributeTypeCode attributeType, string schemaName)
: this(attributeType)
{
this.SchemaName = schemaName;
}
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
private AttributeTypeDisplayName GetAttributeTypeDisplayName(
AttributeTypeCode attributeType)
{
switch (attributeType)
{
case AttributeTypeCode.Boolean:
return AttributeTypeDisplayName.BooleanType;
case AttributeTypeCode.Customer:
return AttributeTypeDisplayName.CustomerType;
case AttributeTypeCode.DateTime:
return AttributeTypeDisplayName.DateTimeType;
case AttributeTypeCode.Decimal:
return AttributeTypeDisplayName.DecimalType;
case AttributeTypeCode.Double:
return AttributeTypeDisplayName.DoubleType;
case AttributeTypeCode.Integer:
return AttributeTypeDisplayName.IntegerType;
case AttributeTypeCode.Lookup:
return AttributeTypeDisplayName.LookupType;
case AttributeTypeCode.Memo:
return AttributeTypeDisplayName.MemoType;
case AttributeTypeCode.Money:
return AttributeTypeDisplayName.MoneyType;
case AttributeTypeCode.Owner:
return AttributeTypeDisplayName.OwnerType;
case AttributeTypeCode.PartyList:
return AttributeTypeDisplayName.PartyListType;
case AttributeTypeCode.Picklist:
return AttributeTypeDisplayName.PicklistType;
case AttributeTypeCode.State:
return AttributeTypeDisplayName.StateType;
case AttributeTypeCode.Status:
return AttributeTypeDisplayName.StatusType;
case AttributeTypeCode.String:
return AttributeTypeDisplayName.StringType;
case AttributeTypeCode.Uniqueidentifier:
return AttributeTypeDisplayName.UniqueidentifierType;
case AttributeTypeCode.CalendarRules:
return AttributeTypeDisplayName.CalendarRulesType;
case AttributeTypeCode.Virtual:
return AttributeTypeDisplayName.VirtualType;
case AttributeTypeCode.BigInt:
return AttributeTypeDisplayName.BigIntType;
case AttributeTypeCode.ManagedProperty:
return AttributeTypeDisplayName.ManagedPropertyType;
case AttributeTypeCode.EntityName:
return AttributeTypeDisplayName.EntityNameType;
default:
return (AttributeTypeDisplayName)null;
}
}
/// <summary>Gets the name of that attribute that this attribute extends.</summary>
/// <returns>Type: Returns_String
/// The attribute name.</returns>
[DataMember]
public string AttributeOf
{
get
{
return this._attributeOf;
}
internal set
{
this._attributeOf = value;
}
}
/// <summary>Gets the type for the attribute.</summary>
/// <returns>Type: Returns_Nullable<<see cref="T:Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode"></see>>
/// The attribute type.</returns>
[DataMember]
public AttributeTypeCode? AttributeType
{
get
{
return this._attributeType;
}
internal set
{
this._attributeType = value;
}
}
/// <summary>Gets the name of the type for the attribute.</summary>
/// <returns>Type: <see cref="T:Microsoft.Xrm.Sdk.Metadata.AttributeTypeDisplayName"></see>
/// The name of the attribute type.</returns>
[DataMember(Order = 60)]
public AttributeTypeDisplayName AttributeTypeName
{
get
{
return this._attributeTypeDisplayName;
}
internal set
{
this._attributeTypeDisplayName = value;
}
}
/// <summary>Gets an organization specific id for the attribute used for auditing.</summary>
/// <returns>Type: Returns_Nullable<Returns_Int32>
/// The organization specific id for the attribute used for auditing.</returns>
[DataMember]
public int? ColumnNumber
{
get
{
return this._columnNumber;
}
internal set
{
this._columnNumber = value;
}
}
/// <summary>Gets or sets the description of the attribute.</summary>
/// <returns>Type: <see cref="T:Microsoft.Xrm.Sdk.Label"></see>The description of the attribute.</returns>
[DataMember]
public Label Description
{
get
{
return this._description;
}
set
{
this._description = value;
}
}
/// <summary>Gets or sets the display name for the attribute.</summary>
/// <returns>Type: <see cref="T:Microsoft.Xrm.Sdk.Label"></see>The display name of the attribute.</returns>
[DataMember]
public Label DisplayName
{
get
{
return this._displayName;
}
set
{
this._displayName = value;
}
}
/// <summary>Gets the pn_microsoftcrm version that the attribute was deprecated in.</summary>
/// <returns>Type: Returns_String
/// The pn_microsoftcrm version that the attribute was deprecated in.</returns>
[DataMember]
public string DeprecatedVersion
{
get
{
return this._deprecatedVersion;
}
internal set
{
this._deprecatedVersion = value;
}
}
/// <summary>introducedversion</summary>
/// <returns>Type: Returns_String
/// The solution version number when the attribute was created.</returns>
[DataMember(Order = 60)]
public string IntroducedVersion
{
get
{
return this._introducedVersion;
}
internal set
{
this._introducedVersion = value;
}
}
/// <summary>Gets the logical name of the entity that contains the attribute.</summary>
/// <returns>Type: Returns_String
/// The logical name of the entity that contains the attribute.</returns>
[DataMember]
public string EntityLogicalName
{
get
{
return this._entityLogicalName;
}
internal set
{
this._entityLogicalName = value;
}
}
/// <summary>Gets or sets the property that determines whether the attribute is enabled for auditing.</summary>
/// <returns>Type: <see cref="T:Microsoft.Xrm.Sdk.BooleanManagedProperty"></see>
/// The property that determines whether the attribute is enabled for auditing.</returns>
[DataMember]
public BooleanManagedProperty IsAuditEnabled
{
get
{
return this._isAuditEnabled;
}
set
{
this._isAuditEnabled = value;
}
}
/// <summary>Gets whether the attribute is a custom attribute.</summary>
/// <returns>Type: Returns_Nullable<Returns_Boolean>true if the attribute is a custom attribute; otherwise, false.</returns>
[DataMember]
public bool? IsCustomAttribute
{
get
{
return this._isCustomAttribute;
}
internal set
{
this._isCustomAttribute = value;
}
}
/// <summary>Gets whether the attribute represents the unique identifier for the record.</summary>
/// <returns>Type: Returns_Nullable<Returns_Boolean>true if the attribute is the unique identifier for the record; otherwise, false.</returns>
[DataMember]
public bool? IsPrimaryId
{
get
{
return this._isPrimaryId;
}
internal set
{
this._isPrimaryId = value;
}
}
/// <summary>Gets or sets whether the attribute represents the primary attribute for the entity.</summary>
/// <returns>Type: Returns_Nullable<Returns_Boolean>true if the attribute is primary attribute for the entity; otherwise, false.</returns>
[DataMember]
public bool? IsPrimaryName
{
get
{
return this._isPrimaryAttribute;
}
internal set
{
this._isPrimaryAttribute = value;
}
}
/// <summary>Gets whether the value can be set when a record is created.</summary>
/// <returns>Type: Returns_Nullable<Returns_Boolean>true if the value can be set when a record is created; otherwise, false.</returns>
[DataMember]
public bool? IsValidForCreate
{
get
{
return this._validForCreate;
}
internal set
{
this._validForCreate = value;
}
}
/// <summary>Gets whether the value can be retrieved.</summary>
/// <returns>Type: Returns_Nullable<Returns_Boolean>true if the value can be retrieved; otherwise, false.</returns>
[DataMember]
public bool? IsValidForRead
{
get
{
return this._validForRead;
}
internal set
{
this._validForRead = value;
}
}
/// <summary>Gets whether the value can be updated.</summary>
/// <returns>Type: Returns_Nullable<Returns_Boolean>true if the value can be updated; otherwise, false.</returns>
[DataMember]
public bool? IsValidForUpdate
{
get
{
return this._validForUpdate;
}
internal set
{
this._validForUpdate = value;
}
}
/// <summary>Gets whether field level security can be applied to prevent a user from viewing data from this attribute.</summary>
/// <returns>Type: Returns_Nullable<Returns_Boolean>true if the field security can be applied; otherwise, false.</returns>
[DataMember]
public bool? CanBeSecuredForRead
{
get
{
return this._canBeSecuredForRead;
}
internal set
{
this._canBeSecuredForRead = value;
}
}
/// <summary>Gets whether field security can be applied to prevent a user from adding data to this attribute.</summary>
/// <returns>Type: Returns_Nullable<Returns_Boolean>true if the field security can be applied; otherwise, false.</returns>
[DataMember]
public bool? CanBeSecuredForCreate
{
get
{
return this._canBeSecuredForCreate;
}
internal set
{
this._canBeSecuredForCreate = value;
}
}
/// <summary>Gets whether field level security can be applied to prevent a user from updating data for this attribute.</summary>
/// <returns>Type: Returns_Nullable<Returns_Boolean>true if the field security can be applied; otherwise, false.</returns>
[DataMember]
public bool? CanBeSecuredForUpdate
{
get
{
return this._canBeSecuredForUpdate;
}
internal set
{
this._canBeSecuredForUpdate = value;
}
}
/// <summary>Gets or sets whether the attribute is secured for field level security.</summary>
/// <returns>Type: Returns_Nullable<Returns_Boolean>true if the attribute is secured for field level security; otherwise, false.</returns>
[DataMember]
public bool? IsSecured
{
get
{
return this._isSecured;
}
set
{
this._isSecured = value;
}
}
/// <summary>Gets whether the attribute is part of a managed solution.</summary>
/// <returns>Type: Returns_Nullable<Returns_Boolean>true if the attribute is part of a managed solution; otherwise, false.</returns>
[DataMember]
public bool? IsManaged
{
get
{
return this._isManaged;
}
internal set
{
this._isManaged = value;
}
}
/// <summary>Gets or sets an attribute that is linked between Appointments and Recurring appointments.</summary>
/// <returns>Type: Returns_Nullable<Returns_Guid>
/// The attribute id that is linked between Appointments and Recurring appointments.</returns>
[DataMember]
public Guid? LinkedAttributeId
{
get
{
return this._linkedAttributeId;
}
set
{
this._linkedAttributeId = value;
}
}
/// <summary>Gets or sets the logical name for the attribute.</summary>
/// <returns>Type: Returns_String
/// The logical name for the attribute.</returns>
[DataMember]
public string LogicalName
{
get
{
return this._logicalName;
}
set
{
this._logicalName = value;
}
}
/// <summary>Gets or sets the property that determines whether the attribute allows customization.</summary>
/// <returns>Type: <see cref="T:Microsoft.Xrm.Sdk.BooleanManagedProperty"></see>The property that determines whether the attribute allows customization.</returns>
[DataMember]
public BooleanManagedProperty IsCustomizable
{
get
{
return this._isCustomizable;
}
set
{
this._isCustomizable = value;
}
}
/// <summary>Gets or sets the property that determines whether the attribute display name can be changed.</summary>
/// <returns>Type: <see cref="T:Microsoft.Xrm.Sdk.BooleanManagedProperty"></see>The property that determines whether the attribute display name can be changed.</returns>
[DataMember]
public BooleanManagedProperty IsRenameable
{
get
{
return this._isRenameable;
}
set
{
this._isRenameable = value;
}
}
/// <summary>Gets or sets the property that determines whether the attribute appears in Advanced Find.</summary>
/// <returns>Type: <see cref="T:Microsoft.Xrm.Sdk.BooleanManagedProperty"></see>The property that determines whether the attribute appears in Advanced Find.</returns>
[DataMember]
public BooleanManagedProperty IsValidForAdvancedFind
{
get
{
return this._isValidForAdvancedFind;
}
set
{
this._isValidForAdvancedFind = value;
}
}
/// <summary>Gets or sets the property that determines the data entry requirement level enforced for the attribute.</summary>
/// <returns>Type: <see cref="T:Microsoft.Xrm.Sdk.Metadata.AttributeRequiredLevelManagedProperty"></see>The property that determines the data entry requirement level enforced for the attribute.</returns>
[DataMember]
public AttributeRequiredLevelManagedProperty RequiredLevel
{
get
{
return this._requiredLevel;
}
set
{
this._requiredLevel = value;
}
}
/// <summary>Gets or sets the property that determines whether any settings not controlled by managed properties can be changed.</summary>
/// <returns>Type: <see cref="T:Microsoft.Xrm.Sdk.BooleanManagedProperty"></see>The property that determines whether any settings not controlled by managed properties can be changed.</returns>
[DataMember]
public BooleanManagedProperty CanModifyAdditionalSettings
{
get
{
return this._canModifyAdditionalSettings;
}
set
{
this._canModifyAdditionalSettings = value;
}
}
/// <summary>Gets or sets the schema name for the attribute.</summary>
/// <returns>Type: Returns_String
/// The schema name for the attribute.</returns>
[DataMember]
public string SchemaName
{
get
{
return this._schemaName;
}
set
{
this._schemaName = value;
}
}
internal int DisplayMask
{
get
{
return this._displayMask;
}
set
{
this._displayMask = value;
}
}
internal string AggregateOf
{
get
{
return this._aggregateOf;
}
set
{
this._aggregateOf = value;
}
}
[DataMember(Order = 70)]
public bool? IsLogical
{
get
{
return this._isLogical;
}
internal set
{
this._isLogical = value;
}
}
/// <summary>Gets or sets the value that indicates the source type for a calculated or rollup attribute.</summary>
/// <returns>Type: Returns_Nullable<Returns_Int32> The value that indicates the source type for a calculated or rollup attribute.</returns>
[DataMember(Order = 70)]
public int? SourceType { get; set; }
}
}
| 36.4592 | 211 | 0.57287 | [
"MIT"
] | develmax/Crm.Sdk.Core | Microsoft.Xrm.Sdk/Metadata/AttributeMetadata.cs | 22,789 | C# |
namespace java.lang
{
[global::MonoJavaBridge.JavaClass()]
public sealed partial class Integer : java.lang.Number, Comparable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Integer(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public static int numberOfLeadingZeros(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m0.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m0 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "numberOfLeadingZeros", "(I)I");
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public static int numberOfTrailingZeros(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m1.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m1 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "numberOfTrailingZeros", "(I)I");
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m2;
public static int bitCount(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m2.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m2 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "bitCount", "(I)I");
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
public sealed override bool equals(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Integer.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::java.lang.Integer._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public static global::java.lang.String toString(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m4.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m4 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "toString", "(II)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m5;
public static global::java.lang.String toString(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m5.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m5 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "toString", "(I)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m6;
public sealed override global::java.lang.String toString()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.lang.Integer.staticClass, "toString", "()Ljava/lang/String;", ref global::java.lang.Integer._m6) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m7;
public sealed override int hashCode()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.Integer.staticClass, "hashCode", "()I", ref global::java.lang.Integer._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
public static int reverseBytes(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m8.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m8 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "reverseBytes", "(I)I");
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m9;
public int compareTo(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.Integer.staticClass, "compareTo", "(Ljava/lang/Object;)I", ref global::java.lang.Integer._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public int compareTo(java.lang.Integer arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.Integer.staticClass, "compareTo", "(Ljava/lang/Integer;)I", ref global::java.lang.Integer._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m11;
public static global::java.lang.String toHexString(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m11.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m11 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "toHexString", "(I)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m12;
public static global::java.lang.Integer valueOf(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m12.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m12 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "valueOf", "(Ljava/lang/String;I)Ljava/lang/Integer;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Integer>(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Integer;
}
private static global::MonoJavaBridge.MethodId _m13;
public static global::java.lang.Integer valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m13.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m13 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "valueOf", "(Ljava/lang/String;)Ljava/lang/Integer;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Integer>(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Integer;
}
private static global::MonoJavaBridge.MethodId _m14;
public static global::java.lang.Integer valueOf(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m14.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m14 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "valueOf", "(I)Ljava/lang/Integer;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Integer>(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Integer;
}
private static global::MonoJavaBridge.MethodId _m15;
public static global::java.lang.Integer decode(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m15.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m15 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "decode", "(Ljava/lang/String;)Ljava/lang/Integer;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Integer>(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Integer;
}
private static global::MonoJavaBridge.MethodId _m16;
public static int reverse(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m16.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m16 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "reverse", "(I)I");
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m17;
public sealed override byte byteValue()
{
return global::MonoJavaBridge.JavaBridge.CallByteMethod(this, global::java.lang.Integer.staticClass, "byteValue", "()B", ref global::java.lang.Integer._m17);
}
private static global::MonoJavaBridge.MethodId _m18;
public sealed override short shortValue()
{
return global::MonoJavaBridge.JavaBridge.CallShortMethod(this, global::java.lang.Integer.staticClass, "shortValue", "()S", ref global::java.lang.Integer._m18);
}
private static global::MonoJavaBridge.MethodId _m19;
public sealed override int intValue()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.Integer.staticClass, "intValue", "()I", ref global::java.lang.Integer._m19);
}
private static global::MonoJavaBridge.MethodId _m20;
public sealed override long longValue()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.lang.Integer.staticClass, "longValue", "()J", ref global::java.lang.Integer._m20);
}
private static global::MonoJavaBridge.MethodId _m21;
public sealed override float floatValue()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::java.lang.Integer.staticClass, "floatValue", "()F", ref global::java.lang.Integer._m21);
}
private static global::MonoJavaBridge.MethodId _m22;
public sealed override double doubleValue()
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::java.lang.Integer.staticClass, "doubleValue", "()D", ref global::java.lang.Integer._m22);
}
private static global::MonoJavaBridge.MethodId _m23;
public static int parseInt(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m23.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m23 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "parseInt", "(Ljava/lang/String;)I");
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m24;
public static int parseInt(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m24.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m24 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "parseInt", "(Ljava/lang/String;I)I");
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m25;
public static global::java.lang.String toOctalString(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m25.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m25 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "toOctalString", "(I)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m26;
public static global::java.lang.String toBinaryString(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m26.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m26 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "toBinaryString", "(I)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m27;
public static global::java.lang.Integer getInteger(java.lang.String arg0, java.lang.Integer arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m27.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m27 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "getInteger", "(Ljava/lang/String;Ljava/lang/Integer;)Ljava/lang/Integer;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Integer>(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Integer;
}
private static global::MonoJavaBridge.MethodId _m28;
public static global::java.lang.Integer getInteger(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m28.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m28 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "getInteger", "(Ljava/lang/String;)Ljava/lang/Integer;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Integer>(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Integer;
}
private static global::MonoJavaBridge.MethodId _m29;
public static global::java.lang.Integer getInteger(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m29.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m29 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "getInteger", "(Ljava/lang/String;I)Ljava/lang/Integer;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Integer>(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Integer;
}
private static global::MonoJavaBridge.MethodId _m30;
public static int highestOneBit(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m30.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m30 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "highestOneBit", "(I)I");
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m31;
public static int lowestOneBit(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m31.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m31 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "lowestOneBit", "(I)I");
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m32;
public static int rotateLeft(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m32.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m32 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "rotateLeft", "(II)I");
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m33;
public static int rotateRight(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m33.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m33 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "rotateRight", "(II)I");
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m34;
public static int signum(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m34.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m34 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "signum", "(I)I");
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m35;
public Integer(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m35.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m35 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "<init>", "(I)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Integer.staticClass, global::java.lang.Integer._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m36;
public Integer(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Integer._m36.native == global::System.IntPtr.Zero)
global::java.lang.Integer._m36 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "<init>", "(Ljava/lang/String;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Integer.staticClass, global::java.lang.Integer._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
public static int MIN_VALUE
{
get
{
return -2147483648;
}
}
public static int MAX_VALUE
{
get
{
return 2147483647;
}
}
internal static global::MonoJavaBridge.FieldId _TYPE6372;
public static global::java.lang.Class TYPE
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Class>(@__env.GetStaticObjectField(global::java.lang.Integer.staticClass, _TYPE6372)) as java.lang.Class;
}
}
public static int SIZE
{
get
{
return 32;
}
}
static Integer()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.lang.Integer.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/Integer"));
global::java.lang.Integer._TYPE6372 = @__env.GetStaticFieldIDNoThrow(global::java.lang.Integer.staticClass, "TYPE", "Ljava/lang/Class;");
}
}
}
| 68.626198 | 316 | 0.775605 | [
"MIT"
] | JeroMiya/androidmono | MonoJavaBridge/android/generated/java/lang/Integer.cs | 21,480 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.WebSites.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.WebSites;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// A snapshot of a web app configuration.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class SiteConfigurationSnapshotInfo : ProxyOnlyResource
{
/// <summary>
/// Initializes a new instance of the SiteConfigurationSnapshotInfo
/// class.
/// </summary>
public SiteConfigurationSnapshotInfo()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SiteConfigurationSnapshotInfo
/// class.
/// </summary>
/// <param name="id">Resource Id.</param>
/// <param name="name">Resource Name.</param>
/// <param name="kind">Kind of resource.</param>
/// <param name="type">Resource type.</param>
/// <param name="time">The time the snapshot was taken.</param>
/// <param name="siteConfigurationSnapshotInfoId">The id of the
/// snapshot</param>
public SiteConfigurationSnapshotInfo(string id = default(string), string name = default(string), string kind = default(string), string type = default(string), System.DateTime? time = default(System.DateTime?), int? siteConfigurationSnapshotInfoId = default(int?))
: base(id, name, kind, type)
{
Time = time;
SiteConfigurationSnapshotInfoId = siteConfigurationSnapshotInfoId;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the time the snapshot was taken.
/// </summary>
[JsonProperty(PropertyName = "properties.time")]
public System.DateTime? Time { get; private set; }
/// <summary>
/// Gets the id of the snapshot
/// </summary>
[JsonProperty(PropertyName = "properties.id")]
public int? SiteConfigurationSnapshotInfoId { get; private set; }
}
}
| 36.611111 | 271 | 0.633915 | [
"MIT"
] | thangnguyen2001/azure-sdk-for-net | src/SDKs/WebSites/Management.Websites/Generated/Models/SiteConfigurationSnapshotInfo.cs | 2,636 | C# |
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using SalesManagement.MultiTenancy;
namespace SalesManagement.Sessions.Dto
{
[AutoMapFrom(typeof(Tenant))]
public class TenantLoginInfoDto : EntityDto
{
public string TenancyName { get; set; }
public string Name { get; set; }
}
}
| 21.533333 | 47 | 0.702786 | [
"MIT"
] | NguyenVanTung11041998/SalesManaementApi | aspnet-core/src/SalesManagement.Application/Sessions/Dto/TenantLoginInfoDto.cs | 325 | C# |
// © Anamnesis.
// Licensed under the MIT license.
namespace Anamnesis.Windows
{
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Animation;
using Anamnesis.GUI;
using Anamnesis.Services;
using Anamnesis.Utils;
using Serilog;
using XivToolsWpf;
/// <summary>
/// Interaction logic for MiniWindow.xaml.
/// </summary>
public partial class MiniWindow : Window
{
private readonly MainWindow main;
private bool isHidden = false;
private Point downPos;
private bool mouseDown = false;
private bool isDeactivating = false;
public MiniWindow(MainWindow main)
{
this.main = main;
this.InitializeComponent();
this.main.Deactivated += this.Main_Deactivated;
this.Left = SettingsService.Current.OverlayWindowPosition.X;
this.Top = SettingsService.Current.OverlayWindowPosition.Y;
_ = Task.Run(this.Ping);
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
this.OnLocationChanged(null, null);
}
private async void Main_Deactivated(object? sender, System.EventArgs e)
{
this.isHidden = true;
this.main.Hide();
((Storyboard)this.Resources["AnimateCloseStoryboard"]).Begin(this);
this.isDeactivating = true;
await Task.Delay(200);
this.isDeactivating = false;
}
private void OnMouseDown(object sender, MouseButtonEventArgs e)
{
if (this.isDeactivating)
return;
this.mouseDown = true;
this.downPos.X = this.Left;
this.downPos.Y = this.Top;
if (e.LeftButton == MouseButtonState.Pressed)
{
this.DragMove();
}
}
private void OnMouseUp(object sender, MouseButtonEventArgs e)
{
if (!this.mouseDown)
return;
this.mouseDown = false;
if (this.isDeactivating)
return;
if (!this.isHidden)
return;
Point upPos = default;
upPos.X = this.Left;
upPos.Y = this.Top;
Vector delta = upPos - this.downPos;
if (delta.Length > 100)
return;
this.OnLocationChanged(null, null);
((Storyboard)this.Resources["AnimateOpenStoryboard"]).Begin(this);
this.main.Show();
if (this.main.WindowState == WindowState.Minimized)
this.main.WindowState = WindowState.Normal;
this.isHidden = false;
}
private void OnLocationChanged(object? sender, System.EventArgs? e)
{
Point p = default;
p.X = this.Left;
p.Y = this.Top;
SettingsService.Current.OverlayWindowPosition = p;
if (double.IsNaN(this.main.Height) || double.IsNaN(this.main.Width))
return;
double centerX = this.Left + (this.Width / 2);
double centerY = this.Top + (this.Width / 2);
double iconRadius = 22;
Point tl = new Point(centerX + iconRadius, centerY - iconRadius);
Point tr = new Point(centerX + iconRadius + this.main.Width, centerY - iconRadius);
Point bl = new Point(centerX + iconRadius, centerY - iconRadius + this.main.Height);
if (!ScreenUtils.IsOnScreen(tr))
tl.X = centerX - iconRadius - this.main.Width;
if (!ScreenUtils.IsOnScreen(bl))
tl.Y = (centerY + iconRadius) - this.main.Height;
this.main.Left = tl.X;
this.main.Top = tl.Y;
SettingsService.Current.WindowPosition = tl;
}
private void OnClosing(object sender, CancelEventArgs e)
{
if (!this.main.IsClosing && SettingsService.Current.OverlayWindow)
{
e.Cancel = true;
}
else
{
this.main.Deactivated -= this.Main_Deactivated;
}
}
private async Task Ping()
{
while (this.main != null && this.Dispatcher != null)
{
await Task.Delay(3000);
await Dispatch.MainThread();
if (!this.isHidden)
continue;
((Storyboard)this.Resources["AnimateIdleStoryboard"]).Begin(this);
}
}
}
}
| 22.851852 | 87 | 0.685305 | [
"MIT"
] | Lunarisnia/Anamnesis | Anamnesis/Windows/MiniWindow.xaml.cs | 3,705 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System;
using System.Collections.Generic;
namespace EdFi.Ods.Common.Models.Domain
{
public class EntityPropertyEqualityComparer : IEqualityComparer<EntityProperty>
{
/// <summary>
/// Determines whether the specified objects are equal.
/// </summary>
/// <returns>
/// true if the specified objects are equal; otherwise, false.
/// </returns>
/// <param name="x">The first object of type <paramref name="T"/> to compare.</param><param name="y">The second object of type <paramref name="T"/> to compare.</param>
public bool Equals(EntityProperty x, EntityProperty y)
{
return string.Equals(x.PropertyName, y.PropertyName, StringComparison.InvariantCultureIgnoreCase);
}
/// <summary>
/// Returns a hash code for the specified object.
/// </summary>
/// <returns>
/// A hash code for the specified object.
/// </returns>
/// <param name="obj">The <see cref="T:System.Object"/> for which a hash code is to be returned.</param><exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception>
public int GetHashCode(EntityProperty obj)
{
return obj.PropertyName.GetHashCode();
}
}
}
| 43.157895 | 263 | 0.65061 | [
"Apache-2.0"
] | gmcelhanon/Ed-Fi-ODS-1 | Application/EdFi.Ods.Common/Models/Domain/EntityPropertyEqualityComparer.cs | 1,640 | C# |
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace CollabAssist.API
{
public class Program
{
public static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseConfiguration(builder)
.UseStartup<Startup>()
.Build()
.Run();
}
}
}
| 28.074074 | 85 | 0.562005 | [
"MIT"
] | Dyllaann/CollabAssist | src/CollabAssist.API/Program.cs | 758 | C# |
// <auto-generated>
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace KyGunCo.Counterpoint.Sdk.Entities
{
// PS_VOID_HIST_LIN_PO
public class PsVoidHistLinPo
{
public DateTime BusDat { get; set; } // BUS_DAT (Primary key)
public long DocId { get; set; } // DOC_ID (Primary key)
public int LinSeqNo { get; set; } // LIN_SEQ_NO (Primary key)
public string PoPreqNo { get; set; } // PO_PREQ_NO (length: 15)
public string PoOrdNo { get; set; } // PO_ORD_NO (length: 20)
public int? PoLinSeqNo { get; set; } // PO_LIN_SEQ_NO
public string PoRecvrNo { get; set; } // PO_RECVR_NO (length: 15)
public int? PoRecvrLinSeqNo { get; set; } // PO_RECVR_LIN_SEQ_NO
public decimal? PoTotQtyRecvd { get; set; } // PO_TOT_QTY_RECVD
public decimal? PoQtyExpectd { get; set; } // PO_QTY_EXPECTD
public int? PoRecvrCnt { get; set; } // PO_RECVR_CNT
// Foreign keys
/// <summary>
/// Parent PsVoidHistLin pointed by [PS_VOID_HIST_LIN_PO].([BusDat], [DocId], [LinSeqNo]) (FK_PS_VOID_HIST_LIN_PO_PS_VOID_HIST_LIN)
/// </summary>
public virtual PsVoidHistLin PsVoidHistLin { get; set; } // FK_PS_VOID_HIST_LIN_PO_PS_VOID_HIST_LIN
}
}
// </auto-generated>
| 38.342857 | 139 | 0.656483 | [
"MIT"
] | kygunco/KyGunCo.Counterpoint | Source/KyGunCo.Counterpoint.Sdk/Entities/PsVoidHistLinPo.cs | 1,342 | C# |
using smartDormitory.Data.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace smartDormitory.WEB.Areas.Admin.Models.Sensor
{
public class SensorViewModel
{
public SensorViewModel()
{
}
public SensorViewModel(UserSensors userSensors)
{
this.Id = userSensors.Id;
this.IcbSensorId = userSensors.Sensor.IcbSensorId;
this.Name = userSensors.Name;
this.UserName = userSensors.User.UserName;
this.Description = userSensors.Description;
this.Tag = userSensors.Sensor.Tag;
this.Value = userSensors.Sensor.Value;
this.PollingInterval = userSensors.PollingInterval;
this.ModifiedOn = userSensors.Sensor.ModifiedOn;
this.Alarm = userSensors.Alarm;
this.Latitude = userSensors.Latitude;
this.Longtitude = userSensors.Longitude;
this.URL = userSensors.Sensor.Url;
this.IsPublic = userSensors.IsPublic;
this.MinValue = userSensors.MinValue;
this.MaxValue = userSensors.MaxValue;
this.ImageURL = userSensors.ImageUrl;
this.MeasureType = userSensors.Sensor.MeasureType.Type;
}
public SensorViewModel(smartDormitory.Data.Sensor sensor)
{
this.Id = sensor.Id;
this.Description = sensor.Description;
this.Tag = sensor.Tag;
this.Value = sensor.Value;
this.PollingInterval = sensor.PollingInterval;
this.ModifiedOn = sensor.ModifiedOn;
this.URL = sensor.Url;
this.MinValue = sensor.MinValue;
this.MaxValue = sensor.MaxValue;
this.MeasureType = sensor.MeasureType.Type;
}
[Required]
public int Id { get; set; }
public string UserId { get; set; }
[Required]
public string IcbSensorId { get; set; }
[Required]
[StringLength(20, MinimumLength = 3)]
public string Name { get; set; }
[Range(0, 5000)]
public double MinValue { get; set; }
[Range(0, 5000)]
public double MaxValue { get; set; }
[Required]
[StringLength(150, MinimumLength = 5)]
public string Description { get; set; }
[Required]
[Range(10, 40)]
public int PollingInterval { get; set; }
[Required]
public double Latitude { get; set; }
[Required]
public double Longtitude { get; set; }
[Required]
public bool IsPublic { get; set; }
[Required]
public bool Alarm { get; set; }
public List<double> ValidationsMinMax { get; set; }
public string Tag { get; set; }
public string UserName { get; set; }
public DateTime? ModifiedOn { get; set; }
public double Value { get; set; }
public string URL { get; set; }
public double SensorTypeMinVal { get; set; }
public double SensorTypeMaxVal { get; set; }
public string ImageURL { get; set; }
public string MeasureType { get; set; }
}
}
| 29.545455 | 67 | 0.592615 | [
"MIT"
] | albozhinov/smartDormitory | smartDormitory/smartDormitory.WEB/Areas/Admin/Models/Sensor/SensorViewModel.cs | 3,252 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class DeathPanelScript : MonoBehaviour
{
public void MenuAfterDeath()
{
Debug.Log("respawn");
EventManager.TriggerEvent(Names.Events.Respawn);
SceneManager.LoadScene("Menu");
}
}
| 18.9 | 57 | 0.645503 | [
"MIT"
] | Riccardo95Facchini/BobTheChameleon | BobTheChameleon/Assets/DeathPanelScript.cs | 380 | C# |
/*
* Copyright (c) 2017-2020 Håkan Edling
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* https://github.com/piranhacms/piranha.core
*
*/
using System;
namespace Piranha.Models
{
[Serializable]
public class MediaStructureItem : StructureItem<MediaStructure, MediaStructureItem>
{
/// <summary>
/// Gets/sets the folder name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the number of child folders in the folder.
/// </summary>
public int FolderCount { get; set; }
/// <summary>
/// Gets/sets the number of media items in the folder.
/// </summary>
public int MediaCount { get; set; }
/// <summary>
/// Gets/sets the created date.
/// </summary>
public DateTime Created { get; set; }
/// <summary>
/// Default constructor.
/// </summary>
public MediaStructureItem()
{
Items = new MediaStructure();
}
}
} | 24.586957 | 87 | 0.562334 | [
"MIT"
] | LostColonel/PiranhaCMS | core/Piranha/Models/MediaStructureItem.cs | 1,132 | C# |
using Dynamix;
using Fame;
using FAMIX;
using FILE;
using System;
using System.Collections.Generic;
namespace FILE
{
[FamePackage("FILE")]
[FameDescription("AbstractFile")]
public class AbstractFile : FAMIX.Entity
{
[FameProperty(Name = "name")]
public String name { get; set; }
[FameProperty(Name = "parentFolder", Opposite = "childrenFileSystemEntities")]
public FILE.Folder parentFolder { get; set; }
}
}
| 21.045455 | 86 | 0.663067 | [
"Apache-2.0"
] | feenkcom/roslyn2famix | Roslyn2Famix/Model/FILE/AbstractFile.cs | 463 | C# |
using JetBrains.Annotations;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Services;
namespace JsonApiDotNetCore.AtomicOperations.Processors;
/// <inheritdoc />
[PublicAPI]
public class RemoveFromRelationshipProcessor<TResource, TId> : IRemoveFromRelationshipProcessor<TResource, TId>
where TResource : class, IIdentifiable<TId>
{
private readonly IRemoveFromRelationshipService<TResource, TId> _service;
public RemoveFromRelationshipProcessor(IRemoveFromRelationshipService<TResource, TId> service)
{
ArgumentGuard.NotNull(service, nameof(service));
_service = service;
}
/// <inheritdoc />
public virtual async Task<OperationContainer?> ProcessAsync(OperationContainer operation, CancellationToken cancellationToken)
{
ArgumentGuard.NotNull(operation, nameof(operation));
var leftId = (TId)operation.Resource.GetTypedId();
ISet<IIdentifiable> rightResourceIds = operation.GetSecondaryResources();
await _service.RemoveFromToManyRelationshipAsync(leftId, operation.Request.Relationship!.PublicName, rightResourceIds, cancellationToken);
return null;
}
}
| 34.352941 | 146 | 0.768836 | [
"MIT"
] | damien-rousseau/JsonApiDotNetCore_Polymorphism | src/JsonApiDotNetCore/AtomicOperations/Processors/RemoveFromRelationshipProcessor.cs | 1,168 | C# |
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
namespace NoteApp.EntityFrameworkCore
{
public static class NoteAppDbContextConfigurer
{
public static void Configure(DbContextOptionsBuilder<NoteAppDbContext> builder, string connectionString)
{
builder.UseSqlServer(connectionString);
}
public static void Configure(DbContextOptionsBuilder<NoteAppDbContext> builder, DbConnection connection)
{
builder.UseSqlServer(connection);
}
}
}
| 28.105263 | 112 | 0.715356 | [
"MIT"
] | nitinreddy3/NoteApp | aspnet-core/src/NoteApp.EntityFrameworkCore/EntityFrameworkCore/NoteAppDbContextConfigurer.cs | 534 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// alipay.pass.file.add
/// </summary>
public class AlipayPassFileAddRequest : IAlipayRequest<AlipayPassFileAddResponse>
{
/// <summary>
/// 支付宝pass文件二进制Base64加密字符串
/// </summary>
public string FileContent { get; set; }
/// <summary>
/// 支付宝用户识别信息: 当 recognition_type=1时, recognition_info={“partner_id”:”2088102114633762”,“out_trade_no”:”1234567”}; 当recognition_type=2时, recognition_info={“user_id”:”2088102114633761“} 当recognition_type=3时,recognition_info={“mobile”:”136XXXXXXXX“}
/// </summary>
public string RecognitionInfo { get; set; }
/// <summary>
/// Alipass添加对象识别类型【1--订单信息;2--支付宝userId;3--支付宝绑定手机号】
/// </summary>
public string RecognitionType { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.pass.file.add";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "file_content", FileContent },
{ "recognition_info", RecognitionInfo },
{ "recognition_type", RecognitionType }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 25.125 | 258 | 0.558677 | [
"MIT"
] | lzw316/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayPassFileAddRequest.cs | 3,569 | C# |
using System;
using System.IO;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// Defines known values for the <see cref="HostSystemID"/> property.
/// </summary>
public enum HostSystemID
{
/// <summary>
/// Host system = MSDOS
/// </summary>
Msdos = 0,
/// <summary>
/// Host system = Amiga
/// </summary>
Amiga = 1,
/// <summary>
/// Host system = Open VMS
/// </summary>
OpenVms = 2,
/// <summary>
/// Host system = Unix
/// </summary>
Unix = 3,
/// <summary>
/// Host system = VMCms
/// </summary>
VMCms = 4,
/// <summary>
/// Host system = Atari ST
/// </summary>
AtariST = 5,
/// <summary>
/// Host system = OS2
/// </summary>
OS2 = 6,
/// <summary>
/// Host system = Macintosh
/// </summary>
Macintosh = 7,
/// <summary>
/// Host system = ZSystem
/// </summary>
ZSystem = 8,
/// <summary>
/// Host system = Cpm
/// </summary>
Cpm = 9,
/// <summary>
/// Host system = Windows NT
/// </summary>
WindowsNT = 10,
/// <summary>
/// Host system = MVS
/// </summary>
MVS = 11,
/// <summary>
/// Host system = VSE
/// </summary>
Vse = 12,
/// <summary>
/// Host system = Acorn RISC
/// </summary>
AcornRisc = 13,
/// <summary>
/// Host system = VFAT
/// </summary>
Vfat = 14,
/// <summary>
/// Host system = Alternate MVS
/// </summary>
AlternateMvs = 15,
/// <summary>
/// Host system = BEOS
/// </summary>
BeOS = 16,
/// <summary>
/// Host system = Tandem
/// </summary>
Tandem = 17,
/// <summary>
/// Host system = OS400
/// </summary>
OS400 = 18,
/// <summary>
/// Host system = OSX
/// </summary>
OSX = 19,
/// <summary>
/// Host system = WinZIP AES
/// </summary>
WinZipAES = 99,
}
/// <summary>
/// This class represents an entry in a zip archive. This can be a file
/// or a directory
/// ZipFile and ZipInputStream will give you instances of this class as
/// information about the members in an archive. ZipOutputStream
/// uses an instance of this class when creating an entry in a Zip file.
/// <br/>
/// <br/>Author of the original java version : Jochen Hoenicke
/// </summary>
public class ZipEntry
{
[Flags]
enum Known : byte
{
None = 0,
Size = 0x01,
CompressedSize = 0x02,
Crc = 0x04,
Time = 0x08,
ExternalAttributes = 0x10,
}
#region Constructors
/// <summary>
/// Creates a zip entry with the given name.
/// </summary>
/// <param name="name">
/// The name for this entry. Can include directory components.
/// The convention for names is 'unix' style paths with relative names only.
/// There are with no device names and path elements are separated by '/' characters.
/// </param>
/// <exception cref="ArgumentNullException">
/// The name passed is null
/// </exception>
public ZipEntry(string name)
: this(name, 0, ZipConstants.VersionMadeBy, CompressionMethod.Deflated)
{
}
/// <summary>
/// Creates a zip entry with the given name and version required to extract
/// </summary>
/// <param name="name">
/// The name for this entry. Can include directory components.
/// The convention for names is 'unix' style paths with no device names and
/// path elements separated by '/' characters. This is not enforced see <see cref="CleanName(string)">CleanName</see>
/// on how to ensure names are valid if this is desired.
/// </param>
/// <param name="versionRequiredToExtract">
/// The minimum 'feature version' required this entry
/// </param>
/// <exception cref="ArgumentNullException">
/// The name passed is null
/// </exception>
internal ZipEntry(string name, int versionRequiredToExtract)
: this(name, versionRequiredToExtract, ZipConstants.VersionMadeBy,
CompressionMethod.Deflated)
{
}
/// <summary>
/// Initializes an entry with the given name and made by information
/// </summary>
/// <param name="name">Name for this entry</param>
/// <param name="madeByInfo">Version and HostSystem Information</param>
/// <param name="versionRequiredToExtract">Minimum required zip feature version required to extract this entry</param>
/// <param name="method">Compression method for this entry.</param>
/// <exception cref="ArgumentNullException">
/// The name passed is null
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// versionRequiredToExtract should be 0 (auto-calculate) or > 10
/// </exception>
/// <remarks>
/// This constructor is used by the ZipFile class when reading from the central header
/// It is not generally useful, use the constructor specifying the name only.
/// </remarks>
internal ZipEntry(string name, int versionRequiredToExtract, int madeByInfo,
CompressionMethod method)
{
if (name == null) {
throw new ArgumentNullException(nameof(name));
}
if (name.Length > 0xffff) {
throw new ArgumentException("Name is too long", nameof(name));
}
if ((versionRequiredToExtract != 0) && (versionRequiredToExtract < 10)) {
throw new ArgumentOutOfRangeException(nameof(versionRequiredToExtract));
}
this.DateTime = DateTime.Now;
this.name = CleanName(name);
this.versionMadeBy = (ushort)madeByInfo;
this.versionToExtract = (ushort)versionRequiredToExtract;
this.method = method;
}
/// <summary>
/// Creates a deep copy of the given zip entry.
/// </summary>
/// <param name="entry">
/// The entry to copy.
/// </param>
[Obsolete("Use Clone instead")]
public ZipEntry(ZipEntry entry)
{
if (entry == null) {
throw new ArgumentNullException(nameof(entry));
}
known = entry.known;
name = entry.name;
size = entry.size;
compressedSize = entry.compressedSize;
crc = entry.crc;
dosTime = entry.dosTime;
method = entry.method;
comment = entry.comment;
versionToExtract = entry.versionToExtract;
versionMadeBy = entry.versionMadeBy;
externalFileAttributes = entry.externalFileAttributes;
flags = entry.flags;
zipFileIndex = entry.zipFileIndex;
offset = entry.offset;
forceZip64_ = entry.forceZip64_;
if (entry.extra != null) {
extra = new byte[entry.extra.Length];
Array.Copy(entry.extra, 0, extra, 0, entry.extra.Length);
}
}
#endregion
/// <summary>
/// Get a value indicating wether the entry has a CRC value available.
/// </summary>
public bool HasCrc {
get {
return (known & Known.Crc) != 0;
}
}
public bool IsAesCrypted
{
get
{
return this.ExtraData.Length >= 168 && this.ExtraData[168] > 0x00;
// return this.RsaKey != null;
}
}
/// <summary>
/// Get/Set flag indicating if entry is encrypted.
/// A simple helper routine to aid interpretation of <see cref="Flags">flags</see>
/// </summary>
/// <remarks>This is an assistant that interprets the <see cref="Flags">flags</see> property.</remarks>
public bool IsCrypted {
get {
return (flags & 1) != 0;
}
set {
if (value) {
flags |= 1;
} else {
flags &= ~1;
}
}
}
/// <summary>
/// Get / set a flag indicating wether entry name and comment text are
/// encoded in <a href="http://www.unicode.org">unicode UTF8</a>.
/// </summary>
/// <remarks>This is an assistant that interprets the <see cref="Flags">flags</see> property.</remarks>
public bool IsUnicodeText {
get {
return (flags & (int)GeneralBitFlags.UnicodeText) != 0;
}
set {
if (value) {
flags |= (int)GeneralBitFlags.UnicodeText;
} else {
flags &= ~(int)GeneralBitFlags.UnicodeText;
}
}
}
/// <summary>
/// Value used during password checking for PKZIP 2.0 / 'classic' encryption.
/// </summary>
internal byte CryptoCheckValue {
get {
return cryptoCheckValue_;
}
set {
cryptoCheckValue_ = value;
}
}
/// <summary>
/// Get/Set general purpose bit flag for entry
/// </summary>
/// <remarks>
/// General purpose bit flag<br/>
/// <br/>
/// Bit 0: If set, indicates the file is encrypted<br/>
/// Bit 1-2 Only used for compression type 6 Imploding, and 8, 9 deflating<br/>
/// Imploding:<br/>
/// Bit 1 if set indicates an 8K sliding dictionary was used. If clear a 4k dictionary was used<br/>
/// Bit 2 if set indicates 3 Shannon-Fanno trees were used to encode the sliding dictionary, 2 otherwise<br/>
/// <br/>
/// Deflating:<br/>
/// Bit 2 Bit 1<br/>
/// 0 0 Normal compression was used<br/>
/// 0 1 Maximum compression was used<br/>
/// 1 0 Fast compression was used<br/>
/// 1 1 Super fast compression was used<br/>
/// <br/>
/// Bit 3: If set, the fields crc-32, compressed size
/// and uncompressed size are were not able to be written during zip file creation
/// The correct values are held in a data descriptor immediately following the compressed data. <br/>
/// Bit 4: Reserved for use by PKZIP for enhanced deflating<br/>
/// Bit 5: If set indicates the file contains compressed patch data<br/>
/// Bit 6: If set indicates strong encryption was used.<br/>
/// Bit 7-10: Unused or reserved<br/>
/// Bit 11: If set the name and comments for this entry are in <a href="http://www.unicode.org">unicode</a>.<br/>
/// Bit 12-15: Unused or reserved<br/>
/// </remarks>
/// <seealso cref="IsUnicodeText"></seealso>
/// <seealso cref="IsCrypted"></seealso>
public int Flags {
get {
return flags;
}
set {
flags = value;
}
}
/// <summary>
/// Get/Set index of this entry in Zip file
/// </summary>
/// <remarks>This is only valid when the entry is part of a <see cref="ZipFile"></see></remarks>
public long ZipFileIndex {
get {
return zipFileIndex;
}
set {
zipFileIndex = value;
}
}
/// <summary>
/// Get/set offset for use in central header
/// </summary>
public long Offset {
get {
return offset;
}
set {
offset = value;
}
}
/// <summary>
/// Get/Set external file attributes as an integer.
/// The values of this are operating system dependant see
/// <see cref="HostSystem">HostSystem</see> for details
/// </summary>
public int ExternalFileAttributes {
get {
if ((known & Known.ExternalAttributes) == 0) {
return -1;
} else {
return externalFileAttributes;
}
}
set {
externalFileAttributes = value;
known |= Known.ExternalAttributes;
}
}
/// <summary>
/// Get the version made by for this entry or zero if unknown.
/// The value / 10 indicates the major version number, and
/// the value mod 10 is the minor version number
/// </summary>
public int VersionMadeBy {
get {
return (versionMadeBy & 0xff);
}
}
/// <summary>
/// Get a value indicating this entry is for a DOS/Windows system.
/// </summary>
public bool IsDOSEntry {
get {
return ((HostSystem == (int)HostSystemID.Msdos) ||
(HostSystem == (int)HostSystemID.WindowsNT));
}
}
/// <summary>
/// Test the external attributes for this <see cref="ZipEntry"/> to
/// see if the external attributes are Dos based (including WINNT and variants)
/// and match the values
/// </summary>
/// <param name="attributes">The attributes to test.</param>
/// <returns>Returns true if the external attributes are known to be DOS/Windows
/// based and have the same attributes set as the value passed.</returns>
bool HasDosAttributes(int attributes)
{
bool result = false;
if ((known & Known.ExternalAttributes) != 0) {
result |= (((HostSystem == (int)HostSystemID.Msdos) ||
(HostSystem == (int)HostSystemID.WindowsNT)) &&
(ExternalFileAttributes & attributes) == attributes);
}
return result;
}
/// <summary>
/// Gets the compatability information for the <see cref="ExternalFileAttributes">external file attribute</see>
/// If the external file attributes are compatible with MS-DOS and can be read
/// by PKZIP for DOS version 2.04g then this value will be zero. Otherwise the value
/// will be non-zero and identify the host system on which the attributes are compatible.
/// </summary>
///
/// <remarks>
/// The values for this as defined in the Zip File format and by others are shown below. The values are somewhat
/// misleading in some cases as they are not all used as shown. You should consult the relevant documentation
/// to obtain up to date and correct information. The modified appnote by the infozip group is
/// particularly helpful as it documents a lot of peculiarities. The document is however a little dated.
/// <list type="table">
/// <item>0 - MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems)</item>
/// <item>1 - Amiga</item>
/// <item>2 - OpenVMS</item>
/// <item>3 - Unix</item>
/// <item>4 - VM/CMS</item>
/// <item>5 - Atari ST</item>
/// <item>6 - OS/2 HPFS</item>
/// <item>7 - Macintosh</item>
/// <item>8 - Z-System</item>
/// <item>9 - CP/M</item>
/// <item>10 - Windows NTFS</item>
/// <item>11 - MVS (OS/390 - Z/OS)</item>
/// <item>12 - VSE</item>
/// <item>13 - Acorn Risc</item>
/// <item>14 - VFAT</item>
/// <item>15 - Alternate MVS</item>
/// <item>16 - BeOS</item>
/// <item>17 - Tandem</item>
/// <item>18 - OS/400</item>
/// <item>19 - OS/X (Darwin)</item>
/// <item>99 - WinZip AES</item>
/// <item>remainder - unused</item>
/// </list>
/// </remarks>
public int HostSystem {
get {
return (versionMadeBy >> 8) & 0xff;
}
set {
versionMadeBy &= 0xff;
versionMadeBy |= (ushort)((value & 0xff) << 8);
}
}
/// <summary>
/// Get minimum Zip feature version required to extract this entry
/// </summary>
/// <remarks>
/// Minimum features are defined as:<br/>
/// 1.0 - Default value<br/>
/// 1.1 - File is a volume label<br/>
/// 2.0 - File is a folder/directory<br/>
/// 2.0 - File is compressed using Deflate compression<br/>
/// 2.0 - File is encrypted using traditional encryption<br/>
/// 2.1 - File is compressed using Deflate64<br/>
/// 2.5 - File is compressed using PKWARE DCL Implode<br/>
/// 2.7 - File is a patch data set<br/>
/// 4.5 - File uses Zip64 format extensions<br/>
/// 4.6 - File is compressed using BZIP2 compression<br/>
/// 5.0 - File is encrypted using DES<br/>
/// 5.0 - File is encrypted using 3DES<br/>
/// 5.0 - File is encrypted using original RC2 encryption<br/>
/// 5.0 - File is encrypted using RC4 encryption<br/>
/// 5.1 - File is encrypted using AES encryption<br/>
/// 5.1 - File is encrypted using corrected RC2 encryption<br/>
/// 5.1 - File is encrypted using corrected RC2-64 encryption<br/>
/// 6.1 - File is encrypted using non-OAEP key wrapping<br/>
/// 6.2 - Central directory encryption (not confirmed yet)<br/>
/// 6.3 - File is compressed using LZMA<br/>
/// 6.3 - File is compressed using PPMD+<br/>
/// 6.3 - File is encrypted using Blowfish<br/>
/// 6.3 - File is encrypted using Twofish<br/>
/// </remarks>
/// <seealso cref="CanDecompress"></seealso>
public int Version {
get {
// Return recorded version if known.
if (versionToExtract != 0) {
return versionToExtract & 0x00ff; // Only lower order byte. High order is O/S file system.
} else {
int result = 10;
// TODO: Detect version for ZStd entries
if (AESKeySize > 0) {
result = ZipConstants.VERSION_AES; // Ver 5.1 = AES
} else if (CentralHeaderRequiresZip64) {
result = ZipConstants.VersionZip64;
} else if (CompressionMethod.Deflated == method) {
result = 20;
} else if (IsDirectory == true) {
result = 20;
} else if (IsCrypted == true) {
result = 20;
} else if (HasDosAttributes(0x08)) {
result = 11;
}
return result;
}
}
}
/// <summary>
/// Get a value indicating whether this entry can be decompressed by the library.
/// </summary>
/// <remarks>This is based on the <see cref="Version"></see> and
/// wether the <see cref="IsCompressionMethodSupported()">compression method</see> is supported.</remarks>
public bool CanDecompress {
get {
return (Version <= ZipConstants.VersionMadeBy) &&
((Version == 10) ||
(Version == 11) ||
(Version == 20) ||
(Version == 45) ||
(Version == 51)) &&
// TODO: Add support for ZStd
IsCompressionMethodSupported();
}
}
/// <summary>
/// Force this entry to be recorded using Zip64 extensions.
/// </summary>
public void ForceZip64()
{
forceZip64_ = true;
}
/// <summary>
/// Get a value indicating wether Zip64 extensions were forced.
/// </summary>
/// <returns>A <see cref="bool"/> value of true if Zip64 extensions have been forced on; false if not.</returns>
public bool IsZip64Forced()
{
return forceZip64_;
}
/// <summary>
/// Gets a value indicating if the entry requires Zip64 extensions
/// to store the full entry values.
/// </summary>
/// <value>A <see cref="bool"/> value of true if a local header requires Zip64 extensions; false if not.</value>
public bool LocalHeaderRequiresZip64 {
get {
bool result = forceZip64_;
if (!result) {
ulong trueCompressedSize = compressedSize;
if ((versionToExtract == 0) && IsCrypted) {
trueCompressedSize += ZipConstants.CryptoHeaderSize;
}
// TODO: A better estimation of the true limit based on compression overhead should be used
// to determine when an entry should use Zip64.
result =
((this.size >= uint.MaxValue) || (trueCompressedSize >= uint.MaxValue)) &&
((versionToExtract == 0) || (versionToExtract >= ZipConstants.VersionZip64));
}
return result;
}
}
/// <summary>
/// Get a value indicating wether the central directory entry requires Zip64 extensions to be stored.
/// </summary>
public bool CentralHeaderRequiresZip64 {
get {
return LocalHeaderRequiresZip64 || (offset >= uint.MaxValue);
}
}
/// <summary>
/// Get/Set DosTime value.
/// </summary>
/// <remarks>
/// The MS-DOS date format can only represent dates between 1/1/1980 and 12/31/2107.
/// </remarks>
public long DosTime {
get {
if ((known & Known.Time) == 0) {
return 0;
} else {
return dosTime;
}
}
set {
unchecked {
dosTime = (uint)value;
}
known |= Known.Time;
}
}
/// <summary>
/// Gets/Sets the time of last modification of the entry.
/// </summary>
/// <remarks>
/// The <see cref="DosTime"></see> property is updated to match this as far as possible.
/// </remarks>
public DateTime DateTime
{
get
{
uint sec = Math.Min(59, 2 * (dosTime & 0x1f));
uint min = Math.Min(59, (dosTime >> 5) & 0x3f);
uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f);
uint mon = Math.Max(1, Math.Min(12, ((dosTime >> 21) & 0xf)));
uint year = ((dosTime >> 25) & 0x7f) + 1980;
int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((dosTime >> 16) & 0x1f)));
return new System.DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec);
}
set {
var year = (uint)value.Year;
var month = (uint)value.Month;
var day = (uint)value.Day;
var hour = (uint)value.Hour;
var minute = (uint)value.Minute;
var second = (uint)value.Second;
if (year < 1980) {
year = 1980;
month = 1;
day = 1;
hour = 0;
minute = 0;
second = 0;
} else if (year > 2107) {
year = 2107;
month = 12;
day = 31;
hour = 23;
minute = 59;
second = 59;
}
DosTime = ((year - 1980) & 0x7f) << 25 |
(month << 21) |
(day << 16) |
(hour << 11) |
(minute << 5) |
(second >> 1);
}
}
/// <summary>
/// Returns the entry name.
/// </summary>
/// <remarks>
/// The unix naming convention is followed.
/// Path components in the entry should always separated by forward slashes ('/').
/// Dos device names like C: should also be removed.
/// See the <see cref="ZipNameTransform"/> class, or <see cref="CleanName(string)"/>
///</remarks>
public string Name {
get {
return name;
}
}
/// <summary>
/// Gets/Sets the size of the uncompressed data.
/// </summary>
/// <returns>
/// The size or -1 if unknown.
/// </returns>
/// <remarks>Setting the size before adding an entry to an archive can help
/// avoid compatability problems with some archivers which dont understand Zip64 extensions.</remarks>
public long Size {
get {
return (known & Known.Size) != 0 ? (long)size : -1L;
}
set {
this.size = (ulong)value;
this.known |= Known.Size;
}
}
/// <summary>
/// Gets/Sets the size of the compressed data.
/// </summary>
/// <returns>
/// The compressed entry size or -1 if unknown.
/// </returns>
public long CompressedSize {
get {
return (known & Known.CompressedSize) != 0 ? (long)compressedSize : -1L;
}
set {
this.compressedSize = (ulong)value;
this.known |= Known.CompressedSize;
}
}
/// <summary>
/// Gets/Sets the crc of the uncompressed data.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Crc is not in the range 0..0xffffffffL
/// </exception>
/// <returns>
/// The crc value or -1 if unknown.
/// </returns>
public long Crc {
get {
return (known & Known.Crc) != 0 ? crc & 0xffffffffL : -1L;
}
set {
if (((ulong)crc & 0xffffffff00000000L) != 0) {
throw new ArgumentOutOfRangeException(nameof(value));
}
this.crc = (uint)value;
this.known |= Known.Crc;
}
}
/// <summary>
/// Gets/Sets the compression method. Only Deflated and Stored are supported.
/// </summary>
/// <returns>
/// The compression method for this entry
/// </returns>
/// <see cref="ICSharpCode.SharpZipLib.Zip.CompressionMethod.ZStd"/>
/// <see cref="ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated"/>
/// <see cref="ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored"/>
public CompressionMethod CompressionMethod {
get {
return method;
}
set {
if (!IsCompressionMethodSupported(value)) {
throw new NotSupportedException("Compression method not supported");
}
this.method = value;
}
}
/// <summary>
/// Gets the compression method for outputting to the local or central header.
/// Returns same value as CompressionMethod except when AES encrypting, which
/// places 99 in the method and places the real method in the extra data.
/// </summary>
internal CompressionMethod CompressionMethodForHeader {
get {
return (AESKeySize > 0) ? CompressionMethod.WinZipAES : method;
}
}
/// <summary>
/// Gets/Sets the extra data.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Extra data is longer than 64KB (0xffff) bytes.
/// </exception>
/// <returns>
/// Extra data or null if not set.
/// </returns>
public byte[] ExtraData {
get {
// TODO: This is slightly safer but less efficient. Think about wether it should change.
// return (byte[]) extra.Clone();
return extra;
}
set {
if (value == null) {
extra = null;
} else {
if (value.Length > 0xffff) {
throw new System.ArgumentOutOfRangeException(nameof(value));
}
extra = new byte[value.Length];
Array.Copy(value, 0, extra, 0, value.Length);
}
}
}
/// <summary>
/// For AES encrypted files returns or sets the number of bits of encryption (128, 192 or 256).
/// When setting, only 0 (off), 128 or 256 is supported.
/// </summary>
public int AESKeySize {
get {
// the strength (1 or 3) is in the entry header
switch (_aesEncryptionStrength) {
case 0:
return 0; // Not AES
case 1:
return 128;
case 2:
return 192; // Not used by WinZip
case 3:
return 256;
default:
throw new ZipException("Invalid AESEncryptionStrength " + _aesEncryptionStrength);
}
}
set {
switch (value) {
case 0:
_aesEncryptionStrength = 0;
break;
case 128:
_aesEncryptionStrength = 1;
break;
case 256:
_aesEncryptionStrength = 3;
break;
default:
throw new ZipException("AESKeySize must be 0, 128 or 256: " + value);
}
}
}
/// <summary>
/// AES Encryption strength for storage in extra data in entry header.
/// 1 is 128 bit, 2 is 192 bit, 3 is 256 bit.
/// </summary>
internal byte AESEncryptionStrength {
get {
return (byte)_aesEncryptionStrength;
}
}
/// <summary>
/// Returns the length of the salt, in bytes
/// </summary>
internal int AESSaltLen {
get {
// Key size -> Salt length: 128 bits = 8 bytes, 192 bits = 12 bytes, 256 bits = 16 bytes.
return AESKeySize / 16;
}
}
/// <summary>
/// Number of extra bytes required to hold the AES Header fields (Salt, Pwd verify, AuthCode)
/// </summary>
internal int AESOverheadSize {
get {
// File format:
// Bytes Content
// Variable Salt value
// 2 Password verification value
// Variable Encrypted file data
// 10 Authentication code
return 12 + AESSaltLen;
}
}
/// <summary>
/// Process extra data fields updating the entry based on the contents.
/// </summary>
/// <param name="localHeader">True if the extra data fields should be handled
/// for a local header, rather than for a central header.
/// </param>
internal void ProcessExtraData(bool localHeader)
{
var extraData = new ZipExtraData(this.extra);
if (extraData.Find(0x0001)) {
// Version required to extract is ignored here as some archivers dont set it correctly
// in theory it should be version 45 or higher
// The recorded size will change but remember that this is zip64.
forceZip64_ = true;
if (extraData.ValueLength < 4) {
throw new ZipException("Extra data extended Zip64 information length is invalid");
}
// (localHeader ||) was deleted, because actually there is no specific difference with reading sizes between local header & central directory
// https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
// ...
// 4.4 Explanation of fields
// ...
// 4.4.8 compressed size: (4 bytes)
// 4.4.9 uncompressed size: (4 bytes)
//
// The size of the file compressed (4.4.8) and uncompressed,
// (4.4.9) respectively. When a decryption header is present it
// will be placed in front of the file data and the value of the
// compressed file size will include the bytes of the decryption
// header. If bit 3 of the general purpose bit flag is set,
// these fields are set to zero in the local header and the
// correct values are put in the data descriptor and
// in the central directory. If an archive is in ZIP64 format
// and the value in this field is 0xFFFFFFFF, the size will be
// in the corresponding 8 byte ZIP64 extended information
// extra field. When encrypting the central directory, if the
// local header is not in ZIP64 format and general purpose bit
// flag 13 is set indicating masking, the value stored for the
// uncompressed size in the Local Header will be zero.
//
// Othewise there is problem with minizip implementation
if (size == uint.MaxValue) {
size = (ulong)extraData.ReadLong();
}
if (compressedSize == uint.MaxValue) {
compressedSize = (ulong)extraData.ReadLong();
}
if (!localHeader && (offset == uint.MaxValue)) {
offset = extraData.ReadLong();
}
// Disk number on which file starts is ignored
} else {
if (
((versionToExtract & 0xff) >= ZipConstants.VersionZip64) &&
((size == uint.MaxValue) || (compressedSize == uint.MaxValue))
) {
throw new ZipException("Zip64 Extended information required but is missing.");
}
}
DateTime = GetDateTime(extraData);
if (method == CompressionMethod.WinZipAES) {
ProcessAESExtraData(extraData);
}
}
private DateTime GetDateTime(ZipExtraData extraData) {
// Check for NT timestamp
// NOTE: Disable by default to match behavior of InfoZIP
#if RESPECT_NT_TIMESTAMP
NTTaggedData ntData = extraData.GetData<NTTaggedData>();
if (ntData != null)
return ntData.LastModificationTime;
#endif
// Check for Unix timestamp
ExtendedUnixData unixData = extraData.GetData<ExtendedUnixData>();
if (unixData != null &&
// Only apply modification time, but require all other values to be present
// This is done to match InfoZIP's behaviour
((unixData.Include & ExtendedUnixData.Flags.ModificationTime) != 0) &&
((unixData.Include & ExtendedUnixData.Flags.AccessTime) != 0) &&
((unixData.Include & ExtendedUnixData.Flags.CreateTime) != 0))
return unixData.ModificationTime;
// Fall back to DOS time
uint sec = Math.Min(59, 2 * (dosTime & 0x1f));
uint min = Math.Min(59, (dosTime >> 5) & 0x3f);
uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f);
uint mon = Math.Max(1, Math.Min(12, ((dosTime >> 21) & 0xf)));
uint year = ((dosTime >> 25) & 0x7f) + 1980;
int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((dosTime >> 16) & 0x1f)));
return new DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec, DateTimeKind.Utc);
}
// For AES the method in the entry is 99, and the real compression method is in the extradata
//
private void ProcessAESExtraData(ZipExtraData extraData)
{
if (extraData.Find(0x9901)) {
// Set version and flag for Zipfile.CreateAndInitDecryptionStream
versionToExtract = ZipConstants.VERSION_AES; // Ver 5.1 = AES see "Version" getter
// Set StrongEncryption flag for ZipFile.CreateAndInitDecryptionStream
Flags = Flags | (int)GeneralBitFlags.StrongEncryption;
//
// Unpack AES extra data field see http://www.winzip.com/aes_info.htm
int length = extraData.ValueLength; // Data size currently 7
if (length < 7)
throw new ZipException("AES Extra Data Length " + length + " invalid.");
int ver = extraData.ReadShort(); // Version number (1=AE-1 2=AE-2)
int vendorId = extraData.ReadShort(); // 2-character vendor ID 0x4541 = "AE"
int encrStrength = extraData.ReadByte(); // encryption strength 1 = 128 2 = 192 3 = 256
int actualCompress = extraData.ReadShort(); // The actual compression method used to compress the file
_aesVer = ver;
_aesEncryptionStrength = encrStrength;
method = (CompressionMethod)actualCompress;
} else
throw new ZipException("AES Extra Data missing");
}
/// <summary>
/// Gets/Sets the entry comment.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// If comment is longer than 0xffff.
/// </exception>
/// <returns>
/// The comment or null if not set.
/// </returns>
/// <remarks>
/// A comment is only available for entries when read via the <see cref="ZipFile"/> class.
/// The <see cref="ZipInputStream"/> class doesnt have the comment data available.
/// </remarks>
public string Comment {
get {
return comment;
}
set {
// This test is strictly incorrect as the length is in characters
// while the storage limit is in bytes.
// While the test is partially correct in that a comment of this length or greater
// is definitely invalid, shorter comments may also have an invalid length
// where there are multi-byte characters
// The full test is not possible here however as the code page to apply conversions with
// isnt available.
if ((value != null) && (value.Length > 0xffff)) {
throw new ArgumentOutOfRangeException(nameof(value), "cannot exceed 65535");
}
comment = value;
}
}
/// <summary>
/// Gets a value indicating if the entry is a directory.
/// however.
/// </summary>
/// <remarks>
/// A directory is determined by an entry name with a trailing slash '/'.
/// The external file attributes can also indicate an entry is for a directory.
/// Currently only dos/windows attributes are tested in this manner.
/// The trailing slash convention should always be followed.
/// </remarks>
public bool IsDirectory {
get {
int nameLength = name.Length;
bool result =
((nameLength > 0) &&
((name[nameLength - 1] == '/') || (name[nameLength - 1] == '\\'))) ||
HasDosAttributes(16)
;
return result;
}
}
/// <summary>
/// Get a value of true if the entry appears to be a file; false otherwise
/// </summary>
/// <remarks>
/// This only takes account of DOS/Windows attributes. Other operating systems are ignored.
/// For linux and others the result may be incorrect.
/// </remarks>
public bool IsFile {
get {
return !IsDirectory && !HasDosAttributes(8);
}
}
public long HeaderOffset { get; internal set; }
/// <summary>
/// Test entry to see if data can be extracted.
/// </summary>
/// <returns>Returns true if data can be extracted for this entry; false otherwise.</returns>
public bool IsCompressionMethodSupported()
{
return IsCompressionMethodSupported(CompressionMethod);
}
#region ICloneable Members
/// <summary>
/// Creates a copy of this zip entry.
/// </summary>
/// <returns>An <see cref="Object"/> that is a copy of the current instance.</returns>
public object Clone()
{
var result = (ZipEntry)this.MemberwiseClone();
// Ensure extra data is unique if it exists.
if (extra != null) {
result.extra = new byte[extra.Length];
Array.Copy(extra, 0, result.extra, 0, extra.Length);
}
return result;
}
#endregion
/// <summary>
/// Gets a string representation of this ZipEntry.
/// </summary>
/// <returns>A readable textual representation of this <see cref="ZipEntry"/></returns>
public override string ToString()
{
return name;
}
/// <summary>
/// Test a <see cref="CompressionMethod">compression method</see> to see if this library
/// supports extracting data compressed with that method
/// </summary>
/// <param name="method">The compression method to test.</param>
/// <returns>Returns true if the compression method is supported; false otherwise</returns>
public static bool IsCompressionMethodSupported(CompressionMethod method)
{
return
(method == CompressionMethod.ZStd) ||
(method == CompressionMethod.Deflated) ||
(method == CompressionMethod.Stored);
}
/// <summary>
/// Cleans a name making it conform to Zip file conventions.
/// Devices names ('c:\') and UNC share names ('\\server\share') are removed
/// and forward slashes ('\') are converted to back slashes ('/').
/// Names are made relative by trimming leading slashes which is compatible
/// with the ZIP naming convention.
/// </summary>
/// <param name="name">The name to clean</param>
/// <returns>The 'cleaned' name.</returns>
/// <remarks>
/// The <seealso cref="ZipNameTransform">Zip name transform</seealso> class is more flexible.
/// </remarks>
public static string CleanName(string name)
{
if (name == null) {
return string.Empty;
}
if (Path.IsPathRooted(name)) {
// NOTE:
// for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt
name = name.Substring(Path.GetPathRoot(name).Length);
}
name = name.Replace(@"\", "/");
while ((name.Length > 0) && (name[0] == '/')) {
name = name.Remove(0, 1);
}
return name;
}
#region Instance Fields
Known known;
int externalFileAttributes = -1; // contains external attributes (O/S dependant)
ushort versionMadeBy; // Contains host system and version information
// only relevant for central header entries
string name;
ulong size;
ulong compressedSize;
ushort versionToExtract; // Version required to extract (library handles <= 2.0)
uint crc;
uint dosTime;
CompressionMethod method = CompressionMethod.Deflated;
byte[] extra;
string comment;
int flags; // general purpose bit flags
long zipFileIndex = -1; // used by ZipFile
long offset; // used by ZipFile and ZipOutputStream
bool forceZip64_;
byte cryptoCheckValue_;
int _aesVer; // Version number (2 = AE-2 ?). Assigned but not used.
int _aesEncryptionStrength; // Encryption strength 1 = 128 2 = 192 3 = 256
#endregion
}
}
| 30.636895 | 146 | 0.63142 | [
"MIT"
] | InX-Invader/unp4k | src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 36,703 | C# |
using System;
namespace AsterNET.FastAGI.Command
{
/// <summary>
/// Retrieves an entry in the Asterisk database for a given family and key.<br/>
/// Returns 0 if is not set. Returns 1 if the variable is set and returns the
/// value in parenthesis.<br/>
/// Example return code: 200 result=1 (testvariable)
/// </summary>
public class DatabaseGetCommand : AGICommand
{
/// <summary> The family of the key to retrieve.</summary>
private string family;
/// <summary> The key to retrieve.</summary>
private string varKey;
/// <summary>
/// Get/Set
/// </summary>
public string Family
{
get { return family; }
set { this.family = value; }
}
/// <summary>
/// Get/Set the the key to retrieve.
/// </summary>
public string Key
{
get { return varKey; }
set { this.varKey = value; }
}
/// <summary>
/// Creates a new DatabaseGetCommand.
/// </summary>
/// <param name="family">the family of the key to retrieve.</param>
/// <param name="key">the key to retrieve.</param>
public DatabaseGetCommand(string family, string key)
{
this.family = family;
this.varKey = key;
}
public override string BuildCommand()
{
return "DATABASE GET " + EscapeAndQuote(family) + " " + EscapeAndQuote(varKey);
}
}
} | 26.56 | 83 | 0.620482 | [
"MIT"
] | 1stco/AsterNET | Asterisk.2013/Asterisk.NET/FastAGI/Command/DatabaseGetCommand.cs | 1,328 | C# |
namespace ELSM_Project
{
partial class userDelete
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(userDelete));
this.btnCancel = new System.Windows.Forms.Button();
this.btnDeleteUser = new System.Windows.Forms.Button();
this.lblUserID = new System.Windows.Forms.Label();
this.cmboUserID = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// btnCancel
//
this.btnCancel.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.btnCancel.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnCancel.FlatAppearance.BorderSize = 0;
this.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnCancel.Font = new System.Drawing.Font("Raleway", 9.749999F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCancel.Location = new System.Drawing.Point(281, 84);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(207, 31);
this.btnCancel.TabIndex = 45;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = false;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnDeleteUser
//
this.btnDeleteUser.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.btnDeleteUser.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnDeleteUser.FlatAppearance.BorderSize = 0;
this.btnDeleteUser.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnDeleteUser.Font = new System.Drawing.Font("Raleway", 9.749999F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnDeleteUser.Location = new System.Drawing.Point(36, 84);
this.btnDeleteUser.Name = "btnDeleteUser";
this.btnDeleteUser.Size = new System.Drawing.Size(206, 31);
this.btnDeleteUser.TabIndex = 44;
this.btnDeleteUser.Text = "Process User Deletion";
this.btnDeleteUser.UseVisualStyleBackColor = false;
this.btnDeleteUser.Click += new System.EventHandler(this.btnDeleteUser_Click);
//
// lblUserID
//
this.lblUserID.AutoSize = true;
this.lblUserID.BackColor = System.Drawing.Color.Transparent;
this.lblUserID.Font = new System.Drawing.Font("Raleway", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblUserID.ForeColor = System.Drawing.SystemColors.ControlLightLight;
this.lblUserID.Location = new System.Drawing.Point(33, 34);
this.lblUserID.Name = "lblUserID";
this.lblUserID.Size = new System.Drawing.Size(62, 18);
this.lblUserID.TabIndex = 38;
this.lblUserID.Text = "User ID:";
//
// cmboUserID
//
this.cmboUserID.FormattingEnabled = true;
this.cmboUserID.Location = new System.Drawing.Point(178, 33);
this.cmboUserID.Name = "cmboUserID";
this.cmboUserID.Size = new System.Drawing.Size(310, 21);
this.cmboUserID.TabIndex = 46;
//
// userDelete
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = global::ELSM_Project.Properties.Resources.imgBackground;
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ClientSize = new System.Drawing.Size(528, 139);
this.ControlBox = false;
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnDeleteUser);
this.Controls.Add(this.lblUserID);
this.Controls.Add(this.cmboUserID);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximumSize = new System.Drawing.Size(544, 178);
this.MinimumSize = new System.Drawing.Size(544, 178);
this.Name = "userDelete";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Delete User";
this.Load += new System.EventHandler(this.manageUsersDelete_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnDeleteUser;
private System.Windows.Forms.Label lblUserID;
private System.Windows.Forms.ComboBox cmboUserID;
}
} | 49.091667 | 166 | 0.620268 | [
"MPL-2.0"
] | metallicgloss/Server-Management | ELSMProject/userDelete.Designer.cs | 5,893 | C# |
using ChamadoFacil.BusinessLogic.Chamado;
using ChamadoFacil.Models.Chamado;
using Microsoft.AspNetCore.Mvc;
namespace ChamadoFacil.ApplicationService.Controllers
{
[Route("[controller]")]
public class ChamadoController : Controller
{
private readonly IChamadoBll _chamadoBll;
public ChamadoController(IChamadoBll chamadoBll)
{
_chamadoBll = chamadoBll;
}
[HttpGet]
public ChamadoModel Get(int id)
{
return _chamadoBll.Selecionar(id);
}
[HttpPost]
public void Post([FromBody]ChamadoModel chamadoModel)
{
_chamadoBll.Salvar(chamadoModel);
}
}
} | 24 | 61 | 0.637931 | [
"MIT"
] | cpsilva/ChamadoFacil | ChamadoFacil/ChamadoFacil.ApplicationService/Controllers/ChamadoController.cs | 698 | C# |
#region BSD License
/*
*
* Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
* © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved.
*
* New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE)
* Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2021. All rights reserved.
*
*/
#endregion
namespace Krypton.Ribbon
{
/// <summary>
/// Represents a ribbon group color button.
/// </summary>
[ToolboxItem(false)]
[ToolboxBitmap(typeof(KryptonRibbonGroupColorButton), "ToolboxBitmaps.KryptonRibbonGroupColorButton.bmp")]
[Designer("Krypton.Ribbon.KryptonRibbonGroupColorButtonDesigner, Krypton.Ribbon")]
[DesignerCategory("code")]
[DesignTimeVisible(false)]
[DefaultEvent("SelectedColorChanged")]
[DefaultProperty("SelectedColor")]
public class KryptonRibbonGroupColorButton : KryptonRibbonGroupItem
{
#region Static Fields
private static readonly Image _defaultButtonImageSmall = Properties.Resources.ButtonColorImageSmall;
private static readonly Image _defaultButtonImageLarge = Properties.Resources.ButtonColorImageLarge;
#endregion
#region Instance Fields
private bool _enabled;
private bool _visible;
private bool _checked;
private bool _autoRecentColors;
private bool _visibleThemes;
private bool _visibleStandard;
private bool _visibleRecent;
private bool _visibleNoColor;
private bool _visibleMoreColors;
private Rectangle _selectedRectSmall;
private Rectangle _selectedRectLarge;
private Color _selectedColor;
private Color _emptyBorderColor;
private Image _imageSmall;
private Image _imageLarge;
private string _textLine1;
private string _textLine2;
private string _keyTip;
private GroupButtonType _buttonType;
private EventHandler _kcmFinishDelegate;
private GroupItemSize _itemSizeMax;
private GroupItemSize _itemSizeMin;
private GroupItemSize _itemSizeCurrent;
private ColorScheme _schemeThemes;
private ColorScheme _schemeStandard;
private KryptonCommand _command;
private int _maxRecentColors;
private readonly List<Color> _recentColors;
// Context menu items
private readonly KryptonContextMenu _kryptonContextMenu;
private readonly KryptonContextMenuSeparator _separatorTheme;
private readonly KryptonContextMenuSeparator _separatorStandard;
private readonly KryptonContextMenuSeparator _separatorRecent;
private readonly KryptonContextMenuHeading _headingTheme;
private readonly KryptonContextMenuHeading _headingStandard;
private readonly KryptonContextMenuHeading _headingRecent;
private readonly KryptonContextMenuColorColumns _colorsTheme;
private readonly KryptonContextMenuColorColumns _colorsStandard;
private readonly KryptonContextMenuColorColumns _colorsRecent;
private readonly KryptonContextMenuSeparator _separatorNoColor;
private readonly KryptonContextMenuItems _itemsNoColor;
private readonly KryptonContextMenuItem _itemNoColor;
private readonly KryptonContextMenuSeparator _separatorMoreColors;
private readonly KryptonContextMenuItems _itemsMoreColors;
private readonly KryptonContextMenuItem _itemMoreColors;
#endregion
#region Events
/// <summary>
/// Occurs when the color button is clicked.
/// </summary>
[Category("Ribbon")]
[Description("Occurs when the color button is clicked.")]
public event EventHandler Click;
/// <summary>
/// Occurs when the drop down color button type is pressed.
/// </summary>
[Category("Ribbon")]
[Description("Occurs when the drop down color button type is pressed.")]
public event EventHandler<ContextMenuArgs> DropDown;
/// <summary>
/// Occurs when the SelectedColor property changes value.
/// </summary>
[Category("Ribbon")]
[Description("Occurs when the SelectedColor property changes value.")]
public event EventHandler<ColorEventArgs> SelectedColorChanged;
/// <summary>
/// Occurs when the user is tracking over a color.
/// </summary>
[Category("Ribbon")]
[Description("Occurs when user is tracking over a color.")]
public event EventHandler<ColorEventArgs> TrackingColor;
/// <summary>
/// Occurs when the user selects the more colors option.
/// </summary>
[Category("Ribbon")]
[Description("Occurs when user selects the more colors option.")]
public event CancelEventHandler MoreColors;
/// <summary>
/// Occurs after the value of a property has changed.
/// </summary>
[Category("Ribbon")]
[Description("Occurs after the value of a property has changed.")]
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Occurs when the design time context menu is requested.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
public event MouseEventHandler DesignTimeContextMenu;
#endregion
#region Identity
/// <summary>
/// Initialise a new instance of the KryptonRibbonGroupColorButton class.
/// </summary>
public KryptonRibbonGroupColorButton()
{
// Default fields
_enabled = true;
_visible = true;
_checked = false;
_visibleThemes = true;
_visibleStandard = true;
_visibleRecent = true;
_visibleNoColor = true;
_visibleMoreColors = true;
_autoRecentColors = true;
ShortcutKeys = Keys.None;
_imageSmall = _defaultButtonImageSmall;
_imageLarge = _defaultButtonImageLarge;
_textLine1 = "Color";
_textLine2 = string.Empty;
_keyTip = "B";
_selectedColor = Color.Red;
_emptyBorderColor = Color.DarkGray;
_selectedRectSmall = new Rectangle(0, 12, 16, 4);
_selectedRectLarge = new Rectangle(2, 26, 28, 4);
_schemeThemes = ColorScheme.OfficeThemes;
_schemeStandard = ColorScheme.OfficeStandard;
_buttonType = GroupButtonType.Split;
_itemSizeMax = GroupItemSize.Large;
_itemSizeMin = GroupItemSize.Small;
_itemSizeCurrent = GroupItemSize.Large;
ToolTipImageTransparentColor = Color.Empty;
ToolTipTitle = string.Empty;
ToolTipBody = string.Empty;
ToolTipStyle = LabelStyle.SuperTip;
_maxRecentColors = 10;
_recentColors = new List<Color>();
// Create the context menu items
_kryptonContextMenu = new KryptonContextMenu();
_separatorTheme = new KryptonContextMenuSeparator();
_headingTheme = new KryptonContextMenuHeading("Theme Colors");
_colorsTheme = new KryptonContextMenuColorColumns(ColorScheme.OfficeThemes);
_separatorStandard = new KryptonContextMenuSeparator();
_headingStandard = new KryptonContextMenuHeading("Standard Colors");
_colorsStandard = new KryptonContextMenuColorColumns(ColorScheme.OfficeStandard);
_separatorRecent = new KryptonContextMenuSeparator();
_headingRecent = new KryptonContextMenuHeading("Recent Colors");
_colorsRecent = new KryptonContextMenuColorColumns(ColorScheme.None);
_separatorNoColor = new KryptonContextMenuSeparator();
_itemNoColor = new KryptonContextMenuItem("&No Color", Properties.Resources.ButtonNoColor, OnClickNoColor);
_itemsNoColor = new KryptonContextMenuItems();
_itemsNoColor.Items.Add(_itemNoColor);
_separatorMoreColors = new KryptonContextMenuSeparator();
_itemMoreColors = new KryptonContextMenuItem("&More Colors...", OnClickMoreColors);
_itemsMoreColors = new KryptonContextMenuItems();
_itemsMoreColors.Items.Add(_itemMoreColors);
_kryptonContextMenu.Items.AddRange(new KryptonContextMenuItemBase[] { _separatorTheme, _headingTheme, _colorsTheme,
_separatorStandard, _headingStandard, _colorsStandard,
_separatorRecent, _headingRecent, _colorsRecent,
_separatorNoColor, _itemsNoColor,
_separatorMoreColors, _itemsMoreColors});
}
#endregion
#region Public
/// <summary>
/// Gets and sets the selected color.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[Description("Selected color.")]
[DefaultValue(typeof(Color), "Red")]
public Color SelectedColor
{
get => _selectedColor;
set
{
if (value != _selectedColor)
{
_selectedColor = value;
UpdateRecentColors(_selectedColor);
OnSelectedColorChanged(_selectedColor);
OnPropertyChanged(nameof(SelectedColor));
}
}
}
/// <summary>
/// Gets and sets the selected color block when selected color is empty.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[Description("Border color of selected block when selected color is empty.")]
[DefaultValue(typeof(Color), "DarkGray")]
public Color EmptyBorderColor
{
get => _emptyBorderColor;
set
{
if (value != _emptyBorderColor)
{
_emptyBorderColor = value;
OnPropertyChanged(nameof(EmptyBorderColor));
}
}
}
/// <summary>
/// Gets and sets the selected color drawing rectangle when small.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[Description("Selected color drawing rectangle when small.")]
[DefaultValue(typeof(Rectangle), "0,12,16,4")]
public Rectangle SelectedRectSmall
{
get => _selectedRectSmall;
set
{
_selectedRectSmall = value;
OnPropertyChanged(nameof(SelectedRectSmall));
}
}
/// <summary>
/// Gets and sets the selected color drawing rectangle when large.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[Description("Selected color drawing rectangle when large.")]
[DefaultValue(typeof(Rectangle), "2, 26, 28, 4")]
public Rectangle SelectedRectLarge
{
get => _selectedRectLarge;
set
{
_selectedRectLarge = value;
OnPropertyChanged(nameof(SelectedRectLarge));
}
}
/// <summary>
/// Gets and sets the small color button image.
/// </summary>
[Bindable(true)]
[Localizable(true)]
[Category("Appearance")]
[Description("Small color button image.")]
[RefreshProperties(RefreshProperties.All)]
public Image ImageSmall
{
get => _imageSmall;
set
{
if (_imageSmall != value)
{
_imageSmall = value;
OnPropertyChanged(nameof(ImageSmall));
}
}
}
private bool ShouldSerializeImageSmall() => ImageSmall != _defaultButtonImageSmall;
/// <summary>
/// Gets and sets the large color button image.
/// </summary>
[Bindable(true)]
[Localizable(true)]
[Category("Appearance")]
[Description("Large color button image.")]
[RefreshProperties(RefreshProperties.All)]
public Image ImageLarge
{
get => _imageLarge;
set
{
if (_imageLarge != value)
{
_imageLarge = value;
OnPropertyChanged(nameof(ImageLarge));
}
}
}
private bool ShouldSerializeImageLarge() => ImageLarge != _defaultButtonImageLarge;
/// <summary>
/// Gets and sets the display text line 1 for color button.
/// </summary>
[Bindable(true)]
[Localizable(true)]
[Category("Appearance")]
[Description("Color button display text line 1.")]
[RefreshProperties(RefreshProperties.All)]
[DefaultValue("Color")]
public string TextLine1
{
get => _textLine1;
set
{
if (value != _textLine1)
{
_textLine1 = value;
OnPropertyChanged(nameof(TextLine1));
}
}
}
/// <summary>
/// Gets and sets the display text line 2 for the color button.
/// </summary>
[Bindable(true)]
[Localizable(true)]
[Category("Appearance")]
[Description("Color button display text line 2.")]
[RefreshProperties(RefreshProperties.All)]
[DefaultValue("")]
public string TextLine2
{
get => _textLine2;
set
{
if (value != _textLine2)
{
_textLine2 = value;
OnPropertyChanged(nameof(TextLine2));
}
}
}
/// <summary>
/// Gets and sets the key tip for the ribbon group color button.
/// </summary>
[Bindable(true)]
[Localizable(true)]
[Category("Appearance")]
[Description("Ribbon group color button key tip.")]
[DefaultValue("B")]
public string KeyTip
{
get => _keyTip;
set
{
if (string.IsNullOrEmpty(value))
{
value = "B";
}
_keyTip = value.ToUpper();
}
}
/// <summary>
/// Gets and sets the maximum number of recent colors to store and display.
/// </summary>
[Category("Behavior")]
[Description("Determine the maximum number of recent colors to store and display.")]
[DefaultValue(10)]
public int MaxRecentColors
{
get => _maxRecentColors;
set
{
if (value != _maxRecentColors)
{
_maxRecentColors = value;
OnPropertyChanged(nameof(MaxRecentColors));
}
}
}
/// <summary>
/// Gets and sets the visible state of the themes color set.
/// </summary>
[Category("Behavior")]
[Description("Determine the visible state of the themes color set.")]
[DefaultValue(true)]
public bool VisibleThemes
{
get => _visibleThemes;
set
{
if (value != _visibleThemes)
{
_visibleThemes = value;
OnPropertyChanged(nameof(VisibleThemes));
}
}
}
/// <summary>
/// Gets and sets the visible state of the standard color set.
/// </summary>
[Category("Behavior")]
[Description("Determine the visible state of the standard color set.")]
[DefaultValue(true)]
public bool VisibleStandard
{
get => _visibleStandard;
set
{
if (value != _visibleStandard)
{
_visibleStandard = value;
OnPropertyChanged(nameof(VisibleStandard));
}
}
}
/// <summary>
/// Gets and sets the visible state of the recent color set.
/// </summary>
[Category("Behavior")]
[Description("Determine the visible state of the recent color set.")]
[DefaultValue(true)]
public bool VisibleRecent
{
get => _visibleRecent;
set
{
if (value != _visibleRecent)
{
_visibleRecent = value;
OnPropertyChanged(nameof(VisibleRecent));
}
}
}
/// <summary>
/// Gets and sets the visible state of the no color menu item.
/// </summary>
[Category("Behavior")]
[Description("Determine if the 'No Color' menu item is used.")]
[DefaultValue(true)]
public bool VisibleNoColor
{
get => _visibleNoColor;
set
{
if (value != _visibleNoColor)
{
_visibleNoColor = value;
OnPropertyChanged(nameof(VisibleNoColor));
}
}
}
/// <summary>
/// Gets and sets the visible state of the more colors menu item.
/// </summary>
[Category("Behavior")]
[Description("Determine if the 'More Colors...' menu item is used.")]
[DefaultValue(true)]
public bool VisibleMoreColors
{
get => _visibleMoreColors;
set
{
if (value != _visibleMoreColors)
{
_visibleMoreColors = value;
OnPropertyChanged(nameof(VisibleMoreColors));
}
}
}
/// <summary>
/// Gets and sets if the recent colors should be automatically updated.
/// </summary>
[Category("Behavior")]
[Description("Should recent colors be automatically updated.")]
[DefaultValue(true)]
public bool AutoRecentColors
{
get => _autoRecentColors;
set
{
if (value != _autoRecentColors)
{
_autoRecentColors = value;
OnPropertyChanged(nameof(AutoRecentColors));
}
}
}
/// <summary>
/// Gets and sets the color scheme for the themes color set.
/// </summary>
[Category("Behavior")]
[Description("Color scheme to use for the themes color set.")]
[DefaultValue(typeof(ColorScheme), "OfficeThemes")]
public ColorScheme SchemeThemes
{
get => _schemeThemes;
set
{
if (value != _schemeThemes)
{
_schemeThemes = value;
OnPropertyChanged(nameof(SchemeThemes));
}
}
}
/// <summary>
/// Gets and sets the color scheme for the standard color set.
/// </summary>
[Category("Behavior")]
[Description("Color scheme to use for the standard color set.")]
[DefaultValue(typeof(ColorScheme), "OfficeStandard")]
public ColorScheme SchemeStandard
{
get => _schemeStandard;
set
{
if (value != _schemeStandard)
{
_schemeStandard = value;
OnPropertyChanged(nameof(SchemeStandard));
}
}
}
/// <summary>
/// Gets and sets the visible state of the color button.
/// </summary>
[Bindable(true)]
[Category("Behavior")]
[Description("Determines whether the color button is visible or hidden.")]
[DefaultValue(true)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override bool Visible
{
get => _visible;
set
{
if (value != _visible)
{
_visible = value;
OnPropertyChanged(nameof(Visible));
}
}
}
/// <summary>
/// Make the ribbon color button visible.
/// </summary>
public void Show()
{
Visible = true;
}
/// <summary>
/// Make the ribbon color button hidden.
/// </summary>
public void Hide()
{
Visible = false;
}
/// <summary>
/// Gets and sets the enabled state of the color button.
/// </summary>
[Bindable(true)]
[Category("Behavior")]
[Description("Determines whether the group color button is enabled.")]
[DefaultValue(true)]
public bool Enabled
{
get => _enabled;
set
{
if (value != _enabled)
{
_enabled = value;
OnPropertyChanged(nameof(Enabled));
}
}
}
/// <summary>
/// Gets and sets the checked state of the group button.
/// </summary>
[Bindable(true)]
[Category("Behavior")]
[Description("Determines whether the group color button is checked.")]
[DefaultValue(false)]
public bool Checked
{
get => _checked;
set
{
if (value != _checked)
{
_checked = value;
OnPropertyChanged(nameof(Checked));
}
}
}
/// <summary>
/// Gets and sets the operation of the group color button.
/// </summary>
[Bindable(true)]
[Category("Behavior")]
[Description("Determines how the group color button operation.")]
[DefaultValue(typeof(GroupButtonType), "Split")]
public GroupButtonType ButtonType
{
get => _buttonType;
set
{
if (value != _buttonType)
{
_buttonType = value;
OnPropertyChanged(nameof(ButtonType));
}
}
}
/// <summary>
/// Gets and sets the shortcut key combination.
/// </summary>
[Localizable(true)]
[Category("Behavior")]
[Description("Shortcut key combination to fire click event of the color button.")]
public Keys ShortcutKeys { get; set; }
private bool ShouldSerializeShortcutKeys() => (ShortcutKeys != Keys.None);
/// <summary>
/// Resets the ShortcutKeys property to its default value.
/// </summary>
public void ResetShortcutKeys()
{
ShortcutKeys = Keys.None;
}
/// <summary>
/// Gets and sets the tooltip label style for group color button.
/// </summary>
[Category("Appearance")]
[Description("Tooltip style for the group color button.")]
[DefaultValue(typeof(LabelStyle), "SuperTip")]
public LabelStyle ToolTipStyle { get; set; }
/// <summary>
/// Gets and sets the image for the item ToolTip.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[Description("Display image associated ToolTip.")]
[DefaultValue(null)]
[Localizable(true)]
public Image ToolTipImage { get; set; }
/// <summary>
/// Gets and sets the color to draw as transparent in the ToolTipImage.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[Description("Color to draw as transparent in the ToolTipImage.")]
[KryptonDefaultColor()]
[Localizable(true)]
public Color ToolTipImageTransparentColor { get; set; }
/// <summary>
/// Gets and sets the title text for the item ToolTip.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[Description("Title text for use in associated ToolTip.")]
[Editor("System.ComponentModel.Design.MultilineStringEditor", typeof(UITypeEditor))]
[DefaultValue("")]
[Localizable(true)]
public string ToolTipTitle { get; set; }
/// <summary>
/// Gets and sets the body text for the item ToolTip.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[Description("Body text for use in associated ToolTip.")]
[Editor("System.ComponentModel.Design.MultilineStringEditor", typeof(UITypeEditor))]
[DefaultValue("")]
[Localizable(true)]
public string ToolTipBody { get; set; }
/// <summary>
/// Gets and sets the set of recent colors.
/// </summary>
[Category("Appearance")]
[Description("Collection of recent colors.")]
public Color[] RecentColors
{
get => _recentColors.ToArray();
set
{
ClearRecentColors();
// You cannot add an empty collection
if (value != null)
{
_recentColors.AddRange(value);
}
}
}
/// <summary>
/// Clear the recent colors setting.
/// </summary>
public void ClearRecentColors()
{
_recentColors.Clear();
}
/// <summary>
/// Gets and sets the associated KryptonCommand.
/// </summary>
[Category("Behavior")]
[Description("Command associated with the color button.")]
[DefaultValue(null)]
public KryptonCommand KryptonCommand
{
get => _command;
set
{
if (_command != value)
{
if (_command != null)
{
_command.PropertyChanged -= OnCommandPropertyChanged;
}
_command = value;
OnPropertyChanged(nameof(KryptonCommand));
if (_command != null)
{
_command.PropertyChanged += OnCommandPropertyChanged;
}
}
}
}
/// <summary>
/// Gets and sets the maximum allowed size of the item.
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override GroupItemSize ItemSizeMaximum
{
get => _itemSizeMax;
set
{
if (_itemSizeMax != value)
{
_itemSizeMax = value;
OnPropertyChanged(nameof(ItemSizeMaximum));
}
}
}
/// <summary>
/// Gets and sets the minimum allowed size of the item.
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override GroupItemSize ItemSizeMinimum
{
get => _itemSizeMin;
set
{
if (_itemSizeMin != value)
{
_itemSizeMin = value;
OnPropertyChanged(nameof(ItemSizeMinimum));
}
}
}
/// <summary>
/// Gets and sets the current item size.
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override GroupItemSize ItemSizeCurrent
{
get => _itemSizeCurrent;
set
{
if (_itemSizeCurrent != value)
{
_itemSizeCurrent = value;
OnPropertyChanged(nameof(ItemSizeCurrent));
}
}
}
/// <summary>
/// Creates an appropriate view element for this item.
/// </summary>
/// <param name="ribbon">Reference to the owning ribbon control.</param>
/// <param name="needPaint">Delegate for notifying changes in display.</param>
/// <returns>ViewBase derived instance.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public override ViewBase CreateView(KryptonRibbon ribbon,
NeedPaintHandler needPaint) =>
new ViewDrawRibbonGroupColorButton(ribbon, this, needPaint);
/// <summary>
/// Generates a Click event for a button.
/// </summary>
public void PerformClick()
{
PerformClick(null);
}
/// <summary>
/// Generates a Click event for a button.
/// </summary>
/// <param name="finishDelegate">Delegate fired during event processing.</param>
public void PerformClick(EventHandler finishDelegate)
{
OnClick(finishDelegate);
}
/// <summary>
/// Generates a DropDown event for a button.
/// </summary>
public void PerformDropDown()
{
PerformDropDown(null);
}
/// <summary>
/// Generates a DropDown event for a button.
/// </summary>
/// <param name="finishDelegate">Delegate fired during event processing.</param>
public void PerformDropDown(EventHandler finishDelegate)
{
OnDropDown(finishDelegate);
}
/// <summary>
/// Internal design time properties.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
public ViewBase ColorButtonView { get; set; }
#endregion
#region Protected
/// <summary>
/// Handles a change in the property of an attached command.
/// </summary>
/// <param name="sender">Source of the event.</param>
/// <param name="e">A PropertyChangedEventArgs that contains the event data.</param>
protected virtual void OnCommandPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "TextLine1":
OnPropertyChanged(nameof(TextLine1));
break;
case "ExtraText":
OnPropertyChanged(nameof(TextLine2));
break;
case "ImageSmall":
OnPropertyChanged(nameof(ImageSmall));
break;
case "ImageLarge":
OnPropertyChanged(nameof(ImageLarge));
break;
case "Enabled":
OnPropertyChanged(nameof(Enabled));
break;
case "Checked":
OnPropertyChanged(nameof(Checked));
break;
default:
break;
}
}
/// <summary>
/// Raises the Click event.
/// </summary>
/// <param name="finishDelegate">Delegate fired during event processing.</param>
protected virtual void OnClick(EventHandler finishDelegate)
{
bool fireDelegate = true;
if (!Ribbon.InDesignMode)
{
// Events only occur when enabled
if (Enabled)
{
// A check button should always toggle state
if (ButtonType == GroupButtonType.Check)
{
// Push back the change to the attached command
if (KryptonCommand != null)
{
KryptonCommand.Checked = !KryptonCommand.Checked;
}
else
{
Checked = !Checked;
}
}
// In showing a popup we fire the delegate before the click so that the
// minimized popup is removed out of the way before the event is handled
// because if the event shows a dialog then it would appear behind the popup
if (VisualPopupManager.Singleton.CurrentPopup != null)
{
// Do we need to fire a delegate stating the click processing has finished?
if (fireDelegate)
{
finishDelegate?.Invoke(this, EventArgs.Empty);
}
fireDelegate = false;
}
// Generate actual click event
Click?.Invoke(this, EventArgs.Empty);
// Clicking the button should execute the associated command
KryptonCommand?.PerformExecute();
}
}
// Do we need to fire a delegate stating the click processing has finished?
if (fireDelegate)
{
finishDelegate?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Raises the DropDown event.
/// </summary>
/// <param name="finishDelegate">Delegate fired during event processing.</param>
protected virtual void OnDropDown(EventHandler finishDelegate)
{
bool fireDelegate = true;
if (!Ribbon.InDesignMode)
{
// Events only occur when enabled
if (Enabled)
{
if ((ButtonType == GroupButtonType.DropDown) ||
(ButtonType == GroupButtonType.Split))
{
if (_kryptonContextMenu != null)
{
UpdateContextMenu();
ContextMenuArgs contextArgs = new(_kryptonContextMenu);
// Generate an event giving a chance for the krypton context menu strip to
// be shown to be provided/modified or the action even to be cancelled
DropDown?.Invoke(this, contextArgs);
// If user did not cancel and there is still a krypton context menu strip to show
if (!contextArgs.Cancel && (contextArgs.KryptonContextMenu != null))
{
Rectangle screenRect = Rectangle.Empty;
// Convert the view for the button into screen coordinates
if ((Ribbon != null) && (ColorButtonView != null))
{
screenRect = Ribbon.ViewRectangleToScreen(ColorButtonView);
}
if (CommonHelper.ValidKryptonContextMenu(contextArgs.KryptonContextMenu))
{
// Cache the finish delegate to call when the menu is closed
_kcmFinishDelegate = finishDelegate;
// Decide which separators are needed
DecideOnVisible(_separatorTheme, _colorsTheme);
DecideOnVisible(_separatorStandard, _colorsStandard);
DecideOnVisible(_separatorRecent, _colorsRecent);
DecideOnVisible(_separatorNoColor, _itemsNoColor);
DecideOnVisible(_separatorMoreColors, _itemsMoreColors);
// Monitor relevant events inside the context menu
HookContextMenuEvents(_kryptonContextMenu.Items, true);
// Show at location we were provided, but need to convert to screen coordinates
contextArgs.KryptonContextMenu.Closed += OnKryptonContextMenuClosed;
if (contextArgs.KryptonContextMenu.Show(this, new Point(screenRect.X, screenRect.Bottom + 1)))
{
fireDelegate = false;
}
}
}
}
}
}
}
// Do we need to fire a delegate stating the click processing has finished?
if (fireDelegate)
{
finishDelegate?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Raises the SelectedColorChanged event.
/// </summary>
/// <param name="selectedColor">New selected color.</param>
protected virtual void OnSelectedColorChanged(Color selectedColor)
{
SelectedColorChanged?.Invoke(this, new ColorEventArgs(selectedColor));
}
/// <summary>
/// Raises the TrackingColor event.
/// </summary>
/// <param name="e">An ColorEventArgs that contains the event data.</param>
protected virtual void OnTrackingColor(ColorEventArgs e)
{
TrackingColor?.Invoke(this, e);
}
/// <summary>
/// Raises the MoreColors event.
/// </summary>
/// <param name="e">An CancelEventArgs that contains the event data.</param>
protected virtual void OnMoreColors(CancelEventArgs e)
{
MoreColors?.Invoke(this, e);
}
/// <summary>
/// Raises the PropertyChanged event.
/// </summary>
/// <param name="propertyName">Name of property that has changed.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
#region Internal
internal void OnDesignTimeContextMenu(MouseEventArgs e)
{
DesignTimeContextMenu?.Invoke(this, e);
}
internal override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// Only interested in key processing if this button definition
// is enabled and itself and all parents are also visible
if (Enabled && ChainVisible)
{
// Do we have a shortcut definition for ourself?
if (ShortcutKeys != Keys.None)
{
// Does it match the incoming key combination?
if (ShortcutKeys == keyData)
{
// Button type determines what event to fire
switch (ButtonType)
{
case GroupButtonType.Push:
case GroupButtonType.Check:
PerformClick();
return true;
case GroupButtonType.DropDown:
case GroupButtonType.Split:
PerformDropDown();
return true;
default:
// Should never happen!
Debug.Assert(false);
break;
}
return true;
}
}
// Check the types that have a relevant context menu strip
if ((ButtonType == GroupButtonType.DropDown) ||
(ButtonType == GroupButtonType.Split))
{
if (_kryptonContextMenu != null)
{
if (_kryptonContextMenu.ProcessShortcut(keyData))
{
return true;
}
}
}
}
return false;
}
internal override LabelStyle InternalToolTipStyle => ToolTipStyle;
internal override Image InternalToolTipImage => ToolTipImage;
internal override Color InternalToolTipImageTransparentColor => ToolTipImageTransparentColor;
internal override string InternalToolTipTitle => ToolTipTitle;
internal override string InternalToolTipBody => ToolTipBody;
#endregion
#region Implementation
private void HookContextMenuEvents(KryptonContextMenuCollection collection, bool hook)
{
// Search for items of interest
foreach (KryptonContextMenuItemBase item in collection)
{
// Hook into color events
if (item is KryptonContextMenuColorColumns columns)
{
columns.SelectedColor = _selectedColor;
if (hook)
{
columns.TrackingColor += OnColumnsTrackingColor;
columns.SelectedColorChanged += OnColumnsSelectedColorChanged;
}
else
{
columns.TrackingColor -= OnColumnsTrackingColor;
columns.SelectedColorChanged -= OnColumnsSelectedColorChanged;
}
}
}
}
private void UpdateRecentColors(Color color)
{
// Do we need to update the recent colors collection?
if (AutoRecentColors)
{
// We do not add to recent colors if it is inside another color columns
foreach (KryptonContextMenuItemBase item in _kryptonContextMenu.Items)
{
// Only interested in the non-recent colors color columns
if ((item != _colorsRecent) && (item is KryptonContextMenuColorColumns colors))
{
// Cast to correct type
// We do not change the theme or standard entries if they are not to be used
if (((item == _colorsTheme) && !VisibleThemes) ||
((item == _colorsStandard) && !VisibleStandard))
{
continue;
}
// If matching color found, do not add to recent colors
if (colors.ContainsColor(color))
{
return;
}
}
}
// If this color valid and so possible to become a recent color
if ((color != Color.Empty) && !color.Equals(Color.Empty))
{
bool found = false;
foreach (Color recentColor in _recentColors)
{
if (recentColor.Equals(color))
{
found = true;
break;
}
}
// If the color is not already part of the recent colors
if (!found)
{
// Add to start of the list
_recentColors.Insert(0, color);
// Enforce the maximum number of recent colors
if (_recentColors.Count > MaxRecentColors)
{
_recentColors.RemoveRange(MaxRecentColors, _recentColors.Count - MaxRecentColors);
}
}
}
}
}
private void UpdateContextMenu()
{
// Update visible state based of properties
_separatorTheme.Visible = _headingTheme.Visible = _colorsTheme.Visible = _visibleThemes;
_separatorStandard.Visible = _headingStandard.Visible = _colorsStandard.Visible = _visibleStandard;
_separatorRecent.Visible = _headingRecent.Visible = _colorsRecent.Visible = (_visibleRecent && (_recentColors.Count > 0));
_itemsNoColor.Visible = _visibleNoColor;
_itemsMoreColors.Visible = _visibleMoreColors;
// Define the display strings
_headingTheme.Text = Ribbon.RibbonStrings.ThemeColors;
_headingStandard.Text = Ribbon.RibbonStrings.StandardColors;
_headingRecent.Text = Ribbon.RibbonStrings.RecentColors;
_itemNoColor.Text = Ribbon.RibbonStrings.NoColor;
_itemMoreColors.Text = Ribbon.RibbonStrings.MoreColors;
// Define the colors used in the first two color schemes
_colorsTheme.ColorScheme = SchemeThemes;
_colorsStandard.ColorScheme = SchemeStandard;
// Define the recent colors
if (_recentColors.Count == 0)
{
_colorsRecent.SetCustomColors(null);
}
else
{
// Create an array of color arrays
Color[][] colors = new Color[_recentColors.Count][];
// Each column is just a single color
for (int i = 0; i < _recentColors.Count; i++)
{
colors[i] = new Color[] { _recentColors[i] };
}
_colorsRecent.SetCustomColors(colors);
}
// Should the no color entry be checked?
_itemNoColor.Checked = _selectedColor.Equals(Color.Empty);
}
private void DecideOnVisible(KryptonContextMenuItemBase visible, KryptonContextMenuItemBase target)
{
bool previous = false;
// Only search if the target itself is visible
if (target.Visible)
{
// Check all items before the target
foreach (KryptonContextMenuItemBase item in _kryptonContextMenu.Items)
{
// Finish when we reach the target
if (item == target)
{
break;
}
// We do not consider existing separators
if (!((item is KryptonContextMenuSeparator) ||
(item is KryptonContextMenuHeading)))
{
// If the previous item is visible, then make the parameter visible
if (item.Visible)
{
previous = true;
break;
}
}
}
}
visible.Visible = previous;
}
private void OnColumnsTrackingColor(object sender, ColorEventArgs e)
{
OnTrackingColor(new ColorEventArgs(e.Color));
}
private void OnColumnsSelectedColorChanged(object sender, ColorEventArgs e)
{
SelectedColor = e.Color;
}
private void OnClickNoColor(object sender, EventArgs e)
{
SelectedColor = Color.Empty;
}
private void OnClickMoreColors(object sender, EventArgs e)
{
// Give user a chance to cancel showing the standard more colors dialog
CancelEventArgs cea = new();
OnMoreColors(cea);
// If not instructed to cancel then...
if (!cea.Cancel)
{
// Use a standard color dialog for the selection of custom colors
ColorDialog cd = new()
{
Color = SelectedColor,
FullOpen = true
};
// Only if user selected a value do we want to use it
if (cd.ShowDialog() == DialogResult.OK)
{
SelectedColor = cd.Color;
}
}
}
private void OnKryptonContextMenuClosed(object sender, EventArgs e)
{
KryptonContextMenu kcm = (KryptonContextMenu)sender;
kcm.Closed -= OnKryptonContextMenuClosed;
// Fire any associated finish delegate
if (_kcmFinishDelegate != null)
{
_kcmFinishDelegate(this, e);
_kcmFinishDelegate = null;
}
// Unhook from item events
HookContextMenuEvents(_kryptonContextMenu.Items, false);
}
#endregion
}
}
| 35.542409 | 136 | 0.518349 | [
"BSD-3-Clause"
] | Krypton-Suite/Standard-Toolk | Source/Krypton Components/Krypton.Ribbon/Group Contents/KryptonRibbonGroupColorButton.cs | 49,869 | C# |
using System;
namespace Kooboo.Json
{
/// <summary>
/// 别名,标记于字段或属性上的特性
/// Alias,Characteristics marked on fields or property
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class AliasAttribute : Attribute
{
internal string _name { get; set; }
/// <summary>
/// Structural aliases
/// </summary>
/// <param name="name"></param>
public AliasAttribute(string name)
{
_name = name;
}
}
}
| 24 | 72 | 0.557971 | [
"MIT"
] | Kooboo/Json | Kooboo.Json/Attribute/AliasAttribute.cs | 582 | C# |
namespace OreonCinema.Application.Common.Exceptions
{
using System;
using System.Collections.Generic;
using System.Linq;
using FluentValidation.Results;
public class ModelValidationException : Exception
{
public ModelValidationException()
: base("One or more validation errors have occurred.")
=> this.Errors = new Dictionary<string, string[]>();
public ModelValidationException(IEnumerable<ValidationFailure> errors)
: this()
{
var failureGroups = errors
.GroupBy(e => e.PropertyName, e => e.ErrorMessage);
foreach (var failureGroup in failureGroups)
{
var propertyName = failureGroup.Key;
var propertyFailures = failureGroup.ToArray();
this.Errors.Add(propertyName, propertyFailures);
}
}
public IDictionary<string, string[]> Errors { get; }
}
}
| 30.3125 | 78 | 0.607216 | [
"MIT"
] | DimchoLakov/Domain-Driven-Design-with-ASP.NET-Core-Microservices | OreonCinema/OreonCinema.Application/Common/Exceptions/ModelValidationException.cs | 972 | C# |
using Sceelix.Annotations;
namespace Sceelix.Designer.Annotations
{
public class ApplicationSettingsAttribute : StringKeyAttribute
{
public ApplicationSettingsAttribute(string key) : base(key)
{
}
}
}
| 19.916667 | 67 | 0.690377 | [
"MIT"
] | IxxyXR/Sceelix | Source/Sceelix.Designer/Annotations/ApplicationSettingsAttribute.cs | 241 | C# |
namespace Barriot.Interaction.Modals
{
public class EvalModal : IModal
{
public string Title
=> "Evaluate or run a C# script.";
[InputLabel("Verification code")]
[ModalTextInput("code", TextInputStyle.Short)]
public string Verification { get; set; } = string.Empty;
[InputLabel("The script to run")]
[ModalTextInput("script", TextInputStyle.Paragraph, "Print(1);")]
public string Script { get; set; } = string.Empty;
[RequiredInput(false)]
[InputLabel("Additional usings")]
[ModalTextInput("usings", TextInputStyle.Short, "Discord, Discord.Rest", 0)]
public string Usings { get; set; } = string.Empty;
[RequiredInput(false)]
[InputLabel("Additional dll references")]
[ModalTextInput("references", TextInputStyle.Short, "Discord.Net.Core.dll, Discord.Net.Rest.dll")]
public string References { get; set; } = string.Empty;
}
}
| 36.074074 | 106 | 0.629363 | [
"MIT"
] | Rozen4334/Barriot | Barriot.Core/Interaction/Modals/Evaluation/EvalModal.cs | 976 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Request the system level data associated with Communication Barring.
/// The response is either a SystemCommunicationBarringGetResponse21sp1 or an ErrorResponse.
/// <see cref="SystemCommunicationBarringGetResponse21sp1"/>
/// <see cref="ErrorResponse"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""7f663d5135470c33ca64b0eed3c3aa0c:6072""}]")]
public class SystemCommunicationBarringGetRequest21sp1 : BroadWorksConnector.Ocip.Models.C.OCIRequest
{
}
}
| 34.458333 | 130 | 0.743652 | [
"MIT"
] | Rogn/broadworks-connector-net | BroadworksConnector/Ocip/Models/SystemCommunicationBarringGetRequest21sp1.cs | 827 | C# |
/*
* Copyright (c) 2000 World Wide Web Consortium,
* (Massachusetts Institute of Technology, Institut National de
* Recherche en Informatique et en Automatique, Keio University). All
* Rights Reserved. This program is distributed under the W3C's Software
* Intellectual Property License. This program is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE.
* See W3C License http://www.w3.org/Consortium/Legal/ for more details.
*/
using System;
namespace Comzept.Genesis.Tidy.Dom
{
/// <summary> The <code>Element</code> interface represents an element in an HTML or XML
/// document. Elements may have attributes associated with them; since the
/// <code>Element</code> interface inherits from <code>Node</code>, the
/// generic <code>Node</code> interface attribute <code>attributes</code> may
/// be used to retrieve the set of all attributes for an element. There are
/// methods on the <code>Element</code> interface to retrieve either an
/// <code>Attr</code> object by name or an attribute value by name. In XML,
/// where an attribute value may contain entity references, an
/// <code>Attr</code> object should be retrieved to examine the possibly
/// fairly complex sub-tree representing the attribute value. On the other
/// hand, in HTML, where all attributes have simple string values, methods to
/// directly access an attribute value can safely be used as a convenience.In
/// DOM Level 2, the method <code>normalize</code> is inherited from the
/// <code>Node</code> interface where it was moved.
/// <p>See also the <a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113'>Document Object Model (DOM) Level 2 Core Specification</a></p>.
/// </summary>
public interface Element:Node
{
/// <summary> The name of the element. For example, in:
/// <pre> <elementExample
/// id="demo"> ... </elementExample> , </pre>
/// <code>tagName</code> has
/// the value <code>"elementExample"</code>. Note that this is
/// case-preserving in XML, as are all of the operations of the DOM. The
/// HTML DOM returns the <code>tagName</code> of an HTML element in the
/// canonical uppercase form, regardless of the case in the source HTML
/// document.
/// </summary>
System.String TagName
{
get;
}
/// <summary> Retrieves an attribute value by name.</summary>
/// <param name="name">name of the attribute to retrieve.
/// </param>
/// <returns> The <code>Attr</code> value as a string, or the empty string
/// if that attribute does not have a specified or default value.
/// </returns>
System.String getAttribute(System.String name);
/// <summary> Adds a new attribute. If an attribute with that name is already present
/// in the element, its value is changed to be that of the value
/// parameter. This value is a simple string; it is not parsed as it is
/// being set. So any markup (such as syntax to be recognized as an
/// entity reference) is treated as literal text, and needs to be
/// appropriately escaped by the implementation when it is written out.
/// In order to assign an attribute value that contains entity
/// references, the user must create an <code>Attr</code> node plus any
/// <code>Text</code> and <code>EntityReference</code> nodes, build the
/// appropriate subtree, and use <code>setAttributeNode</code> to assign
/// it as the value of an attribute.
/// <br/>To set an attribute with a qualified name and namespace URI, use
/// the <code>setAttributeNS</code> method.
/// </summary>
/// <param name="name">name of the attribute to create or alter.
/// </param>
/// <param name="valueValue">to set in string form.
/// </param>
/// <exception cref="DOMException">INVALID_CHARACTER_ERR: Raised if the specified name contains an
/// illegal character.
/// <br/>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
/// </exception>
void setAttribute(System.String name, System.String value_Renamed);
/// <summary> Removes an attribute by name. If the removed attribute is known to have
/// a default value, an attribute immediately appears containing the
/// default value as well as the corresponding namespace URI, local name,
/// and prefix when applicable.
/// <br/>To remove an attribute by local name and namespace URI, use the
/// <code>removeAttributeNS</code> method.
/// </summary>
/// <param name="name">name of the attribute to remove.
/// </param>
/// <exception cref="DOMException">NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
/// </exception>
void removeAttribute(System.String name);
/// <summary> Retrieves an attribute node by name.
/// <br/>To retrieve an attribute node by qualified name and namespace URI,
/// use the <code>getAttributeNodeNS</code> method.
/// </summary>
/// <param name="name">name (<code>nodeName</code>) of the attribute to
/// retrieve.
/// </param>
/// <returns> The <code>Attr</code> node with the specified name (
/// <code>nodeName</code>) or <code>null</code> if there is no such
/// attribute.
/// </returns>
Attr getAttributeNode(System.String name);
/// <summary> Adds a new attribute node. If an attribute with that name (
/// <code>nodeName</code>) is already present in the element, it is
/// replaced by the new one.
/// <br/>To add a new attribute node with a qualified name and namespace
/// URI, use the <code>setAttributeNodeNS</code> method.
/// </summary>
/// <param name="newAttr"><code>Attr</code> node to add to the attribute list.
/// </param>
/// <returns> If the <code>newAttr</code> attribute replaces an existing
/// attribute, the replaced <code>Attr</code> node is returned,
/// otherwise <code>null</code> is returned.
/// </returns>
/// <exception cref="DOMException">WRONG_DOCUMENT_ERR: Raised if <code>newAttr</code> was created from a
/// different document than the one that created the element.
/// <br/>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
/// <br/>INUSE_ATTRIBUTE_ERR: Raised if <code>newAttr</code> is already an
/// attribute of another <code>Element</code> object. The DOM user must
/// explicitly clone <code>Attr</code> nodes to re-use them in other
/// elements.
/// </exception>
Attr setAttributeNode(Attr newAttr);
/// <summary> Removes the specified attribute node. If the removed <code>Attr</code>
/// has a default value it is immediately replaced. The replacing
/// attribute has the same namespace URI and local name, as well as the
/// original prefix, when applicable.
/// </summary>
/// <param name="oldAttr"><code>Attr</code> node to remove from the attribute
/// list.
/// </param>
/// <returns> The <code>Attr</code> node that was removed.
/// </returns>
/// <exception cref="DOMException">NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
/// <br/>NOT_FOUND_ERR: Raised if <code>oldAttr</code> is not an attribute
/// of the element.
/// </exception>
Attr removeAttributeNode(Attr oldAttr);
/// <summary> Returns a <code>NodeList</code> of all descendant <code>Elements</code>
/// with a given tag name, in the order in which they are encountered in
/// a preorder traversal of this <code>Element</code> tree.
/// </summary>
/// <param name="name">name of the tag to match on. The special value "*"
/// matches all tags.
/// </param>
/// <returns> A list of matching <code>Element</code> nodes.
/// </returns>
NodeList getElementsByTagName(System.String name);
/// <summary> Retrieves an attribute value by local name and namespace URI. HTML-only
/// DOM implementations do not need to implement this method.
/// </summary>
/// <param name="namespaceURI">namespace URI of the attribute to retrieve.
/// </param>
/// <param name="localName">local name of the attribute to retrieve.
/// </param>
/// <returns> The <code>Attr</code> value as a string, or the empty string
/// if that attribute does not have a specified or default value.
/// </returns>
/// <since> DOM Level 2
/// </since>
System.String getAttributeNS(System.String namespaceURI, System.String localName);
/// <summary> Adds a new attribute. If an attribute with the same local name and
/// namespace URI is already present on the element, its prefix is
/// changed to be the prefix part of the <code>qualifiedName</code>, and
/// its value is changed to be the <code>value</code> parameter. This
/// value is a simple string; it is not parsed as it is being set. So any
/// markup (such as syntax to be recognized as an entity reference) is
/// treated as literal text, and needs to be appropriately escaped by the
/// implementation when it is written out. In order to assign an
/// attribute value that contains entity references, the user must create
/// an <code>Attr</code> node plus any <code>Text</code> and
/// <code>EntityReference</code> nodes, build the appropriate subtree,
/// and use <code>setAttributeNodeNS</code> or
/// <code>setAttributeNode</code> to assign it as the value of an
/// attribute.
/// <br/>HTML-only DOM implementations do not need to implement this method.
/// </summary>
/// <param name="namespaceURI">namespace URI of the attribute to create or
/// alter.
/// </param>
/// <param name="qualifiedName">qualified name of the attribute to create or
/// alter.
/// </param>
/// <param name="value">value to set in string form.
/// </param>
/// <exception cref="DOMException">INVALID_CHARACTER_ERR: Raised if the specified qualified name
/// contains an illegal character.
/// <br/>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
/// <br/>NAMESPACE_ERR: Raised if the <code>qualifiedName</code> is
/// malformed, if the <code>qualifiedName</code> has a prefix and the
/// <code>namespaceURI</code> is <code>null</code>, if the
/// <code>qualifiedName</code> has a prefix that is "xml" and the
/// <code>namespaceURI</code> is different from "
/// http://www.w3.org/XML/1998/namespace", or if the
/// <code>qualifiedName</code> is "xmlns" and the
/// <code>namespaceURI</code> is different from "
/// http://www.w3.org/2000/xmlns/".
/// </exception>
/// <since> DOM Level 2
/// </since>
void setAttributeNS(System.String namespaceURI, System.String qualifiedName, System.String value_Renamed);
/// <summary> Removes an attribute by local name and namespace URI. If the removed
/// attribute has a default value it is immediately replaced. The
/// replacing attribute has the same namespace URI and local name, as
/// well as the original prefix.
/// <br/>HTML-only DOM implementations do not need to implement this method.
/// </summary>
/// <param name="namespaceURI">namespace URI of the attribute to remove.
/// </param>
/// <param name="localName">local name of the attribute to remove.
/// </param>
/// <exception cref="DOMException">NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
/// </exception>
/// <since> DOM Level 2
/// </since>
void removeAttributeNS(System.String namespaceURI, System.String localName);
/// <summary> Retrieves an <code>Attr</code> node by local name and namespace URI.
/// HTML-only DOM implementations do not need to implement this method.
/// </summary>
/// <param name="namespaceURI">namespace URI of the attribute to retrieve.
/// </param>
/// <param name="localName">local name of the attribute to retrieve.
/// </param>
/// <returns> The <code>Attr</code> node with the specified attribute local
/// name and namespace URI or <code>null</code> if there is no such
/// attribute.
/// </returns>
/// <since> DOM Level 2
/// </since>
Attr getAttributeNodeNS(System.String namespaceURI, System.String localName);
/// <summary> Adds a new attribute. If an attribute with that local name and that
/// namespace URI is already present in the element, it is replaced by
/// the new one.
/// <br/>HTML-only DOM implementations do not need to implement this method.
/// </summary>
/// <param name="newAttr"><code>Attr</code> node to add to the attribute list.
/// </param>
/// <returns> If the <code>newAttr</code> attribute replaces an existing
/// attribute with the same local name and namespace URI, the replaced
/// <code>Attr</code> node is returned, otherwise <code>null</code> is
/// returned.
/// </returns>
/// <exception cref="DOMException">WRONG_DOCUMENT_ERR: Raised if <code>newAttr</code> was created from a
/// different document than the one that created the element.
/// <br/>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
/// <br/>INUSE_ATTRIBUTE_ERR: Raised if <code>newAttr</code> is already an
/// attribute of another <code>Element</code> object. The DOM user must
/// explicitly clone <code>Attr</code> nodes to re-use them in other
/// elements.
/// </exception>
/// <since> DOM Level 2
/// </since>
Attr setAttributeNodeNS(Attr newAttr);
/// <summary> Returns a <code>NodeList</code> of all the descendant
/// <code>Elements</code> with a given local name and namespace URI in
/// the order in which they are encountered in a preorder traversal of
/// this <code>Element</code> tree.
/// <br/>HTML-only DOM implementations do not need to implement this method.
/// </summary>
/// <param name="namespaceURI">namespace URI of the elements to match on. The
/// special value "*" matches all namespaces.
/// </param>
/// <param name="localName">local name of the elements to match on. The
/// special value "*" matches all local names.
/// </param>
/// <returns> A new <code>NodeList</code> object containing all the matched
/// <code>Elements</code>.
/// </returns>
/// <since> DOM Level 2
/// </since>
NodeList getElementsByTagNameNS(System.String namespaceURI, System.String localName);
/// <summary> Returns <code>true</code> when an attribute with a given name is
/// specified on this element or has a default value, <code>false</code>
/// otherwise.
/// </summary>
/// <param name="name">name of the attribute to look for.
/// </param>
/// <returns> <code>true</code> if an attribute with the given name is
/// specified on this element or has a default value, <code>false</code>
/// otherwise.
/// </returns>
/// <since> DOM Level 2
/// </since>
bool hasAttribute(System.String name);
/// <summary> Returns <code>true</code> when an attribute with a given local name and
/// namespace URI is specified on this element or has a default value,
/// <code>false</code> otherwise. HTML-only DOM implementations do not
/// need to implement this method.
/// </summary>
/// <param name="namespaceURI">namespace URI of the attribute to look for.
/// </param>
/// <param name="localName">local name of the attribute to look for.
/// </param>
/// <returns> <code>true</code> if an attribute with the given local name
/// and namespace URI is specified or has a default value on this
/// element, <code>false</code> otherwise.
/// </returns>
/// <since> DOM Level 2
/// </since>
bool hasAttributeNS(System.String namespaceURI, System.String localName);
}
} | 48.845426 | 150 | 0.686838 | [
"MIT"
] | andydunkel/netrix | Netrix2.0/PlugIns/TidySharp/W3C/Dom/Element.cs | 15,484 | C# |
using Autofac;
using Microsoft.AspNetCore.Mvc;
namespace BCVP.Extensions
{
public class AutofacPropertityModuleReg : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
var controllerBaseType = typeof(ControllerBase);
builder.RegisterAssemblyTypes(typeof(Program).Assembly)
.Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
.PropertiesAutowired();
}
}
}
| 27.777778 | 94 | 0.658 | [
"Apache-2.0"
] | hottoy/BCVP.OA | BCVP.Api/Filter/AutofacPropertityModuleReg.cs | 502 | C# |
using MoreLinq;
using OpenMod.Core.Helpers;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace OpenMod.Extensions.Games.Abstractions.Items
{
public static class ItemDirectoryExtensions
{
/// <summary>
/// Searches for items by the item asset id.
/// </summary>
/// <param name="directory">The item directory service.</param>
/// <param name="itemAssetId">The item asset id to search for.</param>
/// <returns><b>The <see cref="IItemAsset"/></b> if found; otherwise, <b>null</b>.</returns>
public static async Task<IItemAsset?> FindByIdAsync(this IItemDirectory directory, string itemAssetId)
{
return (await directory.GetItemAssetsAsync())
.FirstOrDefault(d => d.ItemAssetId.Equals(itemAssetId, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Searches for items by the item asset name.
/// </summary>
/// <param name="directory">The item directory service.</param>
/// <param name="itemName">The name of the item asset.</param>
/// <param name="exact">If true, only exact name matches will be used.</param>
/// <returns><b>The <see cref="IItemAsset"/></b> if found; otherwise, <b>null</b>.</returns>
public static async Task<IItemAsset?> FindByNameAsync(this IItemDirectory directory, string itemName, bool exact = true)
{
if (exact)
return (await directory.GetItemAssetsAsync()).FirstOrDefault(d =>
d.ItemName.Equals(itemName, StringComparison.OrdinalIgnoreCase));
return (await directory.GetItemAssetsAsync())
.Where(x => x.ItemName.IndexOf(itemName, StringComparison.OrdinalIgnoreCase) >= 0)
.MinBy(asset => StringHelper.LevenshteinDistance(itemName, asset.ItemName))
.FirstOrDefault();
}
}
} | 45.97619 | 128 | 0.632833 | [
"MIT"
] | 01-Feli/openmod | extensions/OpenMod.Extensions.Games.Abstractions/Items/ItemDirectoryExtensions.cs | 1,933 | C# |
// OData .NET Libraries
// 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
// 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 Microsoft.Spatial
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
/// <summary>Represents the base class for all Spatial Formats.</summary>
/// <typeparam name="TReaderStream">The type of reader to be read from.</typeparam>
/// <typeparam name="TWriterStream">The type of reader to be read from.</typeparam>
public abstract class SpatialFormatter<TReaderStream, TWriterStream>
{
/// <summary>
/// The implementation that created this instance.
/// </summary>
private readonly SpatialImplementation creator;
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.Spatial.SpatialFormatter`2" /> class. </summary>
/// <param name="creator">The implementation that created this instance.</param>
protected SpatialFormatter(SpatialImplementation creator)
{
Util.CheckArgumentNull(creator, "creator");
this.creator = creator;
}
/// <summary> Parses the input, and produces the object.</summary>
/// <returns>The input.</returns>
/// <param name="input">The input to be parsed.</param>
/// <typeparam name="TResult">The type of object to produce.</typeparam>
public TResult Read<TResult>(TReaderStream input) where TResult : class, ISpatial
{
var trans = MakeValidatingBuilder();
IShapeProvider parsePipelineEnd = trans.Value;
Read<TResult>(input, trans.Key);
if (typeof(Geometry).IsAssignableFrom(typeof(TResult)))
{
return (TResult)(object)parsePipelineEnd.ConstructedGeometry;
}
else
{
return (TResult)(object)parsePipelineEnd.ConstructedGeography;
}
}
/// <summary> Parses the input, and produces the object.</summary>
/// <param name="input">The input to be parsed.</param>
/// <param name="pipeline">The pipeline to call during reading.</param>
/// <typeparam name="TResult">The type of object to produce.</typeparam>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "The type hierarchy is too deep to have a specificly typed Read for each of them.")]
public void Read<TResult>(TReaderStream input, SpatialPipeline pipeline) where TResult : class, ISpatial
{
if (typeof(Geometry).IsAssignableFrom(typeof(TResult)))
{
ReadGeometry(input, pipeline);
}
else
{
ReadGeography(input, pipeline);
}
}
/// <summary> Creates a valid format from the spatial object.</summary>
/// <param name="spatial">The object that the format is being created for.</param>
/// <param name="writerStream">The stream to write the formatted object to.</param>
public void Write(ISpatial spatial, TWriterStream writerStream)
{
var writer = this.CreateWriter(writerStream);
spatial.SendTo(writer);
}
/// <summary> Creates the writerStream. </summary>
/// <returns>The writerStream that was created.</returns>
/// <param name="writerStream">The stream that should be written to.</param>
public abstract SpatialPipeline CreateWriter(TWriterStream writerStream);
/// <summary> Reads the Geography from the readerStream and call the appropriate pipeline methods.</summary>
/// <param name="readerStream">The stream to read from.</param>
/// <param name="pipeline">The pipeline to call based on what is read.</param>
protected abstract void ReadGeography(TReaderStream readerStream, SpatialPipeline pipeline);
/// <summary> Reads the Geometry from the readerStream and call the appropriate pipeline methods.</summary>
/// <param name="readerStream">The stream to read from.</param>
/// <param name="pipeline">The pipeline to call based on what is read.</param>
protected abstract void ReadGeometry(TReaderStream readerStream, SpatialPipeline pipeline);
/// <summary> Creates the builder that will be called by the parser to build the new type. </summary>
/// <returns>The builder that was created.</returns>
protected KeyValuePair<SpatialPipeline, IShapeProvider> MakeValidatingBuilder()
{
var builder = this.creator.CreateBuilder();
var validator = this.creator.CreateValidator();
validator.ChainTo(builder);
return new KeyValuePair<SpatialPipeline, IShapeProvider>(validator, builder);
}
}
}
| 49.072727 | 196 | 0.655984 | [
"Apache-2.0"
] | manukahn/odata.net | src/Spatial/Microsoft/Spatial/SpatialFormatter.cs | 5,398 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Tools;
public class FixSound : FixObserver {
public AudioClip fixedSound;
public AudioClip badFixedSound;
private AudioSource audioSource;
private new void Awake() {
base.Awake();
audioSource = FindObjectOfType<AudioSource>();
}
public override void OnFix(ToolEnum tool) {
if (tool == toolComp.tool) {
if (toolInv.values[toolComp.tool] > 0)
audioSource.PlayOneShot(fixedSound);
else
audioSource.PlayOneShot(badFixedSound);
}
}
}
| 23.714286 | 56 | 0.612952 | [
"MIT"
] | danjfreit/manic-mansion | ManicMansion/Assets/Scripts/NewScripts/FixSound.cs | 666 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Azure.SignalR.Management
{
internal static class TaskExtensions
{
private static readonly TimeSpan _defaultTimeout = TimeSpan.FromMinutes(5);
public static async Task OrTimeout(this Task task, CancellationToken cancellationToken)
{
if (cancellationToken == default)
{
using (CancellationTokenSource cts = new CancellationTokenSource(_defaultTimeout))
{
await task.OrTimeoutCore(cts.Token);
}
}
else
{
await task.OrTimeoutCore(cancellationToken);
}
}
private static async Task OrTimeoutCore(this Task task, CancellationToken cancellationToken)
{
if (task.IsCompleted)
{
await task;
return;
}
var completed = await Task.WhenAny(task, Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken));
if (completed != task)
{
throw new TimeoutException("Operation timed out");
}
}
}
}
| 29.119048 | 110 | 0.564186 | [
"MIT"
] | BlarghLabs/azure-signalr | src/Microsoft.Azure.SignalR.Management/TaskExtensions.cs | 1,225 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace Microsoft.AspNetCore.Testing;
internal sealed class AspNetTestClassRunner : XunitTestClassRunner
{
public AspNetTestClassRunner(
ITestClass testClass,
IReflectionTypeInfo @class,
IEnumerable<IXunitTestCase> testCases,
IMessageSink diagnosticMessageSink,
IMessageBus messageBus,
ITestCaseOrderer testCaseOrderer,
ExceptionAggregator aggregator,
CancellationTokenSource cancellationTokenSource,
IDictionary<Type, object> collectionFixtureMappings)
: base(testClass, @class, testCases, diagnosticMessageSink, messageBus, testCaseOrderer, aggregator, cancellationTokenSource, collectionFixtureMappings)
{
}
protected override Task<RunSummary> RunTestMethodAsync(ITestMethod testMethod, IReflectionMethodInfo method, IEnumerable<IXunitTestCase> testCases, object[] constructorArguments)
{
var runner = new AspNetTestMethodRunner(
testMethod,
Class,
method,
testCases,
DiagnosticMessageSink,
MessageBus,
new ExceptionAggregator(Aggregator),
CancellationTokenSource,
constructorArguments);
return runner.RunAsync();
}
}
| 34.931818 | 182 | 0.720885 | [
"MIT"
] | Akarachudra/kontur-aspnetcore-fork | src/Testing/src/xunit/AspNetTestClassRunner.cs | 1,537 | C# |
namespace ClassLib008
{
public class Class039
{
public static string Property => "ClassLib008";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib008/Class039.cs | 120 | C# |
using System.Collections.Generic;
using System.Linq;
using CrossPlatform.Code.Enums;
namespace CrossPlatform.Code.Utils
{
public static class PackUtils
{
public record PackInfo(
FileType FileType,
string InitialFilesExt,
string ConvertedFilesExt
);
public const int LatestPackStructureVersion = 17;
public const int DefaultAuthorIconHeight = 70;
public const string PacksExtension = ".tl";
public const string PacksActualExtension = ".zip";
public const string PackFileConfigExtension = ".json";
public static IReadOnlyList<PackInfo> PacksInfo { get; }
public static IReadOnlyList<string> TranslationLanguages { get; }
public static IReadOnlyList<string> TranslationLanguageTitles { get; }
static PackUtils()
{
const int _ = 1 / (7 / (int) FileType.LastEnumElement);
PacksInfo = new PackInfo[]
{
new(FileType.Texture, ".png", ".texture"),
new(FileType.Map, ".wld", ".world"),
new(FileType.Character, ".plr", ".character"),
new(FileType.Gui, ".png", ".gui"),
new(FileType.Translation, ".json", ".translation"),
new(FileType.Font, ".png", ".font"),
new(FileType.Audio, ".mp3", ".audio")
};
TranslationLanguages = new[] { "en-US", "de-DE", "it-IT", "fr-FR", "es-ES", "ru-RU", "pt-BR", /*"zh-Hans", "pl-PL", "ja-JP"*/ };
TranslationLanguageTitles = new[] { "English", "Deutsch", "Italiano", "Français", "Español", "Русский", "Português brasileiro" };
}
public static string GetInitialFilesExt(FileType fileType)
{
return PacksInfo.First(it => it.FileType == fileType).InitialFilesExt;
}
public static string GetConvertedFilesExt(FileType fileType)
{
return PacksInfo.First(it => it.FileType == fileType).ConvertedFilesExt;
}
}
}
| 39.222222 | 141 | 0.564212 | [
"MIT"
] | And42/TerrLauncherPackCreator | CrossPlatform/Code/Utils/PackUtils.cs | 2,130 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support
{
/// <summary>SKU size.</summary>
public partial struct SkuSize :
System.IEquatable<SkuSize>
{
public static Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support.SkuSize ExtraSmall = @"Extra small";
public static Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support.SkuSize Large = @"Large";
public static Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support.SkuSize Medium = @"Medium";
public static Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support.SkuSize Small = @"Small";
/// <summary>the value for an instance of the <see cref="SkuSize" /> Enum.</summary>
private string _value { get; set; }
/// <summary>Conversion from arbitrary object to SkuSize</summary>
/// <param name="value">the value to convert to an instance of <see cref="SkuSize" />.</param>
internal static object CreateFrom(object value)
{
return new SkuSize(global::System.Convert.ToString(value));
}
/// <summary>Compares values of enum type SkuSize</summary>
/// <param name="e">the value to compare against this instance.</param>
/// <returns><c>true</c> if the two instances are equal to the same value</returns>
public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support.SkuSize e)
{
return _value.Equals(e._value);
}
/// <summary>Compares values of enum type SkuSize (override for Object)</summary>
/// <param name="obj">the value to compare against this instance.</param>
/// <returns><c>true</c> if the two instances are equal to the same value</returns>
public override bool Equals(object obj)
{
return obj is SkuSize && Equals((SkuSize)obj);
}
/// <summary>Returns hashCode for enum SkuSize</summary>
/// <returns>The hashCode of the value</returns>
public override int GetHashCode()
{
return this._value.GetHashCode();
}
/// <summary>Creates an instance of the <see cref="SkuSize" Enum class./></summary>
/// <param name="underlyingValue">the value to create an instance for.</param>
private SkuSize(string underlyingValue)
{
this._value = underlyingValue;
}
/// <summary>Returns string representation for SkuSize</summary>
/// <returns>A string for this value.</returns>
public override string ToString()
{
return this._value;
}
/// <summary>Implicit operator to convert string to SkuSize</summary>
/// <param name="value">the value to convert to an instance of <see cref="SkuSize" />.</param>
public static implicit operator SkuSize(string value)
{
return new SkuSize(value);
}
/// <summary>Implicit operator to convert SkuSize to string</summary>
/// <param name="e">the value to convert to an instance of <see cref="SkuSize" />.</param>
public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support.SkuSize e)
{
return e._value;
}
/// <summary>Overriding != operator for enum SkuSize</summary>
/// <param name="e1">the value to compare against <see cref="e2" /></param>
/// <param name="e2">the value to compare against <see cref="e1" /></param>
/// <returns><c>true</c> if the two instances are not equal to the same value</returns>
public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support.SkuSize e1, Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support.SkuSize e2)
{
return !e2.Equals(e1);
}
/// <summary>Overriding == operator for enum SkuSize</summary>
/// <param name="e1">the value to compare against <see cref="e2" /></param>
/// <param name="e2">the value to compare against <see cref="e1" /></param>
/// <returns><c>true</c> if the two instances are equal to the same value</returns>
public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support.SkuSize e1, Microsoft.Azure.PowerShell.Cmdlets.Synapse.Support.SkuSize e2)
{
return e2.Equals(e1);
}
}
} | 46.529412 | 165 | 0.629583 | [
"MIT"
] | Agazoth/azure-powershell | src/Synapse/Synapse.Autorest/generated/api/Support/SkuSize.cs | 4,645 | C# |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// 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 Castle.Core
{
using System;
/// <summary>
/// Associates a custom activator with a component
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public sealed class ComponentActivatorAttribute : Attribute
{
private readonly Type componentActivatorType;
/// <summary>
/// Initializes a new instance of the <see cref = "ComponentActivatorAttribute" /> class.
/// </summary>
/// <param name = "componentActivatorType">Type of the component activator.</param>
public ComponentActivatorAttribute(Type componentActivatorType)
{
this.componentActivatorType = componentActivatorType;
}
/// <summary>
/// Gets the type of the component activator.
/// </summary>
/// <value>The type of the component activator.</value>
public Type ComponentActivatorType
{
get { return componentActivatorType; }
}
}
} | 34.577778 | 94 | 0.708226 | [
"Apache-2.0"
] | castleproject-deprecated/Castle.Windsor-READONLY | src/Castle.Windsor/Core/ComponentActivatorAttribute.cs | 1,556 | C# |
/****************************** Module Header ******************************\
Module Name: NativeMethod.cs
Project: CSUACSelfElevation
Copyright (c) Microsoft Corporation.
The P/Invoke signature some native Windows APIs used by the code sample.
This source is subject to the Microsoft Public License.
See http://www.microsoft.com/en-us/openness/resources/licenses.aspx#MPL
All other rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
// ReSharper disable InconsistentNaming
namespace TruckRemoteServer.Helpers
{
static class Uac
{
public static void RestartElevated()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
string processFileName = Process.GetCurrentProcess().MainModule.FileName;
// ReSharper disable once AssignNullToNotNullAttribute
startInfo.WorkingDirectory = Path.GetDirectoryName(processFileName);
startInfo.FileName = processFileName;
startInfo.Verb = "runas";
startInfo.Arguments = Environment.CommandLine.Substring(
Environment.CommandLine.IndexOf(' '));
Process.Start(startInfo);
}
/// <summary>
/// The function gets the elevation information of the current process. It
/// dictates whether the process is elevated or not. Token elevation is only
/// available on Windows Vista and newer operating systems, thus
/// IsProcessElevated throws a C++ exception if it is called on systems prior
/// to Windows Vista. It is not appropriate to use this function to determine
/// whether a process is run as administartor.
/// </summary>
/// <returns>
/// Returns true if the process is elevated. Returns false if it is not.
/// </returns>
/// <exception cref="System.ComponentModel.Win32Exception">
/// When any native Windows API call fails, the function throws a Win32Exception
/// with the last error code.
/// </exception>
/// <remarks>
/// TOKEN_INFORMATION_CLASS provides TokenElevationType to check the elevation
/// type (TokenElevationTypeDefault / TokenElevationTypeLimited /
/// TokenElevationTypeFull) of the process. It is different from TokenElevation
/// in that, when UAC is turned off, elevation type always returns
/// TokenElevationTypeDefault even though the process is elevated (Integrity
/// Level == High). In other words, it is not safe to say if the process is
/// elevated based on elevation type. Instead, we should use TokenElevation.
/// </remarks>
public static bool IsProcessElevated()
{
bool fIsElevated;
SafeTokenHandle hToken = null;
IntPtr pTokenElevation = IntPtr.Zero;
try
{
// Open the access token of the current process with TOKEN_QUERY.
if (!NativeMethods.OpenProcessToken(Process.GetCurrentProcess().Handle,
NativeMethods.TOKEN_QUERY, out hToken))
{
throw new Win32Exception();
}
// Allocate a buffer for the elevation information.
int cbTokenElevation = Marshal.SizeOf(typeof(TOKEN_ELEVATION));
pTokenElevation = Marshal.AllocHGlobal(cbTokenElevation);
if (pTokenElevation == IntPtr.Zero)
{
throw new Win32Exception();
}
// Retrieve token elevation information.
if (!NativeMethods.GetTokenInformation(hToken,
TOKEN_INFORMATION_CLASS.TokenElevation, pTokenElevation,
cbTokenElevation, out cbTokenElevation))
{
// When the process is run on operating systems prior to Windows
// Vista, GetTokenInformation returns false with the error code
// ERROR_INVALID_PARAMETER because TokenElevation is not supported
// on those operating systems.
throw new Win32Exception();
}
// Marshal the TOKEN_ELEVATION struct from native to .NET object.
TOKEN_ELEVATION elevation = (TOKEN_ELEVATION)Marshal.PtrToStructure(
pTokenElevation, typeof(TOKEN_ELEVATION));
// TOKEN_ELEVATION.TokenIsElevated is a non-zero value if the token
// has elevated privileges; otherwise, a zero value.
fIsElevated = (elevation.TokenIsElevated != 0);
}
finally
{
// Centralized cleanup for all allocated resources.
hToken?.Close();
if (pTokenElevation != IntPtr.Zero)
Marshal.FreeHGlobal(pTokenElevation);
}
return fIsElevated;
}
}
/// <summary>
/// The TOKEN_INFORMATION_CLASS enumeration type contains values that
/// specify the type of information being assigned to or retrieved from
/// an access token.
/// </summary>
internal enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
MaxTokenInfoClass
}
/// <summary>
/// The WELL_KNOWN_SID_TYPE enumeration type is a list of commonly used
/// security identifiers (SIDs). Programs can pass these values to the
/// CreateWellKnownSid function to create a SID from this list.
/// </summary>
internal enum WELL_KNOWN_SID_TYPE
{
WinNullSid = 0,
WinWorldSid = 1,
WinLocalSid = 2,
WinCreatorOwnerSid = 3,
WinCreatorGroupSid = 4,
WinCreatorOwnerServerSid = 5,
WinCreatorGroupServerSid = 6,
WinNtAuthoritySid = 7,
WinDialupSid = 8,
WinNetworkSid = 9,
WinBatchSid = 10,
WinInteractiveSid = 11,
WinServiceSid = 12,
WinAnonymousSid = 13,
WinProxySid = 14,
WinEnterpriseControllersSid = 15,
WinSelfSid = 16,
WinAuthenticatedUserSid = 17,
WinRestrictedCodeSid = 18,
WinTerminalServerSid = 19,
WinRemoteLogonIdSid = 20,
WinLogonIdsSid = 21,
WinLocalSystemSid = 22,
WinLocalServiceSid = 23,
WinNetworkServiceSid = 24,
WinBuiltinDomainSid = 25,
WinBuiltinAdministratorsSid = 26,
WinBuiltinUsersSid = 27,
WinBuiltinGuestsSid = 28,
WinBuiltinPowerUsersSid = 29,
WinBuiltinAccountOperatorsSid = 30,
WinBuiltinSystemOperatorsSid = 31,
WinBuiltinPrintOperatorsSid = 32,
WinBuiltinBackupOperatorsSid = 33,
WinBuiltinReplicatorSid = 34,
WinBuiltinPreWindows2000CompatibleAccessSid = 35,
WinBuiltinRemoteDesktopUsersSid = 36,
WinBuiltinNetworkConfigurationOperatorsSid = 37,
WinAccountAdministratorSid = 38,
WinAccountGuestSid = 39,
WinAccountKrbtgtSid = 40,
WinAccountDomainAdminsSid = 41,
WinAccountDomainUsersSid = 42,
WinAccountDomainGuestsSid = 43,
WinAccountComputersSid = 44,
WinAccountControllersSid = 45,
WinAccountCertAdminsSid = 46,
WinAccountSchemaAdminsSid = 47,
WinAccountEnterpriseAdminsSid = 48,
WinAccountPolicyAdminsSid = 49,
WinAccountRasAndIasServersSid = 50,
WinNTLMAuthenticationSid = 51,
WinDigestAuthenticationSid = 52,
WinSChannelAuthenticationSid = 53,
WinThisOrganizationSid = 54,
WinOtherOrganizationSid = 55,
WinBuiltinIncomingForestTrustBuildersSid = 56,
WinBuiltinPerfMonitoringUsersSid = 57,
WinBuiltinPerfLoggingUsersSid = 58,
WinBuiltinAuthorizationAccessSid = 59,
WinBuiltinTerminalServerLicenseServersSid = 60,
WinBuiltinDCOMUsersSid = 61,
WinBuiltinIUsersSid = 62,
WinIUserSid = 63,
WinBuiltinCryptoOperatorsSid = 64,
WinUntrustedLabelSid = 65,
WinLowLabelSid = 66,
WinMediumLabelSid = 67,
WinHighLabelSid = 68,
WinSystemLabelSid = 69,
WinWriteRestrictedCodeSid = 70,
WinCreatorOwnerRightsSid = 71,
WinCacheablePrincipalsGroupSid = 72,
WinNonCacheablePrincipalsGroupSid = 73,
WinEnterpriseReadonlyControllersSid = 74,
WinAccountReadonlyControllersSid = 75,
WinBuiltinEventLogReadersGroup = 76,
WinNewEnterpriseReadonlyControllersSid = 77,
WinBuiltinCertSvcDComAccessGroup = 78
}
/// <summary>
/// The SECURITY_IMPERSONATION_LEVEL enumeration type contains values
/// that specify security impersonation levels. Security impersonation
/// levels govern the degree to which a server process can act on behalf
/// of a client process.
/// </summary>
internal enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
/// <summary>
/// The TOKEN_ELEVATION_TYPE enumeration indicates the elevation type of
/// token being queried by the GetTokenInformation function or set by
/// the SetTokenInformation function.
/// </summary>
internal enum TOKEN_ELEVATION_TYPE
{
TokenElevationTypeDefault = 1,
TokenElevationTypeFull,
TokenElevationTypeLimited
}
/// <summary>
/// The structure represents a security identifier (SID) and its
/// attributes. SIDs are used to uniquely identify users or groups.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct SID_AND_ATTRIBUTES
{
public IntPtr Sid;
public UInt32 Attributes;
}
/// <summary>
/// The structure indicates whether a token has elevated privileges.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct TOKEN_ELEVATION
{
public Int32 TokenIsElevated;
}
/// <summary>
/// The structure specifies the mandatory integrity level for a token.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct TOKEN_MANDATORY_LABEL
{
public SID_AND_ATTRIBUTES Label;
}
/// <summary>
/// Represents a wrapper class for a token handle.
/// </summary>
internal class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
// ReSharper disable once UnusedMember.Local
private SafeTokenHandle()
: base(true)
{
}
internal SafeTokenHandle(IntPtr handle) : base(true)
{
SetHandle(handle);
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
internal class NativeMethods
{
// Token Specific Access Rights
public const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000;
public const UInt32 STANDARD_RIGHTS_READ = 0x00020000;
public const UInt32 TOKEN_ASSIGN_PRIMARY = 0x0001;
public const UInt32 TOKEN_DUPLICATE = 0x0002;
public const UInt32 TOKEN_IMPERSONATE = 0x0004;
public const UInt32 TOKEN_QUERY = 0x0008;
public const UInt32 TOKEN_QUERY_SOURCE = 0x0010;
public const UInt32 TOKEN_ADJUST_PRIVILEGES = 0x0020;
public const UInt32 TOKEN_ADJUST_GROUPS = 0x0040;
public const UInt32 TOKEN_ADJUST_DEFAULT = 0x0080;
public const UInt32 TOKEN_ADJUST_SESSIONID = 0x0100;
public const UInt32 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);
public const UInt32 TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |
TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE |
TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID);
public const Int32 ERROR_INSUFFICIENT_BUFFER = 122;
// Integrity Levels
public const Int32 SECURITY_MANDATORY_UNTRUSTED_RID = 0x00000000;
public const Int32 SECURITY_MANDATORY_LOW_RID = 0x00001000;
public const Int32 SECURITY_MANDATORY_MEDIUM_RID = 0x00002000;
public const Int32 SECURITY_MANDATORY_HIGH_RID = 0x00003000;
public const Int32 SECURITY_MANDATORY_SYSTEM_RID = 0x00004000;
/// <summary>
/// The function opens the access token associated with a process.
/// </summary>
/// <param name="hProcess">
/// A handle to the process whose access token is opened.
/// </param>
/// <param name="desiredAccess">
/// Specifies an access mask that specifies the requested types of
/// access to the access token.
/// </param>
/// <param name="hToken">
/// Outputs a handle that identifies the newly opened access token
/// when the function returns.
/// </param>
/// <returns></returns>
[DllImport("advapi32", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool OpenProcessToken(IntPtr hProcess,
uint desiredAccess, out SafeTokenHandle hToken);
/// <summary>
/// The function creates a new access token that duplicates one
/// already in existence.
/// </summary>
/// <param name="ExistingTokenHandle">
/// A handle to an access token opened with TOKEN_DUPLICATE access.
/// </param>
/// <param name="ImpersonationLevel">
/// Specifies a SECURITY_IMPERSONATION_LEVEL enumerated type that
/// supplies the impersonation level of the new token.
/// </param>
/// <param name="DuplicateTokenHandle">
/// Outputs a handle to the duplicate token.
/// </param>
/// <returns></returns>
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool DuplicateToken(
SafeTokenHandle ExistingTokenHandle,
SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
out SafeTokenHandle DuplicateTokenHandle);
/// <summary>
/// The function retrieves a specified type of information about an
/// access token. The calling process must have appropriate access
/// rights to obtain the information.
/// </summary>
/// <param name="hToken">
/// A handle to an access token from which information is retrieved.
/// </param>
/// <param name="tokenInfoClass">
/// Specifies a value from the TOKEN_INFORMATION_CLASS enumerated
/// type to identify the type of information the function retrieves.
/// </param>
/// <param name="pTokenInfo">
/// A pointer to a buffer the function fills with the requested
/// information.
/// </param>
/// <param name="tokenInfoLength">
/// Specifies the size, in bytes, of the buffer pointed to by the
/// TokenInformation parameter.
/// </param>
/// <param name="returnLength">
/// A pointer to a variable that receives the number of bytes needed
/// for the buffer pointed to by the TokenInformation parameter.
/// </param>
/// <returns></returns>
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetTokenInformation(
SafeTokenHandle hToken,
TOKEN_INFORMATION_CLASS tokenInfoClass,
IntPtr pTokenInfo,
Int32 tokenInfoLength,
out Int32 returnLength);
/// <summary>
/// Sets the elevation required state for a specified button or
/// command link to display an elevated icon.
/// </summary>
public const UInt32 BCM_SETSHIELD = 0x160C;
/// <summary>
/// Sends the specified message to a window or windows. The function
/// calls the window procedure for the specified window and does not
/// return until the window procedure has processed the message.
/// </summary>
/// <param name="hWnd">
/// Handle to the window whose window procedure will receive the
/// message.
/// </param>
/// <param name="Msg">Specifies the message to be sent.</param>
/// <param name="wParam">
/// Specifies additional message-specific information.
/// </param>
/// <param name="lParam">
/// Specifies additional message-specific information.
/// </param>
/// <returns></returns>
[DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, IntPtr lParam);
/// <summary>
/// The function returns a pointer to a specified subauthority in a
/// security identifier (SID). The subauthority value is a relative
/// identifier (RID).
/// </summary>
/// <param name="pSid">
/// A pointer to the SID structure from which a pointer to a
/// subauthority is to be returned.
/// </param>
/// <param name="nSubAuthority">
/// Specifies an index value identifying the subauthority array
/// element whose address the function will return.
/// </param>
/// <returns>
/// If the function succeeds, the return value is a pointer to the
/// specified SID subauthority. To get extended error information,
/// call GetLastError. If the function fails, the return value is
/// undefined. The function fails if the specified SID structure is
/// not valid or if the index value specified by the nSubAuthority
/// parameter is out of bounds.
/// </returns>
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetSidSubAuthority(IntPtr pSid, UInt32 nSubAuthority);
}
}
// ReSharper restore InconsistentNaming | 39.409274 | 97 | 0.630787 | [
"Apache-2.0"
] | alexChurkin/TruckRemoteControlServer | Telemetry/Helpers/Win32Uac.cs | 19,549 | C# |
namespace DigitalLearningSolutions.Web.Extensions
{
using Microsoft.AspNetCore.Mvc.Rendering;
public static class HtmlHelperExtensions
{
public static string IsSelected(this IHtmlHelper htmlHelper, string action, string selectedCssClass = "selected")
{
var currentAction = htmlHelper.ViewContext.RouteData.Values["action"] as string;
return action == currentAction ? selectedCssClass : string.Empty;
}
}
}
| 31.533333 | 121 | 0.701903 | [
"MIT"
] | FridaTveit/DLSV2 | DigitalLearningSolutions.Web/Extensions/HtmlHelperExtensions.cs | 475 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
using Azure.Core.Testing;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Azure.Data.AppConfiguration.Samples
{
[LiveOnly]
public partial class ConfigurationSamples
{
[Test]
/*
* Sample demonstrates how to use Azure App Configuration to save information about two(2) environments
* "beta" and "production".
* To do this, we will create Configuration Settings with the same key,
* but different labels: one for "beta" and one for "production".
*/
public async Task HelloWorldExtended()
{
// Retrieve the connection string from the configuration store.
// You can get the string from your Azure portal or using Azure CLI.
var connectionString = Environment.GetEnvironmentVariable("APPCONFIGURATION_CONNECTION_STRING");
// Instantiate a client that will be used to call the service.
var client = new ConfigurationClient(connectionString);
// Create the Configuration Settings to be stored in the Configuration Store.
var betaEndpoint = new ConfigurationSetting("endpoint", "https://beta.endpoint.com", "beta");
var betaInstances = new ConfigurationSetting("instances", "1", "beta");
var productionEndpoint = new ConfigurationSetting("endpoint", "https://production.endpoint.com", "production");
var productionInstances = new ConfigurationSetting("instances", "1", "production");
// There are two(2) ways to store a Configuration Setting:
// -AddAsync creates a setting only if the setting does not already exist in the store.
// -SetAsync creates a setting if it doesn't exist or overrides an existing setting
await client.AddAsync(betaEndpoint);
await client.AddAsync(betaInstances);
await client.AddAsync(productionEndpoint);
await client.AddAsync(productionInstances);
// There is a need to increase the production instances from 1 to 5.
// The UpdateSync will help us with this.
ConfigurationSetting instancesToUpdate = await client.GetAsync(productionInstances.Key, productionInstances.Label);
instancesToUpdate.Value = "5";
await client.UpdateAsync(instancesToUpdate);
// We want to gather all the information available for the "production' environment.
// By calling GetBatchSync with the proper filter for label "production", we will get
// all the Configuration Settings that satisfy that condition.
var selector = new SettingSelector(null, "production");
Debug.WriteLine("Settings for Production environmnet");
await foreach (var setting in client.GetSettingsAsync(selector))
{
Debug.WriteLine(setting);
}
// Once we don't need the Configuration Setting, we can delete them.
await client.DeleteAsync(betaEndpoint.Key, betaEndpoint.Label);
await client.DeleteAsync(betaInstances.Key, betaInstances.Label);
await client.DeleteAsync(productionEndpoint.Key, productionEndpoint.Label);
await client.DeleteAsync(productionInstances.Key, productionInstances.Label);
}
}
}
| 48.931507 | 127 | 0.674692 | [
"MIT"
] | Only2125/azure-sdk-for-net | sdk/appconfiguration/Azure.Data.AppConfiguration/samples/Sample2_HelloWorldExtended.cs | 3,574 | C# |
// Copyright (c) homuler & The Vignette Authors. Licensed under the MIT license.
// See the LICENSE file in the repository root for more details.
using System;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
namespace Akihabara.Native.Gpu
{
public partial class SafeNativeMethods : NativeMethods
{
// HACK: ONLY CALL THIS IF YOU'RE DOING iOS STUFF!
[Pure, DllImport(MediaPipeLibrary, ExactSpelling = true)]
public static extern IntPtr mp_GpuResources__ios_gpu_data(IntPtr gpuResources);
[Pure, DllImport(MediaPipeLibrary, ExactSpelling = true)]
public static extern IntPtr mp_SharedGpuResources__get(IntPtr gpuResources);
[Pure, DllImport(MediaPipeLibrary, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool mp_StatusOrGpuResources__ok(IntPtr statusOrGpuResources);
}
}
| 38 | 91 | 0.744518 | [
"MIT"
] | Amberarch/Akihabara | src/Akihabara/Native/Gpu/SafeGpuResources.cs | 912 | C# |
using Newtonsoft.Json;
namespace PddOpenSdk.Models.Request.Order
{
public partial class UpdateOrderNoteRequestModel : PddRequestModel
{
/// <summary>
/// 订单备注
/// </summary>
[JsonProperty("note")]
public string Note { get; set; }
/// <summary>
/// 备注标记:1-红色,2-黄色,3-绿色,4-蓝色,5-紫色,tag与tag_name关联,都入参或都不入参
/// </summary>
[JsonProperty("tag")]
public int? Tag { get; set; }
/// <summary>
/// 标记名称;长度最大为3个字符,tag与tag_name关联,都入参或都不入参
/// </summary>
[JsonProperty("tag_name")]
public string TagName { get; set; }
/// <summary>
/// 订单号
/// </summary>
[JsonProperty("order_sn")]
public string OrderSn { get; set; }
}
}
| 26.066667 | 70 | 0.531969 | [
"Apache-2.0"
] | niltor/open-pdd-net-sdk | PddOpenSdk/PddOpenSdk/Models/Request/Order/UpdateOrderNoteRequestModel.cs | 912 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.IO.Pipes
{
[Flags]
public enum PipeOptions
{
None = 0x0,
WriteThrough = unchecked((int)0x80000000),
Asynchronous = unchecked((int)0x40000000), // corresponds to FILE_FLAG_OVERLAPPED
CurrentUserOnly = unchecked((int)0x20000000)
}
}
| 29 | 90 | 0.685057 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeOptions.cs | 435 | C# |
// Copyright (c) 2018, Rene Lergner - @Heathcliff74xda
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.Threading;
namespace WPinternals
{
internal class ContextViewModel : INotifyPropertyChanged
{
protected SynchronizationContext UIContext;
public bool IsSwitchingInterface = false;
public bool IsFlashModeOperation = false;
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected void OnPropertyChanged(string propertyName)
{
if ((UIContext == null) && (SynchronizationContext.Current != null))
{
UIContext = SynchronizationContext.Current;
}
if (this.PropertyChanged != null)
{
if (SynchronizationContext.Current == UIContext)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
else
{
UIContext.Post((s) => PropertyChanged(this, new PropertyChangedEventArgs(propertyName)), null);
}
}
}
private ContextViewModel _SubContextViewModel;
public ContextViewModel SubContextViewModel
{
get
{
return _SubContextViewModel;
}
private set
{
if (_SubContextViewModel != null)
{
_SubContextViewModel.IsActive = false;
}
_SubContextViewModel = value;
if (_SubContextViewModel != null)
{
_SubContextViewModel.IsActive = IsActive;
}
OnPropertyChanged(nameof(SubContextViewModel));
}
}
internal ContextViewModel()
{
UIContext = SynchronizationContext.Current;
}
internal ContextViewModel(MainViewModel Main) : this()
{
}
internal ContextViewModel(MainViewModel Main, ContextViewModel SubContext) : this(Main)
{
SubContextViewModel = SubContext;
}
internal bool IsActive { get; set; } = false;
internal virtual void EvaluateViewState()
{
}
internal void Activate()
{
IsActive = true;
EvaluateViewState();
SubContextViewModel?.Activate();
}
internal void ActivateSubContext(ContextViewModel NewSubContext)
{
if (_SubContextViewModel != null)
{
_SubContextViewModel.IsActive = false;
}
if (NewSubContext != null)
{
if (IsActive)
{
NewSubContext.Activate();
}
else
{
NewSubContext.IsActive = false;
}
}
SubContextViewModel = NewSubContext;
}
internal void SetWorkingStatus(string Message, string SubMessage, ulong? MaxProgressValue, bool ShowAnimation = true, WPinternalsStatus Status = WPinternalsStatus.Undefined)
{
ActivateSubContext(new BusyViewModel(Message, SubMessage, MaxProgressValue, UIContext: UIContext, ShowAnimation: ShowAnimation, ShowRebootHelp: Status == WPinternalsStatus.WaitingForManualReset));
}
internal void UpdateWorkingStatus(string Message, string SubMessage, ulong? CurrentProgressValue, WPinternalsStatus Status = WPinternalsStatus.Undefined)
{
if (SubContextViewModel is BusyViewModel Busy)
{
if (Message != null)
{
Busy.Message = Message;
Busy.SubMessage = SubMessage;
}
if ((CurrentProgressValue != null) && (Busy.ProgressUpdater != null))
{
try
{
Busy.ProgressUpdater.SetProgress((ulong)CurrentProgressValue);
}
catch (Exception Ex)
{
LogFile.LogException(Ex);
}
}
Busy.SetShowRebootHelp(Status == WPinternalsStatus.WaitingForManualReset);
}
}
}
}
| 34.531646 | 208 | 0.577529 | [
"MIT"
] | MagicAndre1981/WPinternals | WPinternals/ViewModels/ContextViewModel.cs | 5,458 | C# |
using System;
using Ttc.DataAccess.Services;
using Ttc.DataAccess.Utilities;
namespace Ttc.WebApi.Emailing
{
public class PasswordChangedEmailer
{
private readonly EmailConfig _config;
private const string NewPasswordRequestTemplate = @"
Je paswoord is aangepast!<br>
Als je dit niet zelf gedaan hebt, dan is er iets mis!<br>
";
public PasswordChangedEmailer(EmailConfig emailConfig)
{
_config = emailConfig;
}
public void Email(string email)
{
string subject = "Nieuw paswoord TTC Erembodegem";
string content = string.Format(NewPasswordRequestTemplate);
EmailService.SendEmail(email, subject, content, _config).Wait();
}
}
} | 27.925926 | 76 | 0.664456 | [
"MIT"
] | TTCErembodegem/TTC-React-Back | src/Ttc.WebApi/Emailing/PasswordChangedEmailer.cs | 756 | C# |
namespace NefitEasy.Enumerations
{
public enum EasyUpdateStrategy
{
Unknown,
Automatic
}
} | 14.875 | 34 | 0.621849 | [
"MIT"
] | bsamoylenko/nefiteasy | src/NefitEasy/Enumerations/EasyUpdateStrategy.cs | 121 | C# |
using HarmonyLib;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Verse;
namespace ZeFlammenwerfer
{
public class PawnShooterTracker : IPawnSubscriber
{
public static readonly Dictionary<Pawn, FlameRadiusDetector> pawns = new Dictionary<Pawn, FlameRadiusDetector>();
public void Prepare() { }
public void UpdatedCenter(Pawn pawn, Vector3 center) { }
public void ClearAll()
{
foreach (var pair in pawns)
pair.Value.Cleanup();
pawns.Clear();
}
public void NewPawn(Pawn pawn)
{
if (pawn.HasFlameThrower() == false) return;
var detector = pawns.TryGetValue(pawn);
if (detector == null)
{
detector = new FlameRadiusDetector(pawn);
pawns[pawn] = detector;
}
detector.Update(pawn);
}
public void NewPosition(Pawn pawn)
{
if (pawns.TryGetValue(pawn, out var detector))
detector.Update(pawn);
}
public void RemovePawn(Pawn pawn)
{
if (pawns.TryGetValue(pawn, out var detector))
{
detector.Cleanup();
_ = pawns.Remove(pawn);
}
}
// extra
public static void RemoveThing(Map map, IEnumerable<IntVec2> vec2s)
{
pawns
.Where(pair => pair.Value.AffectedByCells(map, vec2s))
.Do(pair => pair.Value.Update(pair.Key));
}
}
}
| 20.639344 | 115 | 0.680699 | [
"MIT"
] | pardeike/ZeFlammenwerfer | Source/PawnShooterTracker.cs | 1,261 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using GoNorth.Data.Karta.Marker;
namespace GoNorth.Data.Karta
{
/// <summary>
/// Interface for Database Access for Karta Maps
/// </summary>
public interface IKartaMapDbAccess
{
/// <summary>
/// Creates a Karta map
/// </summary>
/// <param name="map">Map to create</param>
/// <returns>Created map, with filled id</returns>
Task<KartaMap> CreateMap(KartaMap map);
/// <summary>
/// Renames a map
/// </summary>
/// <param name="map">Map with updated data</param>
/// <returns>Task</returns>
Task RenameMap(KartaMap map);
/// <summary>
/// Updates all fields of a map
/// </summary>
/// <param name="map">Map with updated data</param>
/// <returns>Task</returns>
Task UpdateMap(KartaMap map);
/// <summary>
/// Returns a map by its id
/// </summary>
/// <param name="id">Id</param>
/// <returns>Map</returns>
Task<KartaMap> GetMapById(string id);
/// <summary>
/// Returns all markers that are not yet implemented
/// </summary>
/// <param name="projectId">Project Id</param>
/// <param name="start">Start of the query</param>
/// <param name="pageSize">Page Size</param>
/// <returns>Markers</returns>
Task<List<MarkerImplementationQueryResultObject>> GetNotImplementedMarkers(string projectId, int start, int pageSize);
/// <summary>
/// Returns the count of all markers that are not yet implemented
/// </summary>
/// <param name="projectId">Project Id</param>
/// <returns>Markers Count</returns>
Task<int> GetNotImplementedMarkersCount(string projectId);
/// <summary>
/// Returns all maps for a project with full detail
/// </summary>
/// <param name="projectId">Project Id for which to request the maps</param>
/// <returns>All Maps for a project with full information</returns>
Task<List<KartaMap>> GetAllProjectMapsWithFullDetail(string projectId);
/// <summary>
/// Returns all maps for a project without detail information
/// </summary>
/// <param name="projectId">Project Id for which to request the maps</param>
/// <returns>All Maps for a project without detail information</returns>
Task<List<KartaMap>> GetAllProjectMaps(string projectId);
/// <summary>
/// Returns all maps for an npc without detail information
/// </summary>
/// <param name="npcId">Npc Id for which to request the maps</param>
/// <returns>Marker Query Result</returns>
Task<List<KartaMapMarkerQueryResult>> GetAllMapsNpcIsMarkedIn(string npcId);
/// <summary>
/// Returns all maps for an item without detail information
/// </summary>
/// <param name="itemId">Item Id for which to request the maps</param>
/// <returns>Marker Query Result</returns>
Task<List<KartaMapMarkerQueryResult>> GetAllMapsItemIsMarkedIn(string itemId);
/// <summary>
/// Returns all maps for a kirja page without detail information
/// </summary>
/// <param name="pageId">Page Id for which to request the maps</param>
/// <returns>Marker Query Result</returns>
Task<List<KartaMapMarkerQueryResult>> GetAllMapsKirjaPageIsMarkedIn(string pageId);
/// <summary>
/// Returns all maps for a Aika quest without detail information
/// </summary>
/// <param name="questId">Quest Id for which to request the maps</param>
/// <returns>All Maps for a Aika Quest without detail information</returns>
Task<List<KartaMap>> GetAllMapsAikaQuestIsMarkedIn(string questId);
/// <summary>
/// Returns all maps in which a map is marked without detail information
/// </summary>
/// <param name="mapId">Map Id for which to request the maps</param>
/// <returns>All Maps in which a map is marked without detail information</returns>
Task<List<KartaMap>> GetAllMapsMapIsMarkedIn(string mapId);
/// <summary>
/// Returns all quest markers for a given quest
/// </summary>
/// <param name="questId">Quest Id for which to request the markers</param>
/// <returns>All Markers for the given quest</returns>
Task<List<MapMarkerQueryResult>> GetAllQuestMarkers(string questId);
/// <summary>
/// Deletes a map
/// </summary>
/// <param name="map">Map to delete</param>
/// <returns>Task</returns>
Task DeleteMap(KartaMap map);
/// <summary>
/// Deletes all markers for a given quest
/// </summary>
/// <param name="questId">Id of the quest for which the markers must be deleted</param>
/// <returns>Async Task</returns>
Task DeleteMarkersOfQuest(string questId);
}
} | 41.380952 | 127 | 0.593211 | [
"MIT"
] | NoisySpaceBalls/GoNorth | Data/Karta/IKartaMapDbAccess.cs | 5,214 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;
namespace ILRuntime.Runtime.Generated
{
unsafe class System_Collections_Generic_Queue_1_ILTypeInstance_Binding
{
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase method;
Type[] args;
Type type = typeof(System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance>);
args = new Type[]{typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance)};
method = type.GetMethod("Enqueue", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, Enqueue_0);
args = new Type[]{};
method = type.GetMethod("Dequeue", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, Dequeue_1);
args = new Type[]{};
method = type.GetMethod("Peek", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, Peek_2);
args = new Type[]{};
method = type.GetMethod("get_Count", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, get_Count_3);
args = new Type[]{};
method = type.GetMethod("Clear", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, Clear_4);
args = new Type[]{};
method = type.GetConstructor(flag, null, args, null);
app.RegisterCLRMethodRedirection(method, Ctor_0);
}
static StackObject* Enqueue_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
ILRuntime.Runtime.Intepreter.ILTypeInstance @item = (ILRuntime.Runtime.Intepreter.ILTypeInstance)typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
instance_of_this_method.Enqueue(@item);
return __ret;
}
static StackObject* Dequeue_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.Dequeue();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* Peek_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.Peek();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* get_Count_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.Count;
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method;
return __ret + 1;
}
static StackObject* Clear_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
instance_of_this_method.Clear();
return __ret;
}
static StackObject* Ctor_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* __ret = ILIntepreter.Minus(__esp, 0);
var result_of_this_method = new System.Collections.Generic.Queue<ILRuntime.Runtime.Intepreter.ILTypeInstance>();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
}
}
| 53.699301 | 358 | 0.700221 | [
"MIT"
] | InMyBload/et6.0-ilruntime | Unity/Assets/Clod/ILBinding/System_Collections_Generic_Queue_1_ILTypeInstance_Binding.cs | 7,679 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInfo : MonoBehaviour
{
public static PlayerInfo instance;
public int Health;
public int Stamina;
private void Awake()
{
#region SingleTon
if (instance != null)
{
Debug.Log("Warning multiple playerinfos found");
return;
}
instance = this;
#endregion
}
} | 18.791667 | 60 | 0.605322 | [
"Apache-2.0"
] | Gman0808/Personal | PersonalAdvanture/Assets/Worlds/TestWorld/Scripts/PlayerInfo.cs | 453 | C# |
namespace Effekseer.GUI
{
partial class DockNodeScaleValues
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lp_Scale = new Effekseer.GUI.Component.LayoutPanel();
this.SuspendLayout();
//
// lp_Scale
//
this.lp_Scale.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lp_Scale.AutoScroll = true;
this.lp_Scale.Location = new System.Drawing.Point(1, 1);
this.lp_Scale.Name = "lp_Scale";
this.lp_Scale.Size = new System.Drawing.Size(290, 270);
this.lp_Scale.TabIndex = 0;
//
// DockNodeScaleValues
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.lp_Scale);
this.Font = new System.Drawing.Font("MS UI Gothic", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.Name = "DockNodeScaleValues";
this.Text = Properties.Resources.Scale;
this.Load += new System.EventHandler(this.DockNodeScalingValues_Load);
this.ResumeLayout(false);
}
#endregion
private Component.LayoutPanel lp_Scale;
}
}
| 31.75 | 148 | 0.695866 | [
"Apache-2.0",
"BSD-3-Clause"
] | NumAniCloud/Effekseer | Dev/Editor/EffekseerOld/GUI/DockNodeScaleValues.Designer.cs | 2,034 | C# |
using System;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
namespace SparkSense.StatementCompletion
{
internal class KeyPressInterceptor : IOleCommandTarget
{
private readonly IVsTextView _textViewAdapter;
private readonly CompletionSessionManager _sessionManager;
private IOleCommandTarget _nextCommand;
public KeyPressInterceptor(ViewCreationListener createdView)
{
_textViewAdapter = createdView.TextViewAdapter;
var textNavigator = createdView.TextNavigator.GetTextStructureNavigator(createdView.TextView.TextBuffer);
_sessionManager = new CompletionSessionManager(createdView.CompletionBroker, createdView.TextView, textNavigator);
TryChainTheNextCommand();
}
private void TryChainTheNextCommand()
{
if (_textViewAdapter != null) _textViewAdapter.AddCommandFilter(this, out _nextCommand);
}
#region IOleCommandTarget Members
public int QueryStatus(ref Guid cmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
return _nextCommand.QueryStatus(ref cmdGroup, cCmds, prgCmds, pCmdText);
}
public int Exec(ref Guid cmdGroup, uint key, uint cmdExecOpt, IntPtr pvaIn, IntPtr pvaOut)
{
char inputCharacter = key.GetInputCharacter(cmdGroup, pvaIn);
if (_sessionManager.IsCompletionCommitted(key, inputCharacter)) return VSConstants.S_OK;
int keyPressResult = _nextCommand.Exec(ref cmdGroup, key, cmdExecOpt, pvaIn, pvaOut);
return _sessionManager.IsCompletionStarted(key, inputCharacter) ? VSConstants.S_OK : keyPressResult;
}
#endregion
}
} | 39.255319 | 127 | 0.693767 | [
"Apache-2.0"
] | SparkViewEngine/SparkSense | src/SparkSense/StatementCompletion/KeyPressInterceptor.cs | 1,847 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using DryIoc;
using SharpOffice.Core.Configuration;
namespace SharpOffice.Core.Container
{
public class ConfigurationsRegistrationModule : IRegistrationModule
{
private readonly List<Type> _configurations;
public ConfigurationsRegistrationModule(Assembly[] assemblies)
{
_configurations = new List<Type>();
foreach (var assembly in assemblies)
_configurations.AddRange(assembly.GetTypes().Where(t => typeof(IConfiguration).IsAssignableFrom(t) && t.IsClass));
}
public void Register(DryIoc.Container container)
{
foreach (var configuration in _configurations)
container.Register(typeof(IConfiguration), configuration);
}
}
} | 30.571429 | 130 | 0.685748 | [
"MIT"
] | manio143/SharpOffice | SharpOffice.Core/Container/ConfigurationsRegistrationModule.cs | 858 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace GroupService.Repo.EntityFramework.Entities
{
public class EnumNewRequestNotificationStrategy
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string Name { get; set; }
}
}
| 25.133333 | 57 | 0.734748 | [
"MIT"
] | HelpMyStreet/group-service | GroupService/GroupService.Repo/EntityFramework/Entities/EnumNewRequestNotificationStrategy.cs | 379 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Inputs
{
public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryStringArgs : Pulumi.ResourceArgs
{
public WebAclRuleStatementRateBasedStatementScopeDownStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryStringArgs()
{
}
}
}
| 36.75 | 188 | 0.804082 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryStringArgs.cs | 735 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Uvozovky
{
public partial class Form1 : Form
{
public Form1()
{
Visible = false;
ShowInTaskbar = false;
WindowState = FormWindowState.Minimized;
InitializeComponent();
}
private void dolni_MouseDoubleClick(object sender, MouseEventArgs e)
{
}
private void dolni_Click(object sender, EventArgs e)
{
SendKeys.Send("%{TAB}");
Thread.Sleep(100);
SendKeys.Send("„");
}
private void horni_Click(object sender, EventArgs e)
{
SendKeys.Send("%{TAB}");
Thread.Sleep(100);
SendKeys.Send("“");
}
}
}
| 22.5 | 76 | 0.599034 | [
"MIT"
] | jiwopene/uvozovky | Uvozovky/Uvozovky/Form1.cs | 1,041 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using SqlDal;
using System.Configuration;
using IDAL;
namespace BLL
{
public static class FlightLogic
{
private static IFlightStorable readerwriter;
static FlightLogic()
{
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = @"D:\isp-3\ProjectEntities\BLL.config";
Configuration cfg = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
AppSettingsSection section = (cfg.GetSection("appSettings") as AppSettingsSection);
if (section.Settings["dataSource"].Value == "SQL")
readerwriter = new FlightSqlReaderWriter();
else
readerwriter = new FlightReaderWriter();
}
public static void AddFlight(Flight flight)
{
readerwriter.Add(flight);
}
public static void DeleteFlight(int ID)
{
readerwriter.Delete(ID);
}
public static void UpdateFlight(Flight flight)
{
readerwriter.Update(flight);
}
public static void UpdateFlight(Station departingstation, Station arrivalstation, Flight flight)
{
flight.DepartingPoint = departingstation.ID;
flight.ArrivalPoint = arrivalstation.ID;
readerwriter.Update(flight);
}
public static TimeSpan FlyingTime(Flight flight)
{
return StationLogic.ReadAll().First(x => x.ID == flight.ArrivalPoint).ArrivalTime - StationLogic.ReadAll().First(x => x.ID == flight.DepartingPoint).DepartingTime;
}
public static List<Flight> ReadAll()
{
return readerwriter.ReadAll();
}
public static Flight Read(int id)
{
return readerwriter.Read(id);
}
public static List<Flight> FindByArrivalPoint(string arrivalpoint)
{
List<Station> arrival = StationLogic.FindByName(arrivalpoint);
List<Flight> flights = new List<Flight>(), allflights = readerwriter.ReadAll();
foreach (var stat in arrival)
{
IEnumerable<Flight> suitflights = allflights.Where(x => x.ArrivalPoint == stat.ID);
foreach (var fl in suitflights)
flights.Add(fl);
}
return flights;
}
}
}
| 33.050633 | 176 | 0.591344 | [
"Apache-2.0"
] | nik-sergeson/bsuir-informatics-labs | 4term/ISP/ProjectEntities/FlightLogic.cs | 2,613 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20180801.Outputs
{
[OutputType]
public sealed class CustomRulesResponse
{
/// <summary>
/// List of rules
/// </summary>
public readonly ImmutableArray<Outputs.CustomRuleResponse> Rules;
[OutputConstructor]
private CustomRulesResponse(ImmutableArray<Outputs.CustomRuleResponse> rules)
{
Rules = rules;
}
}
}
| 26.428571 | 85 | 0.677027 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20180801/Outputs/CustomRulesResponse.cs | 740 | C# |
/*
* Program : Clash Of SL Server
* Description : A C# Writted 'Clash of SL' Server Emulator !
*
* Authors: Sky Tharusha <Founder at Sky Production>,
* And the Official DARK Developement Team
*
* Copyright (c) 2021 Sky Production
* All Rights Reserved.
*/
namespace CSS.PacketProcessing.Messages.Client
{
internal class ChangeAllianceMemberRoleMessage : Message
{
#region Public Fields
public static int PacketID = 14306;
#endregion Public Fields
}
} | 23.227273 | 61 | 0.671233 | [
"MIT"
] | skyprolk/Clash-Of-SL | Clash SL Server/PacketProcessing/Messages/Client/ChangeAllianceMemberRoleMessage.cs | 513 | C# |
using System;
namespace SmartHome.DomainCore.Data
{
[Flags]
public enum MeasurementType
{
Temperature = 1,
Humidity = Temperature << 1,
Voltage = Humidity << 1
}
} | 17.916667 | 37 | 0.562791 | [
"MIT"
] | JanPalasek/smart-home-server | SmartHome.DomainCore/Data/MeasurementType.cs | 215 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Parallels")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Parallels")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1f239ed1-1ff7-4693-96b9-fb207feb0c00")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.081081 | 84 | 0.747339 | [
"MIT"
] | 53V3N1X/Theta | Examples/Parallels/Properties/AssemblyInfo.cs | 1,412 | C# |
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// IL2C - A translator for ECMA-335 CIL/MSIL to C language.
// Copyright (c) 2016-2019 Kouji Matsui (@kozy_kekyo, @kekyo2)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Runtime.CompilerServices;
namespace IL2C.ILConverters
{
[TestCase(123, "SByte", (sbyte)123)]
[TestCase(12345, "Int16", (short)12345)]
[TestCase(12345, "Int32", 12345)]
[TestCase(12345, "Int64", 12345L)]
[TestCase(12345, "IntPtr", 12345)]
[TestCase(123, "Byte", (byte)123)]
[TestCase(12345, "UInt16", (ushort)12345)]
[TestCase(12345, "UInt32", (uint)12345)]
[TestCase(12345, "UInt64", 12345UL)]
[TestCase(12345, "UIntPtr", (uint)12345)]
[TestCase(12345, "Single", 12345.67f)]
[TestCase(12345, "Double", 12345.67)]
public sealed class Conv_i
{
[MethodImpl(MethodImplOptions.ForwardRef)]
public static extern IntPtr SByte(sbyte value);
[MethodImpl(MethodImplOptions.ForwardRef)]
public static extern IntPtr Int16(short value);
[MethodImpl(MethodImplOptions.ForwardRef)]
public static extern IntPtr Int32(int value);
[MethodImpl(MethodImplOptions.ForwardRef)]
public static extern IntPtr Int64(long value);
[MethodImpl(MethodImplOptions.ForwardRef)]
public static extern IntPtr IntPtr(IntPtr value);
[MethodImpl(MethodImplOptions.ForwardRef)]
public static extern IntPtr Byte(byte value);
[MethodImpl(MethodImplOptions.ForwardRef)]
public static extern IntPtr UInt16(ushort value);
[MethodImpl(MethodImplOptions.ForwardRef)]
public static extern IntPtr UInt32(uint value);
[MethodImpl(MethodImplOptions.ForwardRef)]
public static extern IntPtr UInt64(ulong value);
[MethodImpl(MethodImplOptions.ForwardRef)]
public static extern IntPtr UIntPtr(UIntPtr value);
[MethodImpl(MethodImplOptions.ForwardRef)]
public static extern IntPtr Single(float value);
[MethodImpl(MethodImplOptions.ForwardRef)]
public static extern IntPtr Double(double value);
}
}
| 37.052632 | 97 | 0.648793 | [
"Apache-2.0"
] | kekyo/IL2C.InlineIL-Migration | src/IL2C.Core.Test.ILConverters/Conv_i/Conv_i.cs | 2,816 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class AbilityData : CVariable
{
[Ordinal(0)] [RED("AssignedIndex")] public CInt32 AssignedIndex { get; set; }
[Ordinal(1)] [RED("CategoryName")] public CString CategoryName { get; set; }
[Ordinal(2)] [RED("Description")] public CString Description { get; set; }
[Ordinal(3)] [RED("Empty")] public CBool Empty { get; set; }
[Ordinal(4)] [RED("EquipmentArea")] public CEnum<gamedataEquipmentArea> EquipmentArea { get; set; }
[Ordinal(5)] [RED("GameItemData")] public CHandle<gameItemData> GameItemData { get; set; }
[Ordinal(6)] [RED("ID")] public gameItemID ID { get; set; }
[Ordinal(7)] [RED("IconPath")] public CString IconPath { get; set; }
[Ordinal(8)] [RED("IsEquipped")] public CBool IsEquipped { get; set; }
[Ordinal(9)] [RED("Name")] public CString Name { get; set; }
public AbilityData(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 43.24 | 103 | 0.666975 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/AbilityData.cs | 1,057 | C# |
using Newtonsoft.Json;
using DSM.Common.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace DSM.Metadata
{
[JsonArray]
public class MetadataList<TMetadata> : IList<TMetadata> where TMetadata : IModelMetadata
{
private readonly List<TMetadata> _list;
public MetadataList()
{
_list = new List<TMetadata>();
}
[JsonIgnore]
internal Func<string> MetadataIdResolver { private get; set; }
[JsonIgnore]
internal Action ResolveDocumentOrder { private get; set; }
private void AddResolvers(TMetadata metadata)
{
Debug.Assert(metadata != null);
Func<IModelMetadata, string> func = meta =>
{
if (this.MetadataIdResolver == null)
{
return null;
}
var idx = _list.IndexOf((TMetadata) meta);
if (idx == -1)
{
return null;
}
return $"{this.MetadataIdResolver()}[{idx}]";
};
dynamic item = metadata;
item.MetadataIdResolver = func;
if (this.ResolveDocumentOrder != null)
{
item.ResolveDocumentOrder = this.ResolveDocumentOrder;
}
}
private void RemoveResolvers(TMetadata metadata)
{
((dynamic) metadata).MetadataIdResolver = null;
}
public TMetadata this[int index]
{
get => ((IList<TMetadata>)_list)[index];
set
{
AddResolvers(value);
((IList<TMetadata>)_list)[index] = value;
}
}
public int Count => ((ICollection<TMetadata>)_list).Count;
public bool IsReadOnly => ((ICollection<TMetadata>)_list).IsReadOnly;
public void Add(TMetadata item)
{
AddResolvers(item);
((ICollection<TMetadata>)_list).Add(item);
}
public void Clear()
{
_list.ForEach(RemoveResolvers);
((ICollection<TMetadata>)_list).Clear();
}
public bool Contains(TMetadata item)
{
return ((ICollection<TMetadata>)_list).Contains(item);
}
public void CopyTo(TMetadata[] array, int arrayIndex)
{
Array.ForEach(array, AddResolvers);
((ICollection<TMetadata>)_list).CopyTo(array, arrayIndex);
}
public IEnumerator<TMetadata> GetEnumerator()
{
return ((IEnumerable<TMetadata>)_list).GetEnumerator();
}
public int IndexOf(TMetadata item)
{
return ((IList<TMetadata>)_list).IndexOf(item);
}
public void Insert(int index, TMetadata item)
{
AddResolvers(item);
((IList<TMetadata>)_list).Insert(index, item);
}
public bool Remove(TMetadata item)
{
RemoveResolvers(item);
return ((ICollection<TMetadata>)_list).Remove(item);
}
public void RemoveAt(int index)
{
var item = this[index];
RemoveResolvers(item);
((IList<TMetadata>)_list).RemoveAt(index);
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_list).GetEnumerator();
}
}
}
| 25.911111 | 92 | 0.530017 | [
"MIT"
] | jplane/DurableStateMachines | Metadata/MetadataList.cs | 3,500 | C# |
using API;
using PxStat.System.Navigation;
namespace PxStat.Entities.System.Navigation.AlertLanguage
{
/// <summary>
/// Class for managing other language versions of alerts
/// </summary>
internal class AlertLanguage_BSO
{
internal int CreateOrUpdate(Alert_DTO dto, ADO ado)
{
AlertLanguage_ADO alAdo = new AlertLanguage_ADO(ado);
return alAdo.CreateOrUpdate(dto);
}
}
} | 24.777778 | 65 | 0.654709 | [
"MIT"
] | CSOIreland/PxStat | server/PxStat/Entities/System/Navigation/AlertLanguage/AlertLanguage_BSO.cs | 448 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Razor.Directives;
using Microsoft.AspNetCore.Razor;
using Microsoft.Extensions.FileProviders;
namespace RazorCodeGenerator
{
public class Program
{
public static int Main(string[] args)
{
if (args.Length > 0 && File.Exists(args[0]))
{
var dump = false;
var iterations = 15;
if (args.Length > 1 && args[1] == "--dump")
{
dump = true;
iterations = 1;
}
else if (args.Length > 1)
{
iterations = int.Parse(args[1]);
}
GenerateCodeFile(Path.GetFullPath(args[0]), "Test", iterations, dump);
Console.WriteLine("Press the ANY key to exit.");
Console.ReadLine();
return 0;
}
else
{
Console.WriteLine("usage: dnx run <file.cshtml>");
return -1;
}
}
private static void GenerateCodeFile(string file, string @namespace, int iterations, bool dump)
{
var basePath = Path.GetDirectoryName(file);
var fileName = Path.GetFileName(file);
var fileNameNoExtension = Path.GetFileNameWithoutExtension(fileName);
var codeLang = new CSharpRazorCodeLanguage();
var host = new MvcRazorHost(new DefaultChunkTreeCache(new PhysicalFileProvider(basePath)));
var engine = new RazorTemplateEngine(host);
Console.WriteLine("Press the ANY key to start.");
Console.ReadLine();
Console.WriteLine($"Starting Code Generation: {file}");
var timer = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
using (var fileStream = File.OpenText(file))
{
var code = engine.GenerateCode(
input: fileStream,
className: fileNameNoExtension,
rootNamespace: Path.GetFileName(@namespace),
sourceFileName: fileName);
if (dump)
{
File.WriteAllText(Path.ChangeExtension(file, ".cs"), code.GeneratedCode);
}
}
Console.WriteLine("Completed iteration: " + (i + 1));
}
Console.WriteLine($"Completed after {timer.Elapsed}");
}
}
} | 34.780488 | 111 | 0.518934 | [
"Apache-2.0"
] | benaadams/Performance | testapp/RazorCodeGenerator/Program.cs | 2,854 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DLaB.Xrm.Entities
{
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9154")]
public enum PurchaseTimeFrame
{
[System.Runtime.Serialization.EnumMemberAttribute()]
Immediate = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
NextQuarter = 2,
[System.Runtime.Serialization.EnumMemberAttribute()]
ThisQuarter = 1,
[System.Runtime.Serialization.EnumMemberAttribute()]
ThisYear = 3,
[System.Runtime.Serialization.EnumMemberAttribute()]
Unknown = 4,
}
} | 28.424242 | 80 | 0.601279 | [
"MIT"
] | ScottColson/XrmUnitTest | DLaB.Xrm.Entities/OptionSets/PurchaseTimeFrame.cs | 938 | C# |
/*
* 2012 Sizing Servers Lab, affiliated with IT bachelor degree NMCT
* University College of West-Flanders, Department GKG (www.sizingservers.be, www.nmct.be, www.howest.be/en)
*
* Author(s):
* Dieter Vandroemme
*/
using System.Collections.Generic;
using System.Linq;
using vApus.SolutionTree;
using vApus.Util;
namespace vApus.DistributedTest {
/// <summary>
/// Holds information about the slave and client (via properties) to be able to let a stress test happen there.
/// </summary>
public class Slave : BaseItem {
#region Fields
private int _port = 1347;
#endregion
#region Properties
[SavableCloneable]
public int Port {
get { return _port; }
set { _port = value; }
}
/// <summary>
/// Get the ip from the client.
/// </summary>
public string IP {
get {
if (Parent == null) return null;
return (Parent as Client).IP;
}
}
/// <summary>
/// Get the hostname from the client.
/// </summary>
public string HostName {
get {
if (Parent == null) return null;
return (Parent as Client).HostName;
}
}
/// <summary>
/// Search the slaves for this.
/// Use AssigneTileStressTest to set.
/// </summary>
public TileStressTest TileStressTest {
get {
try {
foreach (TileStressTest ts in TileStessTests)
if (ts.BasicTileStressTest.Slaves.Contains(this))
return ts;
} catch {
//Handled later on.
}
return null;
}
}
private IEnumerable<TileStressTest> TileStessTests {
get {
if (Parent != null &&
Parent.GetParent() != null &&
Parent.GetParent().GetParent() != null) {
var dt = Parent.GetParent().GetParent() as DistributedTest;
foreach (Tile t in dt.Tiles)
foreach (TileStressTest ts in t)
yield return ts;
}
}
}
#endregion
#region Constructor
public Slave() { ShowInGui = false; }
#endregion
#region Functions
/// <summary>
/// Clears the stress test if it is null.
/// </summary>
/// <param name="tileStressTest"></param>
public void AssignTileStressTest(TileStressTest tileStressTest) {
ClearTileStressTest();
if (tileStressTest != null)
tileStressTest.BasicTileStressTest.Slaves = new Slave[] { this };
}
private void ClearTileStressTest() {
//Remove it from the tile stress tests (can be used only once atm).
foreach (TileStressTest ts in TileStessTests)
if (ts.BasicTileStressTest.Slaves.Contains(this)) {
var sl = new List<Slave>(ts.BasicTileStressTest.Slaves);
sl.Remove(this);
ts.BasicTileStressTest.Slaves = sl.ToArray();
}
}
public Slave Clone() {
var clone = new Slave();
clone.Port = _port;
return clone;
}
public override string ToString() {
object parent = Parent;
if (parent != null)
return parent + " - " + _port;
return base.ToString();
}
#endregion
/// <summary>
/// Compares the ports.
/// </summary>
public class SlaveComparer : IComparer<Slave> {
private static readonly SlaveComparer _labeledBaseItemComparer = new SlaveComparer();
private SlaveComparer() { }
/// <summary>
/// Compares the ports.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Compare(Slave x, Slave y) { return x.Port.CompareTo(y.Port); }
/// <summary>
/// Compares the ports.
/// </summary>
/// <returns></returns>
public static SlaveComparer GetInstance() { return _labeledBaseItemComparer; }
}
}
} | 31.70068 | 116 | 0.48412 | [
"MIT"
] | sizingservers/vApus | vApus.DistributedTesting/Slave.cs | 4,662 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Charlotte.Commons;
using Charlotte.GameCommons;
namespace Charlotte.Games.Shots
{
public class Shot_AirShooter : Shot
{
private int Level;
/// <summary>
/// 3発一緒に発射される。
/// プレイヤーに近い方から this.Order == { 0, 1, 2 } とする。
/// </summary>
private int Order;
public Shot_AirShooter(double x, double y, bool facingLeft, int order, int level)
: base(x, y, facingLeft, LevelToAttackPoint(level), true, false)
{
this.Level = level;
this.Order = order;
}
private static int LevelToAttackPoint(int level)
{
switch (level)
{
case 1: return 1;
case 2: return 2;
case 3: return 4;
case 4: return 8;
default:
throw null; // never
}
}
private static double LevelToScale(int level)
{
switch (level)
{
case 1: return 1.0;
case 2: return 1.25;
case 3: return 1.5;
case 4: return 2.0;
default:
throw null; // never
}
}
protected override IEnumerable<bool> E_Draw()
{
double SCALE = LevelToScale(this.Level);
double R = SCommon.ToInt(24.0 * SCALE);
double yAdd = 0.0;
// 初期位置調整
{
this.X += (36.0 + R * (1 + 2 * this.Order)) * (this.FacingLeft ? -1 : 1);
//this.Y += 0.0;
}
for (; ; )
{
yAdd -= (0.2 + 0.05 * this.Order) * SCALE;
this.X += (4.0 + 0.5 * this.Order) * SCALE * (this.FacingLeft ? -1 : 1);
this.Y += yAdd;
DDDraw.SetBright(new I3Color(0, 192, 192));
DDDraw.DrawBegin(Ground.I.Picture.WhiteCircle, this.X - DDGround.ICamera.X, this.Y - DDGround.ICamera.Y);
DDDraw.DrawSetSize(R * 2, R * 2);
DDDraw.DrawEnd();
DDDraw.Reset();
DDPrint.SetDebug(
(int)this.X - DDGround.ICamera.X - 12,
(int)this.Y - DDGround.ICamera.Y - 8
);
DDPrint.SetBorder(new I3Color(0, 0, 0));
DDPrint.Print("AS" + this.Level);
DDPrint.Reset();
this.Crash = DDCrashUtils.Circle(new D2Point(this.X, this.Y), R);
yield return !DDUtils.IsOutOfCamera(new D2Point(this.X, this.Y), R); // カメラから出たら消滅する。
}
}
}
}
| 21.78125 | 109 | 0.609278 | [
"MIT"
] | soleil-taruto/Elsa2 | e20210253_DoremyRockman/Elsa20200001/Elsa20200001/Games/Shots/Shot_AirShooter.cs | 2,181 | C# |
using DotvvmAcademy.Meta.Syntax;
using Microsoft.CodeAnalysis;
using System;
using System.Linq;
namespace DotvvmAcademy.Meta
{
internal class MetaSymbolVisitor : SymbolVisitor<NameNode>
{
public override NameNode DefaultVisit(ISymbol symbol)
{
throw new NotSupportedException($"Symbol of type \"{symbol.GetType()}\" is not supported.");
}
public override NameNode VisitArrayType(IArrayTypeSymbol symbol)
{
return NameFactory.ArrayType(Visit(symbol.ElementType), symbol.Rank);
}
public override NameNode VisitEvent(IEventSymbol symbol)
{
return VisitMember(symbol);
}
public override NameNode VisitField(IFieldSymbol symbol)
{
return VisitMember(symbol);
}
public override NameNode VisitMethod(IMethodSymbol symbol)
{
return VisitMember(symbol);
}
public override NameNode VisitNamedType(INamedTypeSymbol symbol)
{
if (symbol.IsConstructedType())
{
var typeArguments = symbol.TypeArguments.Select(Visit);
return NameFactory.ConstructedType(Visit(symbol.ConstructedFrom), typeArguments);
}
else if (symbol.ContainingType != default)
{
return NameFactory.NestedType(Visit(symbol.ContainingType), symbol.Name, symbol.Arity);
}
else if (symbol.ContainingNamespace.IsGlobalNamespace)
{
return NameFactory.Simple(symbol.Name, symbol.Arity);
}
else
{
return NameFactory.Qualified(Visit(symbol.ContainingNamespace), symbol.Name, symbol.Arity);
}
}
public override NameNode VisitNamespace(INamespaceSymbol symbol)
{
if (symbol.ContainingNamespace.IsGlobalNamespace)
{
return NameFactory.Identifier(symbol.Name);
}
else
{
return NameFactory.Qualified(VisitNamespace(symbol.ContainingNamespace), symbol.Name);
}
}
public override NameNode VisitPointerType(IPointerTypeSymbol symbol)
{
return NameFactory.PointerType(Visit(symbol.PointedAtType));
}
public override NameNode VisitProperty(IPropertySymbol symbol)
{
return VisitMember(symbol);
}
private NameNode VisitMember(ISymbol symbol)
{
return NameFactory.Member(Visit(symbol.ContainingType), symbol.Name);
}
}
} | 31.807229 | 107 | 0.604545 | [
"Apache-2.0"
] | ammogcoder/dotvvm-samples-academy | src/DotvvmAcademy.Meta/MetaSymbolVisitor.cs | 2,642 | C# |
using System;
using System.Xml.Serialization;
namespace NetworkUtility
{
/// <summary>
///
/// </summary>
[Serializable]
[XmlRoot(MediaTypeRegistry.ElementName_hide, Namespace = MediaTypeRegistry.XmlNamespace_Registry, IsNullable = true)]
public class MediaTypeRegHide : MediaTypeRegRawXml
{
/// <summary>
///
/// </summary>
public override string ElementName { get { return MediaTypeRegistry.ElementName_hide; } }
}
}
| 25.631579 | 121 | 0.657084 | [
"Apache-2.0"
] | erwinel/PowerShell-Modules | src/NetworkUtility/MediaTypeRegHide.cs | 489 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DataType;
namespace Sound
{
[System.Serializable]
public class BasicSound : ISound
{
[SerializeField]
protected ValueRange _pitch = new ValueRange(1);
[SerializeField]
protected ValueRange _volume = new ValueRange(1);
[SerializeField]
protected ValueRange _deley = new ValueRange(0);
[SerializeField]
protected bool _loop;
[SerializeField]
string _audioPool;
protected List<AudioClip> _clipPool;
public virtual ValueRange Pitch { get => _pitch; set => _pitch = value; }
public virtual ValueRange Volume { get => _volume; set => _volume = value; }
public virtual ValueRange Delay { get => _deley; set => _deley = value; }
public virtual bool Loop { get => _loop; set => _loop = value; }
public virtual AudioClip Clip { get => GetClip(); }
private AudioClip GetClip()
{
if (_clipPool == null)
{
LoadAudio();
if (_clipPool == null)
{
Console.LogWarning($"Could not load {_audioPool}.");
return null;
}
if (_clipPool.Count <= 0)
{
Console.LogWarning($"Could not load {_audioPool}.");
return null;
}
}
if (_clipPool.Count > 0)
return _clipPool[Random.Range(0, _clipPool.Count)];
else
return null;
}
public void LoadAudio(string newAudio = null)
{
if (newAudio == _audioPool && _clipPool == null)
return;
if (!string.IsNullOrWhiteSpace(newAudio))
_audioPool = newAudio;
_clipPool = Utility.Toolbox.Instance.SoundPool.GrabBakedAudio(_audioPool);
}
}
} | 31.68254 | 86 | 0.534569 | [
"MIT"
] | sim2kid/FirstDayOfSnow | Assets/Scripts/Sound/BasicSound.cs | 1,996 | C# |
using RabbitMQ.Client.Events;
using System;
namespace RmqLib.Core {
internal interface IConsumerRegisterEventHandler {
void AddHandler(Action<object, ConsumerEventArgs> handler);
void RegisteredHandler(object sender, ConsumerEventArgs e);
}
} | 27.777778 | 61 | 0.808 | [
"MIT"
] | milovidov983/RmqMiniLib | src/RmqLib/Core/Consumer/Interfaces/IConsumerRegisterEventHandler.cs | 252 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TouhouLauncher.Views.UserControls.Settings {
/// <summary>
/// Interaction logic for GameLocationsSettingsControl.xaml
/// </summary>
public partial class GamesSettings : UserControl {
public GamesSettings() {
InitializeComponent();
}
}
}
| 24.807692 | 60 | 0.789147 | [
"MIT"
] | McFlyboy/Touhou-Launcher | TouhouLauncher/Views/UserControls/Settings/GamesSettings.xaml.cs | 647 | C# |
using log4net.Config;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
[assembly: InternalsVisibleTo("KvmSwitch.Tests")]
// Configure log4net using the .config file
[assembly: XmlConfigurator(Watch = true)]
| 45.138889 | 98 | 0.705231 | [
"MIT"
] | Holger-H/KvmSwitch | src/KvmSwitch/AssemblyInfo.cs | 1,627 | C# |
using NBitcoin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.BitcoinCore;
using WalletWasabi.BitcoinCore.Endpointing;
using WalletWasabi.Blockchain.Mempool;
using WalletWasabi.Helpers;
using WalletWasabi.Services;
using WalletWasabi.Stores;
namespace WalletWasabi.Tests.Helpers
{
public static class TestNodeBuilder
{
public static async Task<CoreNode> CreateAsync(HostedServices hostedServices, [CallerFilePath]string callerFilePath = null, [CallerMemberName]string callerMemberName = null, string additionalFolder = null, MempoolService mempoolService = null)
{
var network = Network.RegTest;
return await CoreNode.CreateAsync(
new CoreNodeParams(
network,
mempoolService ?? new MempoolService(),
hostedServices,
Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.ExtractFileName(callerFilePath), callerMemberName, additionalFolder ?? ""),
tryRestart: true,
tryDeleteDataDir: true,
EndPointStrategy.Random,
EndPointStrategy.Random,
txIndex: 1,
prune: 0,
userAgent: $"/MustardWalletLTC:{Constants.ClientVersion}/"),
CancellationToken.None);
}
}
}
| 32.1 | 245 | 0.777259 | [
"MIT"
] | MustardWallet/MustardWalletLTC | WalletWasabi.Tests/Helpers/TestNodeBuilder.cs | 1,284 | C# |
using UnityEngine;
using UnityEditor.ProjectWindowCallback;
using System.IO;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
namespace UnityEditor.Rendering
{
/// <summary>
/// A utility class to create Volume Profiles and components.
/// </summary>
public static class VolumeProfileFactory
{
[MenuItem("Assets/Create/Volume Profile", priority = 201)]
static void CreateVolumeProfile()
{
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(
0,
ScriptableObject.CreateInstance<DoCreatePostProcessProfile>(),
"New Volume Profile.asset",
null,
null
);
}
/// <summary>
/// Creates a <see cref="VolumeProfile"/> Asset and saves it at the given path.
/// </summary>
/// <param name="path">The path to save the Asset to, relative to the Project folder.</param>
/// <returns>The newly created <see cref="VolumeProfile"/>.</returns>
public static VolumeProfile CreateVolumeProfileAtPath(string path)
{
var profile = ScriptableObject.CreateInstance<VolumeProfile>();
profile.name = Path.GetFileName(path);
AssetDatabase.CreateAsset(profile, path);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
return profile;
}
/// <summary>
/// Creates a <see cref="VolumeProfile"/> Asset and saves it in a folder next to the Scene.
/// </summary>
/// <param name="scene">The Scene to save the Profile next to.</param>
/// <param name="targetName">A name to use for the Asset filename.</param>
/// <returns>The newly created <see cref="VolumeProfile"/>.</returns>
public static VolumeProfile CreateVolumeProfile(Scene scene, string targetName)
{
string path;
if (string.IsNullOrEmpty(scene.path))
{
path = "Assets/";
}
else
{
var scenePath = Path.GetDirectoryName(scene.path);
var extPath = scene.name;
var profilePath = scenePath + Path.DirectorySeparatorChar + extPath;
if (!AssetDatabase.IsValidFolder(profilePath))
{
var directories = profilePath.Split(Path.DirectorySeparatorChar);
string rootPath = "";
foreach (var directory in directories)
{
var newPath = rootPath + directory;
if (!AssetDatabase.IsValidFolder(newPath))
AssetDatabase.CreateFolder(rootPath.TrimEnd(Path.DirectorySeparatorChar), directory);
rootPath = newPath + Path.DirectorySeparatorChar;
}
}
path = profilePath + Path.DirectorySeparatorChar;
}
path += targetName + " Profile.asset";
path = AssetDatabase.GenerateUniqueAssetPath(path);
var profile = ScriptableObject.CreateInstance<VolumeProfile>();
AssetDatabase.CreateAsset(profile, path);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
return profile;
}
/// <summary>
/// Creates a <see cref="VolumeComponent"/> in an existing <see cref="VolumeProfile"/>.
/// </summary>
/// <typeparam name="T">A type of <see cref="VolumeComponent"/>.</typeparam>
/// <param name="profile">The profile to store the new component in.</param>
/// <param name="overrides">specifies whether to override the parameters in the component or not.</param>
/// <param name="saveAsset">Specifies whether to save the Profile Asset or not. This is useful when you need to
/// create several components in a row and only want to save the Profile Asset after adding the last one,
/// because saving Assets to disk can be slow.</param>
/// <returns></returns>
public static T CreateVolumeComponent<T>(VolumeProfile profile, bool overrides = false, bool saveAsset = true)
where T : VolumeComponent
{
var comp = profile.Add<T>(overrides);
comp.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(comp, profile);
if (saveAsset)
{
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
return comp;
}
}
class DoCreatePostProcessProfile : EndNameEditAction
{
public override void Action(int instanceId, string pathName, string resourceFile)
{
var profile = VolumeProfileFactory.CreateVolumeProfileAtPath(pathName);
ProjectWindowUtil.ShowCreatedAsset(profile);
}
}
}
| 41.528455 | 120 | 0.574785 | [
"MIT"
] | AlePPisa/GameJamPractice1 | Cellular/Library/PackageCache/com.unity.render-pipelines.core@8.2.0/Editor/Volume/VolumeProfileFactory.cs | 5,108 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace UsingPageDialogService.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
| 34.78125 | 98 | 0.681042 | [
"MIT"
] | ScarlettCode/Prism-Samples-Forms | 06-PageDialogService/src/UsingPageDialogService.iOS/AppDelegate.cs | 1,115 | C# |
using System;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class Screenshot360 : MonoBehaviour
{
#if UNITY_EDITOR
[MenuItem("GameObject/Take 360 Screenshot")]
#endif
private static void Generate360Screenshot()
{
int imageWidth = 4096;
bool saveAsJPEG = true;
bool newFileName = false;
int currentCount = 1;
string path;
byte[] bytes = I360Render.Capture(imageWidth, saveAsJPEG);
if (bytes != null)
{
while (!newFileName)
{
if (File.Exists("Assets/360Photos/360Render_" + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + "_" + currentCount + (saveAsJPEG ? ".jpeg" : ".png")))
{
currentCount++;
}
else
{
path = Path.Combine("Assets/360Photos", "360Render_" + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + "_" + currentCount + (saveAsJPEG ? ".jpeg" : ".png"));
File.WriteAllBytes(path, bytes);
Debug.Log("360 render saved to " + path);
newFileName = true;
}
}
}
}
}
| 30.933333 | 198 | 0.519397 | [
"Apache-2.0"
] | FrogAC/ai2thor | unity/Assets/Scripts/Screenshot360.cs | 1,394 | C# |
using ArangoDBNetStandard.DocumentApi.Models;
using ArangoDBNetStandard.Serialization;
using ArangoDBNetStandard.Transport;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using ArangoDBNetStandard.Models;
namespace ArangoDBNetStandard.DocumentApi
{
/// <summary>
/// Provides access to ArangoDB document API.
/// </summary>
public class DocumentApiClient : ApiClientBase, IDocumentApiClient
{
protected override string ApiRootPath => "_api/document";
/// <summary>
/// Creates an instance of <see cref="DocumentApiClient"/>
/// using the provided transport layer and the default JSON serialization.
/// </summary>
/// <param name="client"></param>
public DocumentApiClient(IApiClientTransport transport)
: base(transport, new JsonNetApiClientSerialization())
{
}
/// <summary>
/// Creates an instance of <see cref="DocumentApiClient"/>
/// using the provided transport and serialization layers.
/// </summary>
/// <param name="client"></param>
/// <param name="serializer"></param>
public DocumentApiClient(IApiClientTransport transport, IApiClientSerialization serializer)
: base(transport, serializer)
{
}
/// <summary>
/// Post a single document.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collectionName"></param>
/// <param name="document"></param>
/// <param name="cancellationToken"></param>
/// <param name="query"></param>
/// <returns></returns>
public virtual async Task<PostDocumentResponse<T>> PostDocumentAsync<T>(string collectionName, T document,
PostDocumentsOptions query = null, CancellationToken cancellationToken = default)
{
if (query != null && query.ContentSerializationOptions == null)
{
query.ContentSerializationOptions = new ContentSerializationOptions(false, true);
}
return await PostRequestAsync($"{ApiRootPath}/{WebUtility.UrlEncode(collectionName)}",
response => new PostDocumentResponse<T>(response), document,
query ?? new PostDocumentsOptions
{ContentSerializationOptions = new ContentSerializationOptions(false, true)}, cancellationToken);
}
/// <summary>
/// Post multiple documents in a single request.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collectionName"></param>
/// <param name="documents"></param>
/// <param name="cancellationToken"></param>
/// <param name="query"></param>
/// <returns></returns>
public virtual async Task<PostDocumentsResponse<T>> PostDocumentsAsync<T>(string collectionName,
IEnumerable<T> documents, PostDocumentsOptions query = null, CancellationToken cancellationToken = default)
{
return await PostRequestAsync($"{ApiRootPath}/{WebUtility.UrlEncode(collectionName)}",
response => new PostDocumentsResponse<T>(response), documents, query, cancellationToken);
}
/// <summary>
/// Replace multiple documents.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collectionName"></param>
/// <param name="documents"></param>
/// <param name="query"></param>
/// <returns></returns>
public virtual async Task<PostDocumentsResponse<T>> PutDocumentsAsync<T>(string collectionName,
IEnumerable<T> documents, PutDocumentsOptions query = null, CancellationToken cancellationToken = default)
{
return await PutRequestAsync($"{ApiRootPath}/{WebUtility.UrlEncode(collectionName)}",
response => new PostDocumentsResponse<T>(response), documents, query, cancellationToken);
}
/// <summary>
/// Replaces the document with handle <document-handle> with the one in
/// the body, provided there is such a document and no precondition is
/// violated.
/// PUT/_api/document/{document-handle}
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="documentId"></param>
/// <param name="doc"></param>
/// <param name="opts"></param>
/// <returns></returns>
public virtual async Task<PostDocumentResponse<T>> PutDocumentAsync<T>(string documentId, T document, PutDocumentsOptions query = null, CancellationToken cancellationToken = default)
{
ValidateDocumentId(documentId);
return await PutRequestAsync($"{ApiRootPath}/{documentId}",
response => new PostDocumentResponse<T>(response), document, query, cancellationToken);
}
/// <summary>
/// Get an existing document.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collectionName"></param>
/// <param name="documentKey"></param>
/// <returns></returns>
public virtual async Task<GetDocumentResponse<T>> GetDocumentAsync<T>(string collectionName, string documentKey,
CancellationToken cancellationToken = default)
{
return await GetDocumentAsync<T>(
$"{WebUtility.UrlEncode(collectionName)}/{WebUtility.UrlEncode(documentKey)}", cancellationToken);
}
/// <summary>
/// Get an existing document based on its Document ID.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="documentId"></param>
/// <returns></returns>
public virtual async Task<GetDocumentResponse<T>> GetDocumentAsync<T>(string documentId, CancellationToken cancellationToken = default)
{
ValidateDocumentId(documentId);
return await GetRequestAsync($"{ApiRootPath}/{documentId}",
response => new GetDocumentResponse<T>(response), null, cancellationToken);
}
/// <summary>
/// Delete a document.
/// </summary>
/// <remarks>
/// This method overload is provided as a convenience when the client does not care about the type of <see cref="DeleteDocumentResponse{T}.Old"/>
/// in the returned <see cref="DeleteDocumentResponse{object}"/>. Its value will be <see cref="null"/> when
/// <see cref="DeleteDocumentsOptions.ReturnOld"/> is either <see cref="false"/> or not set, so this overload is useful in the default case
/// when deleting documents.
/// </remarks>
/// <param name="collectionName"></param>
/// <param name="documentKey"></param>
/// <param name="query"></param>
/// <returns></returns>
public virtual async Task<DeleteDocumentResponse<object>> DeleteDocumentAsync(string collectionName, string documentKey,
DeleteDocumentsOptions query = null, CancellationToken cancellationToken = default)
{
return await DeleteDocumentAsync<object>(
$"{WebUtility.UrlEncode(collectionName)}/{WebUtility.UrlEncode(documentKey)}", query, cancellationToken);
}
/// <summary>
/// Delete a document based on its document ID.
/// </summary>
/// <remarks>
/// This method overload is provided as a convenience when the client does not care about the type of <see cref="DeleteDocumentResponse{T}.Old"/>
/// in the returned <see cref="DeleteDocumentResponse{object}"/>. Its value will be <see cref="null"/> when
/// <see cref="DeleteDocumentsOptions.ReturnOld"/> is either <see cref="false"/> or not set, so this overload is useful in the default case
/// when deleting documents.
/// </remarks>
/// <param name="documentId"></param>
/// <param name="query"></param>
/// <returns></returns>
public virtual async Task<DeleteDocumentResponse<object>> DeleteDocumentAsync(string documentId,
DeleteDocumentsOptions query = null, CancellationToken cancellationToken = default)
{
return await DeleteDocumentAsync<object>(documentId, query, cancellationToken);
}
/// <summary>
/// Delete multiple documents based on the passed document selectors.
/// A document selector is either the document ID or the document Key.
/// </summary>
/// <remarks>
/// This method overload is provided as a convenience when the client does not care about the type of <see cref="DeleteDocumentResponse{T}.Old"/>
/// in the returned <see cref="DeleteDocumentsResponse{object}"/>. These will be <see cref="null"/> when
/// <see cref="DeleteDocumentsOptions.ReturnOld"/> is either <see cref="false"/> or not set, so this overload is useful in the default case
/// when deleting documents.
/// </remarks>
/// <param name="collectionName"></param>
/// <param name="selectors"></param>
/// <param name="query"></param>
/// <returns></returns>
public virtual async Task<DeleteDocumentsResponse<object>> DeleteDocumentsAsync(string collectionName,
IEnumerable<string> selectors, DeleteDocumentsOptions query = null, CancellationToken cancellationToken = default)
{
return await DeleteDocumentsAsync<object>(collectionName, selectors, query, cancellationToken);
}
/// <summary>
/// Delete a document.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collectionName"></param>
/// <param name="documentKey"></param>
/// <param name="query"></param>
/// <returns></returns>
public virtual async Task<DeleteDocumentResponse<T>> DeleteDocumentAsync<T>(string collectionName, string documentKey, DeleteDocumentsOptions query = null, CancellationToken cancellationToken = default)
{
return await DeleteDocumentAsync<T>(
$"{WebUtility.UrlEncode(collectionName)}/{WebUtility.UrlEncode(documentKey)}", query,
cancellationToken);
}
/// <summary>
/// Delete a document based on its document ID.
/// </summary>
/// <param name="documentId"></param>
/// <param name="query"></param>
/// <returns></returns>
public virtual async Task<DeleteDocumentResponse<T>> DeleteDocumentAsync<T>(string documentId,
DeleteDocumentsOptions query = null, CancellationToken cancellationToken = default)
{
ValidateDocumentId(documentId);
return await DeleteRequestAsync($"{ApiRootPath}/{documentId}",
response => new DeleteDocumentResponse<T>(response), query, cancellationToken);
}
/// <summary>
/// Delete multiple documents based on the passed document selectors.
/// A document selector is either the document ID or the document Key.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collectionName"></param>
/// <param name="selectors"></param>
/// <param name="query"></param>
/// <returns></returns>
public virtual async Task<DeleteDocumentsResponse<T>> DeleteDocumentsAsync<T>(string collectionName,
IEnumerable<string> selectors, DeleteDocumentsOptions query = null, CancellationToken cancellationToken = default)
{
return await DeleteRequestAsync($"{ApiRootPath}/{WebUtility.UrlEncode(collectionName)}",
response => new DeleteDocumentsResponse<T>(response), query, selectors, cancellationToken);
}
/// <summary>
/// Partially updates documents, the documents to update are specified
/// by the _key attributes in the body objects.The body of the
/// request must contain a JSON array of document updates with the
/// attributes to patch(the patch documents). All attributes from the
/// patch documents will be added to the existing documents if they do
/// not yet exist, and overwritten in the existing documents if they do
/// exist there.
/// Setting an attribute value to null in the patch documents will cause a
/// value of null to be saved for the attribute by default.
/// If ignoreRevs is false and there is a _rev attribute in a
/// document in the body and its value does not match the revision of
/// the corresponding document in the database, the precondition is
/// violated.
/// PATCH/_api/document/{collection}
/// </summary>
/// <typeparam name="T">Type of the patch object used to partially update documents.</typeparam>
/// <typeparam name="TResponse">Type of the returned documents, only applies when
/// <see cref="PatchDocumentsOptions.ReturnNew"/> or <see cref="PatchDocumentsOptions.ReturnOld"/>
/// are used.</typeparam>
/// <param name="collectionName"></param>
/// <param name="patches"></param>
/// <param name="cancellationToken"></param>
/// <param name="query"></param>
/// <returns></returns>
public virtual async Task<PatchDocumentsResponse<TResponse>> PatchDocumentsAsync<TPatch, TResponse>(
string collectionName,
IEnumerable<TPatch> patches,
PatchDocumentsOptions query = null,
CancellationToken cancellationToken = default)
{
return await PatchRequestAsync(ApiRootPath + "/" + WebUtility.UrlEncode(collectionName),
response => new PatchDocumentsResponse<TResponse>(response), patches, query, cancellationToken);
}
/// <summary>
/// Partially updates the document identified by document-handle.
/// The body of the request must contain a JSON document with the
/// attributes to patch(the patch document). All attributes from the
/// patch document will be added to the existing document if they do not
/// yet exist, and overwritten in the existing document if they do exist
/// there.
/// PATCH/_api/document/{document-handle}
/// </summary>
/// <typeparam name="T">Type of the patch object used to partially update a document.</typeparam>
/// <typeparam name="TResponse">Type of the returned document, only applies when
/// <see cref="PatchDocumentOptions.ReturnNew"/> or <see cref="PatchDocumentOptions.ReturnOld"/>
/// are used.</typeparam>
/// <param name="collectionName"></param>
/// <param name="documentKey"></param>
/// <param name="body"></param>
/// <param name="query"></param>
/// <returns></returns>
public virtual async Task<PatchDocumentResponse<TResponse>> PatchDocumentAsync<TPatch, TResponse>(
string collectionName,
string documentKey,
TPatch body,
PatchDocumentOptions query = null,
CancellationToken cancellationToken = default)
{
string documentHandle = WebUtility.UrlEncode(collectionName) +
"/" + WebUtility.UrlEncode(documentKey);
return await PatchDocumentAsync<TPatch, TResponse>(documentHandle, body, query, cancellationToken);
}
/// <summary>
/// Partially updates the document identified by document-handle.
/// The body of the request must contain a JSON document with the
/// attributes to patch(the patch document). All attributes from the
/// patch document will be added to the existing document if they do not
/// yet exist, and overwritten in the existing document if they do exist
/// there.
/// PATCH/_api/document/{document-handle}
/// </summary>
/// <typeparam name="TPatch">Type of the patch object used to partially update a document.</typeparam>
/// <typeparam name="TResponse">Type of the returned document, only applies when
/// <see cref="PatchDocumentOptions.ReturnNew"/> or <see cref="PatchDocumentOptions.ReturnOld"/>
/// are used.</typeparam>
/// <param name="documentId"></param>
/// <param name="body"></param>
/// <param name="query"></param>
/// <returns></returns>
public virtual async Task<PatchDocumentResponse<TResponse>> PatchDocumentAsync<TPatch, TResponse>(
string documentId,
TPatch body,
PatchDocumentOptions query = null,
CancellationToken cancellationToken = default)
{
ValidateDocumentId(documentId);
return await PatchRequestAsync(ApiRootPath + "/" + documentId,
response => new PatchDocumentResponse<TResponse>(response), body, query, cancellationToken);
}
/// <summary>
/// Like GET, but only returns the header fields and not the body. You
/// can use this call to get the current revision of a document or check if
/// the document was deleted.
/// HEAD /_api/document/{document-handle}
/// </summary>
/// <param name="collectionName"></param>
/// <param name="documentKey"></param>
/// <param name="headers"></param>
/// <remarks>
/// 200: is returned if the document was found.
/// 304: is returned if the “If-None-Match” header is given and the document has the same version.
/// 404: is returned if the document or collection was not found.
/// 412: is returned if an “If-Match” header is given and the found document has a different version. The response will also contain the found document’s current revision in the Etag header.
/// </remarks>
/// <returns></returns>
public virtual async Task<HeadDocumentResponse> HeadDocumentAsync(
string collectionName,
string documentKey,
HeadDocumentHeader headers = null,
CancellationToken cancellationToken = default)
{
return await HeadDocumentAsync(
$"{WebUtility.UrlEncode(collectionName)}/{WebUtility.UrlEncode(documentKey)}", headers,
cancellationToken);
}
/// <summary>
/// Like GET, but only returns the header fields and not the body. You
/// can use this call to get the current revision of a document or check if
/// the document was deleted.
/// HEAD/_api/document/{document-handle}
/// </summary>
/// <param name="documentId"></param>
/// <param name="headers">Object containing a dictionary of Header keys and values</param>
/// <exception cref="ArgumentException">Document ID is invalid.</exception>
/// <remarks>
/// 200: is returned if the document was found.
/// 304: is returned if the “If-None-Match” header is given and the document has the same version.
/// 404: is returned if the document or collection was not found.
/// 412: is returned if an “If-Match” header is given and the found document has a different version. The response will also contain the found document’s current revision in the Etag header.
/// </remarks>
/// <returns></returns>
public virtual async Task<HeadDocumentResponse> HeadDocumentAsync(string documentId, HeadDocumentHeader headers = null, CancellationToken cancellationToken = default)
{
ValidateDocumentId(documentId);
string uri = ApiRootPath + "/" + documentId;
WebHeaderCollection headerCollection = headers == null ? new WebHeaderCollection() : headers.ToWebHeaderCollection();
using (var response = await Transport.HeadAsync(uri, headerCollection, cancellationToken))
{
if (response.IsSuccessStatusCode)
{
return new HeadDocumentResponse(response.StatusCode, response.Headers.ETag);
}
return new HeadDocumentResponse(response.Headers.ETag, new ApiResponse(true, response.StatusCode, null, null));
}
}
}
}
| 51.392947 | 210 | 0.628682 | [
"Apache-2.0"
] | apawsey/arangodb-net-standard | arangodb-net-standard/DocumentApi/DocumentApiClient.cs | 20,425 | C# |
using Aim_All_Towers.Utils;
using Assets.Scripts.Models;
using Assets.Scripts.Models.Towers;
using Assets.Scripts.Models.Towers.Behaviors.Attack;
using MelonLoader;
using System;
using System.Collections.Generic;
using System.Linq;
using UnhollowerBaseLib;
namespace Aim_All_Towers.Extensions
{
public static class TowerModelExt
{
public static List<AttackModel> GetAttackModel(this TowerModel towerModel)
{
if (!towerModel.HasBehavior<AttackModel>())
return null;
return towerModel.GetBehavior<AttackModel>();
}
public static bool HasBehavior<T>(this TowerModel towerModel) where T : TowerBehaviorModel
{
if (towerModel.behaviors == null || towerModel.behaviors.Count == 0)
return false;
try { var result = towerModel.behaviors.First(item => item.name.Contains(typeof(T).Name)); }
catch (InvalidOperationException) { return false; }
return true;
}
public static List<T> GetBehavior<T>(this TowerModel towerModel) where T : TowerBehaviorModel
{
var behaviors = towerModel.behaviors;
if (towerModel.behaviors is null || towerModel.behaviors.Count == 0)
return null;
var results = new Il2CppReferenceArray<T>(0);
foreach (var behavior in behaviors)
{
if (behavior.name.Contains(typeof(T).Name))
Il2CppUtils.Add<T>(results, behavior.TryCast<T>());
}
//var result = behaviors.FirstOrDefault(behavior => behavior.name.Contains(typeof(T).Name)); //removed to use List instead
return results.ToList();
}
public static void RemoveBehavior<T>(this TowerModel towerModel) where T : TowerBehaviorModel
{
if (!towerModel.HasBehavior<T>())
return;
var behaviors = towerModel.GetBehavior<T>();
foreach (var item in behaviors)
towerModel.RemoveBehavior(item);
}
public static void RemoveBehavior<T>(this TowerModel towerModel, T behavior) where T : TowerBehaviorModel
{
if (!towerModel.HasBehavior<T>())
return;
int itemsRemoved = 0;
var behaviors = towerModel.behaviors;
towerModel.behaviors = new Il2CppReferenceArray<Model>(behaviors.Length - 1);
for (int i = 0; i < behaviors.Length; i++)
{
var item = behaviors[i];
if (item.name == behavior.name)
{
itemsRemoved++;
continue;
}
towerModel.behaviors[i - itemsRemoved] = item;
}
}
}
}
| 33.440476 | 134 | 0.584906 | [
"MIT"
] | KLightning18/BTD6-Mods | Aim All Towers/Extensions/TowerModelExt.cs | 2,811 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18408
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace gen.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.129032 | 151 | 0.57845 | [
"Apache-2.0"
] | RohitTiwari92/Minimum-Code | gen/Properties/Settings.Designer.cs | 1,060 | C# |
using Annexio.Controllers;
using Annexio.Repository.Manager;
using Moq;
using NUnit.Framework;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Annexio.Tests.Controllers
{
public class RegionsControllerTest
{
private Mock<IRegionsManager> _mock;
private RegionsController _controller;
[SetUp]
public void SetUp()
{
_mock = new Mock<IRegionsManager>();
_controller = new RegionsController(_mock.Object);
}
[Test]
public void RegionsController_RegionDetails_ReturnsATaskOfActionResult()
{
var result = _controller.RegionDetails("RegionName");
Assert.IsInstanceOf<Task<ActionResult>>(result);
}
[Test]
public void RegionsController_RegionDetails_ReturnsAHttpNotFoundResult()
{
var result = _controller.RegionDetails(null).Result;
Assert.IsInstanceOf<HttpNotFoundResult>(result);
}
[Test]
public void RegionsController_RegionDetails_IsCallingGetRegionDetailsMethod()
{
var regionName = "RegionName";
var result = _controller.RegionDetails(regionName);
_mock.Verify(c => c.GetRegionDetails(regionName));
}
}
}
| 26.895833 | 85 | 0.646011 | [
"Apache-2.0"
] | OscarPonte/Annexio | Annexio.Tests/Controllers/RegionsControllerTest.cs | 1,293 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using Transport.Notify;
namespace Transport
{
public class Peer
{
public delegate void OnConnectionFailedDelegate(Connection connection, ConnectionFailedReason reason);
public delegate void OnConnectedDelegate(Connection connection);
public delegate void OnDisconnectedDelegate(Connection connection, DisconnectReason reason);
public delegate void OnUnreliablePacketDelegate(Connection connection, Packet packet);
public delegate void OnNotifyPacketDelegate(Connection connection, object? userData);
public delegate void OnNotifyPacketDelegate2(Connection connection, Packet packet);
public event OnConnectionFailedDelegate? OnConnectionFailed;
public event OnConnectedDelegate? OnConnected;
public event OnDisconnectedDelegate? OnDisconnected;
public event OnUnreliablePacketDelegate? OnUnreliablePacket;
public event OnNotifyPacketDelegate? OnNotifyPacketLost;
public event OnNotifyPacketDelegate? OnNotifyPacketDelivered;
public event OnNotifyPacketDelegate2? OnNotityPacketReceived;
private readonly Socket _socket;
private readonly Config _config;
private readonly Timer _timer;
private readonly Random _random;
private readonly Dictionary<IPEndPoint, Connection> _connections;
public Peer(Config config)
{
_random = new Random(Environment.TickCount);
_config = config;
_timer = Timer.StartNew();
_connections = new Dictionary<IPEndPoint, Connection>();
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
{
Blocking = false
};
_socket.Bind(config.EndPoint);
SetConnectionReset(_socket);
}
public void Update()
{
// Receive
Receive();
// Process
UpdateConnections();
// TODO - Implement threading for sending
// Send()
}
public void Connect(IPEndPoint endPoint)
{
var connection = CreateConnection(endPoint);
connection.State = ConnectionState.Connecting;
}
public void Disconnect(Connection connection)
{
if (connection.State != ConnectionState.Connected)
{
Log.Error($"[Disconnect]: Can't disconnect {connection}, state is {connection.State}");
return;
}
DisconnectConnection(connection, DisconnectReason.UserRequest);
}
public void SendUnconnected(EndPoint target, Packet packet)
{
Log.Info($"[SendUnconnected]: Target {target}, {packet.ToString()}");
SendInternal(target, packet.Data.ToArray());
}
public void SendUnreliable(Connection connection, byte[] data)
{
if (data.Length > (_config.MTU - 1))
{
Log.Error($"[SendUnreliable]: Data too large, above MTU-1 {data.Length}");
return;
}
var buffer = GetMtuBuffer();
Buffer.BlockCopy(data, 0, buffer, 1, data.Length);
buffer[0] = (byte)PacketType.Unreliable;
SendInternal(connection.RemoteEndPoint, buffer, data.Length + 1);
}
private int NotifyPacketHeaderSize => 1 + (2 * _config.SequenceNumberBytes) + sizeof(ulong);
public bool SendNotify(Connection connection, byte[] data, object? userObject)
{
if (connection.SendWindow.IsFull)
{
return false;
}
if (data.Length > (_config.MTU - NotifyPacketHeaderSize))
{
Log.Error($"[SendNotify]: Data too large, above MTU-Header_Size({NotifyPacketHeaderSize}) {data.Length}");
return false;
}
var sequenceNumberForPacket = connection.SendSequencer.Next();
var buffer = GetMtuBuffer();
Buffer.BlockCopy(data, 0, buffer, NotifyPacketHeaderSize, data.Length);
// Fill header data
buffer[0] = (byte)PacketType.Notify;
var offset = 1;
ByteUtils.WriteULong(buffer, offset, _config.SequenceNumberBytes, sequenceNumberForPacket);
offset += _config.SequenceNumberBytes;
ByteUtils.WriteULong(buffer, offset, _config.SequenceNumberBytes, connection.LastReceivedSequence);
offset += _config.SequenceNumberBytes;
ByteUtils.WriteULong(buffer, offset, sizeof(ulong), connection.ReceiveMask);
connection.SendWindow.Push(new SendEnvelope()
{
Sequence = sequenceNumberForPacket,
SendTime = _timer.Now,
UserData = userObject
});
SendInternal(connection, buffer, NotifyPacketHeaderSize + data.Length);
return true;
}
public void SendPacket(Connection connection, Packet packet)
{
//Log.Info($"[Send]: Target {connection}, {packet.ToString()}");
SendInternal(connection, packet.Data.ToArray());
}
private void UpdateConnections()
{
foreach (var (_, connection) in _connections)
{
UpdateConnection(connection);
}
}
private void UpdateConnection(Connection connection)
{
switch (connection.State)
{
case ConnectionState.Connecting:
UpdateConnecting(connection);
break;
case ConnectionState.Connected:
UpdateConnected(connection);
break;
case ConnectionState.Disconnected:
UpdateDisconnected(connection);
break;
}
}
private void UpdateDisconnected(Connection connection)
{
if (connection.DisconnectTime + _config.DisconnectIdleTime < _timer.Now)
{
RemoveConnection(connection);
}
}
private void UpdateConnected(Connection connection)
{
if (connection.LastReceivedPacketTime + _config.ConnectionTimeout < _timer.Now)
{
Log.Info($"[Timeout]: {connection}");
DisconnectConnection(connection, DisconnectReason.Timeout);
}
if (connection.LastSentPacketTime + _config.KeepAliveInterval < _timer.Now)
{
SendPacket(connection, Packet.KeepAlive());
}
}
private void DisconnectConnection(Connection connection, DisconnectReason reason, bool sendToOtherPeer = true)
{
Log.Info($"[DisconnectConnection]: {connection}, Reason={reason}");
if (sendToOtherPeer)
{
SendPacket(connection, Packet.Command(Commands.Disconnected, (byte)reason));
}
connection.State = ConnectionState.Disconnected;
connection.DisconnectTime = _timer.Now;
OnDisconnected?.Invoke(connection, reason);
}
private void UpdateConnecting(Connection connection)
{
if (connection.LastConnectionAttemptTime + _config.ConnectionAttemptInterval > _timer.Now)
{
return;
}
if (connection.ConnectionAttempts == _config.MaxConnectionAttempts)
{
// TODO - Use callback for this
Debug.Fail("Max attempts reached: use callback on this");
return;
}
connection.ConnectionAttempts++;
connection.LastConnectionAttemptTime = _timer.Now;
SendPacket(connection, Packet.Command(Commands.ConnectionRequest));
}
private void SendInternal(Connection connection, byte[] data, int? length = null)
{
Debug.Assert(connection.State < ConnectionState.Disconnected);
connection.LastSentPacketTime = _timer.Now;
SendInternal(connection.RemoteEndPoint, data, length);
}
private void SendInternal(EndPoint target, byte[] data, int? length = null)
{
if (length.HasValue)
{
_socket.SendTo(data, 0, length.Value, SocketFlags.None, target);
}
else
{
_socket.SendTo(data, target);
}
}
private void Receive()
{
while (_socket.Poll(0, SelectMode.SelectRead))
{
var buffer = GetMtuBuffer();
var endpoint = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
var bytesReceived = _socket.ReceiveFrom(buffer, SocketFlags.None, ref endpoint);
if (_random.NextDouble() <= _config.SimulatedLoss)
{
Log.Info($"Simulated loss of {bytesReceived} bytes");
continue;
}
var packet = new Packet(buffer, 0, bytesReceived);
//Log.Info($"[Received]: From [{endpoint}], {packet.ToString()}");
var ipEndPoint = (IPEndPoint)endpoint;
if (_connections.TryGetValue(ipEndPoint, out var connection))
{
HandleConnectedPacket(connection, packet);
}
else
{
HandleUnconnectedPacket(ipEndPoint, packet);
}
}
}
private void HandleConnectedPacket(Connection connection, Packet packet)
{
if (connection.State >= ConnectionState.Disconnected)
{
return;
}
connection.LastReceivedPacketTime = _timer.Now;
switch (packet.Type)
{
case PacketType.Command:
HandleCommandPacket(connection, packet);
break;
case PacketType.Unreliable:
HandleUnreliablePacket(connection, packet);
break;
case PacketType.KeepAlive:
// Only used to keep connections alive
// Don't need to do anything
break;
case PacketType.Notify:
HandleNotifyPacket(connection, packet);
break;
default:
throw new NotImplementedException($"Not implemented for packet type: {packet.Type}");
}
}
private void HandleNotifyPacket(Connection connection, Packet packet)
{
if (packet.Data.Length < NotifyPacketHeaderSize)
{
return;
}
var offset = 1;
var packetSequenceNumber = ByteUtils.ReadULong(packet.Data, offset, _config.SequenceNumberBytes);
offset += _config.SequenceNumberBytes;
var remoteRecvSequence = ByteUtils.ReadULong(packet.Data, offset, _config.SequenceNumberBytes);
offset += _config.SequenceNumberBytes;
var remoteRecvMask = ByteUtils.ReadULong(packet.Data, offset, sizeof(ulong));
var sequenceDistance = connection.SendSequencer.Distance(packetSequenceNumber, connection.LastReceivedSequence);
// Sequence so out of bounds we can't save, just disconnect
if (Math.Abs(sequenceDistance) > _config.SendWindowSize)
{
DisconnectConnection(connection, DisconnectReason.SequenceOutOfBounds);
return;
}
// Sequence is old, so duplicate or re-ordered packet
if (sequenceDistance <= 0)
{
return;
}
// Update recv sequence for ou local connection object
connection.LastReceivedSequence = packetSequenceNumber;
if (sequenceDistance >= ACK_MASK_BITS)
{
connection.ReceiveMask = 1; // 0000 0000 0000 0000 0000 0000 0000 0001
}
else
{
connection.ReceiveMask = (connection.ReceiveMask << (int)sequenceDistance) | 1;
}
AckPackets(connection, remoteRecvSequence, remoteRecvMask);
// Only a ack packet
if (packet.Data.Length == NotifyPacketHeaderSize)
{
return;
}
var trimedPacket = packet.Slice(NotifyPacketHeaderSize);
OnNotityPacketReceived?.Invoke(connection, trimedPacket);
}
const int ACK_MASK_BITS = sizeof(ulong) * 8;
private void AckPackets(Connection connection, ulong recvSequenceFromRemote, ulong recvMaskFromRemote)
{
while (connection.SendWindow.Count > 0)
{
var envelope = connection.SendWindow.Peek();
var distance = (int)connection.SendSequencer.Distance(envelope.Sequence, recvSequenceFromRemote);
if (distance > 0)
{
break;
}
// remove envelope from send window
connection.SendWindow.Pop();
// If this is the same as the latest sequence remove received from us, we can use thus to calculate RTT
if (distance == 0)
{
connection.Rtt = _timer.Now - envelope.SendTime;
}
// If any of this cases trigger, packet is most likely lost
if ((distance <= -ACK_MASK_BITS) || ((recvMaskFromRemote & (1UL << -distance)) == 0UL))
{
OnNotifyPacketLost?.Invoke(connection, envelope.UserData);
}
else
{
OnNotifyPacketDelivered?.Invoke(connection, envelope.UserData);
}
}
}
private void HandleUnreliablePacket(Connection connection, Packet packet)
{
// Remove the unreliable header and pass to the user code
var trimedPacket = packet.Slice(1);
OnUnreliablePacket?.Invoke(connection, trimedPacket);
}
private void HandleUnconnectedPacket(IPEndPoint endpoint, Packet packet)
{
if (packet.Data.Length != 2)
{
// Assume the packet is garbage from somewhere on the internet
return;
}
if (packet.Type != PacketType.Command)
{
// First packet has to be a command
return;
}
var commandId = (Commands)packet.Data[1];
if (commandId != Commands.ConnectionRequest)
{
// First packet has to be a connect request command
return;
}
if (_connections.Count >= _config.MaxConnections)
{
SendUnconnected(endpoint,
Packet.Command(Commands.ConnectionFailed,
(byte)ConnectionFailedReason.ServerIsFull));
return;
}
// TODO - Try detect DDOS attack?
var connection = CreateConnection(endpoint);
HandleCommandPacket(connection, packet);
}
private void HandleCommandPacket(Connection connection, Packet packet)
{
Debug.Assert(packet.Type == PacketType.Command);
var commandId = (Commands)packet.Data[1];
switch (commandId)
{
case Commands.ConnectionRequest:
HandleConnectionRequest(connection, packet);
break;
case Commands.ConnectionAccepted:
HandleConnectionAccepted(connection, packet);
break;
case Commands.ConnectionFailed:
HandleConnectionFailed(connection, packet);
break;
case Commands.Disconnected:
HandleDisconnected(connection, packet);
break;
default:
Log.Warn($"[HandleCommandPacket]: Unkown Command {commandId}");
break;
}
}
private void HandleDisconnected(Connection connection, Packet packet)
{
var reason = (DisconnectReason)packet.Data[2];
DisconnectConnection(connection, reason, false);
}
private void HandleConnectionFailed(Connection connection, Packet packet)
{
Debug.Assert(connection.State == ConnectionState.Connecting);
var reason = (ConnectionFailedReason)packet.Data[2];
Log.Info($"[ConnectionFailed]: {connection}, Reason={reason}");
RemoveConnection(connection);
// Callback to the user code
OnConnectionFailed?.Invoke(connection, reason);
}
private void HandleConnectionAccepted(Connection connection, Packet packet)
{
switch (connection.State)
{
case ConnectionState.Created:
Debug.Fail("");
break;
case ConnectionState.Connected:
// Already connected, so this is a duplicated packet, ignore
break;
case ConnectionState.Connecting:
SetAsConnected(connection);
break;
}
}
private void HandleConnectionRequest(Connection connection, Packet packet)
{
switch (connection.State)
{
case ConnectionState.Created:
SetAsConnected(connection);
SendPacket(connection, Packet.Command(Commands.ConnectionAccepted));
break;
case ConnectionState.Connected:
SendPacket(connection, Packet.Command(Commands.ConnectionAccepted));
break;
case ConnectionState.Connecting:
Debug.Fail("Cannot be in connecting state while a connection request has been sent");
break;
}
}
private Connection CreateConnection(IPEndPoint endPoint)
{
var connection = new Connection(_config, endPoint)
{
LastReceivedPacketTime = _timer.Now
};
_connections.Add(endPoint, connection);
Log.Info($"[CreateConnection] Created {connection}");
return connection;
}
private void RemoveConnection(Connection connection)
{
Debug.Assert(connection.State != ConnectionState.Removed);
Log.Info($"[RemoveConnection]: {connection}");
var removed = _connections.Remove(connection.RemoteEndPoint);
Debug.Assert(removed);
connection.State = ConnectionState.Removed;
}
private void SetAsConnected(Connection connection)
{
connection.State = ConnectionState.Connected;
OnConnected?.Invoke(connection);
}
// TODO: Reuse this buffer
private byte[] GetMtuBuffer()
{
return new byte[_config.MTU];
}
private static void SetConnectionReset(Socket s)
{
try
{
const uint IOC_IN = 0x80000000;
const uint IOC_VENDOR = 0x18000000;
s.IOControl(unchecked((int)(IOC_IN | IOC_VENDOR | 12)),
new byte[] { Convert.ToByte(false) },
null);
}
catch { }
}
}
}
| 35.374558 | 124 | 0.557237 | [
"MIT"
] | PauloHMattos/ReliableUDP | Transport/Transport/Peer.cs | 20,024 | C# |
using System;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using LennyBOTv2.Preconditions;
using LennyBOTv2.Services;
namespace LennyBOTv2.Modules
{
public class AmongUsModule : LennyModuleBase
{
private readonly AmongUsService _auService;
public AmongUsModule(AmongUsService auService)
{
_auService = auService;
}
[Command("crew")]
[AmongUsWriteStats]
public async Task CrewCmdAsync(string gameResult, params IUser[] players)
{
try
{
_auService.WriteCrewStats(gameResult, players);
}
catch (Exception ex)
{
await Context.MarkCmdFailedAsync(ex.ToString()).ConfigureAwait(false);
return;
}
await Context.MarkCmdOkAsync().ConfigureAwait(false);
}
[Command("impostor")]
[AmongUsWriteStats]
public async Task ImpostorCmdAsync(string gameResult, params IUser[] players)
{
try
{
_auService.WriteImpostorStats(gameResult, players);
}
catch (Exception ex)
{
await Context.MarkCmdFailedAsync(ex.ToString()).ConfigureAwait(false);
return;
}
await Context.MarkCmdOkAsync().ConfigureAwait(false);
}
[Command("stats")]
[AmongUsServer]
public async Task StatsCmdAsync()
{
await ReplyAsync(embed: _auService.GetStatsEmbed("impostor")).ConfigureAwait(false);
await ReplyAsync(embed: _auService.GetStatsEmbed("crew")).ConfigureAwait(false);
}
[Command("stats crew")]
[AmongUsServer]
public async Task StatsCrewCmdAsync()
{
await ReplyAsync(embed: _auService.GetStatsEmbed("crew")).ConfigureAwait(false);
}
[Command("stats impostor")]
[AmongUsServer]
public async Task StatsImpostorCmdAsync()
{
await ReplyAsync(embed: _auService.GetStatsEmbed("impostor")).ConfigureAwait(false);
}
}
}
| 28.552632 | 96 | 0.584793 | [
"MIT"
] | seky16/LennyBOTv2 | LennyBOTv2/Modules/AmongUsModule.cs | 2,172 | C# |
// <copyright file="TagContextBuilder.cs" company="OpenTelemetry Authors">
// Copyright 2018, OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
namespace OpenTelemetry.Tags
{
internal sealed class TagContextBuilder : TagContextBuilderBase
{
internal TagContextBuilder(IDictionary<TagKey, TagValue> tags)
{
this.Tags = new Dictionary<TagKey, TagValue>(tags);
}
internal TagContextBuilder()
{
this.Tags = new Dictionary<TagKey, TagValue>();
}
internal IDictionary<TagKey, TagValue> Tags { get; }
public override ITagContextBuilder Put(TagKey key, TagValue value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
this.Tags[key] = value ?? throw new ArgumentNullException(nameof(value));
return this;
}
public override ITagContextBuilder Remove(TagKey key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (this.Tags.ContainsKey(key))
{
this.Tags.Remove(key);
}
return this;
}
public override ITagContext Build()
{
return new TagContext(this.Tags);
}
public override IDisposable BuildScoped()
{
return CurrentTagContextUtils.WithTagContext(this.Build());
}
}
}
| 29.291667 | 85 | 0.612613 | [
"Apache-2.0"
] | andy-g/opentelemetry-dotnet | src/OpenTelemetry/Tags/TagContextBuilder.cs | 2,111 | C# |
namespace StrawberryShake.Tools.Configuration
{
public enum RequestStrategy
{
Default = 0,
PersistedQuery = 1,
AutomaticPersistedQuery = 2
}
}
| 17.9 | 45 | 0.636872 | [
"MIT"
] | AccountTechnologies/hotchocolate | src/StrawberryShake/Tooling/src/Configuration/RequestStrategy.cs | 179 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Silk.Core.Data.Entities;
namespace Silk.Core.Data.EntityConfigurations
{
public class TagEntityConfiguration : IEntityTypeConfiguration<TagEntity>
{
public void Configure(EntityTypeBuilder<TagEntity> builder)
{
builder.Property(t => t.Id).ValueGeneratedOnAdd();
}
}
} | 29.642857 | 77 | 0.73253 | [
"Apache-2.0"
] | VelvetThePanda/Silk | src/Silk.Core.Data/EntityConfigurations/TagEntityConfiguration.cs | 417 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LinkedInZIPParser.api")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LinkedInZIPParser.api")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("31762cba-abd1-4381-b74a-6cdd6dd553f8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.194444 | 84 | 0.750545 | [
"MIT"
] | remixed2/linkedin-pdf-parser-api | Properties/AssemblyInfo.cs | 1,378 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.