content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.ContractsLight;
using System.Threading;
using static BuildXL.Utilities.FormattableStringEx;
#pragma warning disable SA1649 // File name must match first type name
namespace TypeScript.Net.Types
{
/// <nodoc/>
public sealed class FileReference : IFileReference
{
/// <inheritdoc/>
public int Pos { get; set; }
/// <inheritdoc/>
public int End { get; set; }
/// <inheritdoc/>
public string FileName { get; set; }
}
/// <nodoc/>
[DebuggerDisplay("{ToString(), nq}")]
public sealed class TextSpan : ITextSpan
{
/// <inheritdoc/>
public int Start { get; set; }
/// <inheritdoc/>
public int Length { get; set; }
/// <inheritdoc/>
public override string ToString()
{
return I($"[{Start}, {Start + Length}]");
}
}
/// <nodoc/>
public sealed class TextChangeRange : ITextChangeRange
{
/// <inheritdoc/>
public ITextSpan Span { get; set; }
/// <inheritdoc/>
public int NewLength { get; set; }
}
/// <summary>
/// Factory for creating new instance of the <see cref="INode"/>.
/// </summary>
public static class NodeFactory
{
/// <nodoc/>
public static T Create<T>(SyntaxKind kind, int pos, int end) where T : INode, new()
{
var node = FastActivator<T>.Create();
node.Initialize(kind, pos, end);
return node;
}
}
/// <nodoc/>
public sealed class CommentRange : ICommentRange
{
/// <inheritdoc/>
public int Pos { get; set; }
/// <inheritdoc/>
public int End { get; set; }
/// <inheritdoc/>
public Optional<bool> HasTrailingNewLine { get; set; }
/// <inheritdoc/>
public SyntaxKind Kind { get; set; }
}
/// <nodoc/>
public class Signature : ISignature
{
/// <inheritdoc/>
public ISignatureDeclaration Declaration { get; set; } // Originating declaration
/// <inheritdoc/>
public IReadOnlyList<ITypeParameter> TypeParameters { get; set; } // Type parameters (undefined if non-generic)
/// <inheritdoc/>
public IReadOnlyList<ISymbol> Parameters { get; set; } // Parameters
/// <inheritdoc/>
public IType ResolvedReturnType { get; set; } // Resolved return type
/// <inheritdoc/>
public int MinArgumentCount { get; set; } // Number of non-optional parameters
/// <inheritdoc/>
public bool HasRestParameter { get; set; } // True if last parameter is rest parameter
/// <inheritdoc/>
public bool HasStringLiterals { get; set; } // True if specialized
/// <inheritdoc/>
public ISignature Target { get; set; } // Instantiation target
/// <inheritdoc/>
public ITypeMapper Mapper { get; set; } // Instantiation mapper
/// <inheritdoc/>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Necessary functionality")]
public List<ISignature> UnionSignatures { get; set; } // Underlying signatures of a union signature
/// <inheritdoc/>
public ISignature ErasedSignature { get; set; } // Erased version of signature (deferred)
/// <inheritdoc/>
public IObjectType IsolatedSignatureType { get; set; } // A manufactured type that just contains the signature for purposes of signature comparison
/// <nodoc/>
private Signature()
{
}
/// <nodoc/>
public static Signature Create(List<ISignature> signatures = null)
{
return new Signature()
{
UnionSignatures = signatures,
};
}
}
// TypeChecker types.
internal class SymbolLinks : ISymbolLinks
{
private volatile ISymbol m_target;
private volatile ISymbol m_directTarget;
private volatile IType m_type;
private volatile IType m_declaredType;
private volatile IReadOnlyList<ITypeParameter> m_typeParameters;
private volatile IType m_inferredClassType;
private volatile Map<IType> m_instantiations;
private volatile ITypeMapper m_mapper;
// The next field is used a lot and avoiding the lock accessing it boosts performance.
private volatile NullableBool m_referenced;
private volatile IUnionOrIntersectionType m_containingType;
private volatile ISymbolTable m_resolvedExports;
private volatile bool m_exportsChecked;
private bool? m_isNestedRedeclaration;
private volatile IBindingElement m_bindingElement;
private bool? m_exportsSomeValue;
public ISymbol Target
{
get { return m_target; }
set { m_target = value; }
}
public ISymbol DirectTarget
{
get { return m_directTarget; }
set { m_directTarget = value; }
}
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "Type nomenclature is necessary within a compiler.")]
public IType Type
{
get { return m_type; }
set { m_type = value; }
}
public IType DeclaredType
{
get { return m_declaredType; }
set { m_declaredType = value; }
}
public IReadOnlyList<ITypeParameter> TypeParameters
{
get { return m_typeParameters; }
set { m_typeParameters = value; }
}
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Necessary functionality")]
public IType InferredClassType
{
get { return m_inferredClassType; }
set { m_inferredClassType = value; }
}
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Necessary functionality")]
public Map<IType> Instantiations
{
get { return m_instantiations; }
set { m_instantiations = value; }
}
public ITypeMapper Mapper
{
get { return m_mapper; }
set { m_mapper = value; }
}
#pragma warning disable SA1501 // Statement must not be on a single line
public bool? Referenced
{
get { return m_referenced.AsBool(); }
set { m_referenced = value.AsNullableBool(); }
}
public IUnionOrIntersectionType ContainingType
{
get { return m_containingType; }
set { m_containingType = value; }
}
public ISymbolTable ResolvedExports
{
get { return m_resolvedExports; }
set { m_resolvedExports = value; }
}
public bool ExportsChecked
{
get { return m_exportsChecked; }
set { m_exportsChecked = value; }
}
public bool? IsNestedRedeclaration
{
get { lock (this) { return m_isNestedRedeclaration; } }
set { lock (this) { m_isNestedRedeclaration = value; } }
}
public IBindingElement BindingElement
{
get { return m_bindingElement; }
set { m_bindingElement = value; }
}
public bool? ExportsSomeValue
{
get { lock (this) { return m_exportsSomeValue; } }
set { lock (this) { m_exportsSomeValue = value; } }
}
#pragma warning restore SA1501 // Statement must not be on a single line
}
/// <summary>
/// Special enum type that represents bool?.
/// </summary>
/// <remarks>
/// This internal enum reduces memory footprint because it fits into a byte, and bool? will ocupy 4 or 8 bytes.
/// </remarks>
internal enum NullableBool : byte
{
Null,
True,
False,
}
internal static class NullableBoolExtensions
{
public static bool? AsBool(this NullableBool value)
{
switch (value)
{
case NullableBool.Null:
return null;
case NullableBool.True:
return true;
case NullableBool.False:
return false;
default:
throw new ArgumentOutOfRangeException(nameof(value), value, null);
}
}
public static NullableBool AsNullableBool(this bool? value)
{
if (value == null)
{
return NullableBool.Null;
}
return value == true ? NullableBool.True : NullableBool.False;
}
}
internal class NodeLinks : INodeLinks
{
private Dictionary<int, bool> m_assignmentChecks;
private volatile IType m_resolvedType;
private volatile ISignature m_resolvedSignature;
private volatile ISymbol m_resolvedSymbol;
// This field order is very important.
// The CLR will pack them in one 8 bytes chunk. Switching them around will increase memory footprint.
private volatile int m_enumMemberValue = -1;
private volatile NodeCheckFlags m_flags;
private volatile NullableBool m_hasReportedStatementInAmbientContext;
/// <nodoc />
public object SyncRoot => this;
/// <inheritdoc />
public IType ResolvedType
{
get { return m_resolvedType; }
set { m_resolvedType = value; }
}
/// <inheritdoc />
// This field is never used in DScript
public IType ResolvedAwaitedType
{
get { return null; }
set { }
}
/// <inheritdoc />
public ISignature ResolvedSignature
{
get { return m_resolvedSignature; }
set { m_resolvedSignature = value; }
}
/// <inheritdoc />
public ISymbol ResolvedSymbolForIncrementalMode
{
get { return m_resolvedSymbol; }
set { m_resolvedSymbol = value; }
}
/// <inheritdoc />
public NodeCheckFlags Flags
{
get { return m_flags; }
set { m_flags = value; }
}
/// <inheritdoc />
public int EnumMemberValue
{
get { return m_enumMemberValue; }
set { m_enumMemberValue = value; }
}
/// <inheritdoc />
public bool? HasReportedStatementInAmbientContext
{
get { return m_hasReportedStatementInAmbientContext.AsBool(); }
set { m_hasReportedStatementInAmbientContext = value.AsNullableBool(); }
}
/// <inheritdoc />
// This field is nver used (except for assigning) in DScript.
// TODO: consider removing it.
public bool? IsVisible
{
get { return null; }
set { }
}
/// <inheritdoc />
public Dictionary<int, bool> AssignmentChecks
{
get
{
LazyInitializer.EnsureInitialized(ref m_assignmentChecks, () => new Dictionary<int, bool>());
return m_assignmentChecks;
}
}
}
internal class SymbolVisibilityResult : ISymbolVisibilityResult
{
public SymbolAccessibility Accessibility { get; set; }
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Necessary functionality")]
public List<AnyImportSyntax> AliasesToMakeVisible { get; set; }
public INode ErrorNode { get; set; }
public string ErrorSymbolName { get; set; }
}
internal class SymbolAccessibilityResult : SymbolVisibilityResult, ISymbolAccessiblityResult
{
public string ErrorModuleName { get; set; }
}
/// <nodoc/>
public class CompilerOptions : ICompilerOptions
{
/// <summary>
/// Empty compiler options.
/// </summary>
public static ICompilerOptions Empty { get; } = new CompilerOptions();
/// <inheritdoc/>
public Optional<bool> AllowNonTsExtensions { get; set; }
/// <inheritdoc/>
public Optional<string> Charset { get; set; }
/// <inheritdoc/>
public Optional<bool> Declaration { get; set; }
/// <inheritdoc/>
public Optional<bool> Diagnostics { get; set; }
/// <inheritdoc/>
public Optional<bool> EmitBom { get; set; }
/// <inheritdoc/>
public Optional<bool> Help { get; set; }
/// <inheritdoc/>
public Optional<bool> Init { get; set; }
/// <inheritdoc/>
public Optional<bool> InlineSourceMap { get; set; }
/// <inheritdoc/>
public Optional<bool> InlineSources { get; set; }
/// <inheritdoc/>
public Optional<bool> ListFiles { get; set; }
/// <inheritdoc/>
public Optional<string> Locale { get; set; }
/// <inheritdoc/>
public Optional<string> MapRoot { get; set; }
/// <inheritdoc/>
public Optional<ModuleKind> Module { get; set; }
/// <inheritdoc/>
public Optional<NewLineKind> NewLine { get; set; }
/// <inheritdoc/>
public Optional<bool> NoEmit { get; set; }
/// <inheritdoc/>
public Optional<bool> NoEmitHelpers { get; set; }
/// <inheritdoc/>
public Optional<bool> NoEmitOnError { get; set; }
/// <inheritdoc/>
public bool NoErrorTruncation { get; set; }
/// <inheritdoc/>
public Optional<bool> NoImplicitAny { get; set; }
/// <inheritdoc/>
public Optional<bool> NoLib { get; set; }
/// <inheritdoc/>
public Optional<bool> NoResolve { get; set; }
/// <inheritdoc/>
public Optional<string> Out { get; set; }
/// <inheritdoc/>
public Optional<string> OutFile { get; set; }
/// <inheritdoc/>
public Optional<string> OutDir { get; set; }
/// <inheritdoc/>
public Optional<bool> PreserveConstEnums { get; set; }
/// <inheritdoc/>
/* @internal */
public Optional<DiagnosticStyle> Pretty { get; set; }
/// <inheritdoc/>
public Optional<string> Project { get; set; }
/// <inheritdoc/>
public Optional<bool> RemoveComments { get; set; }
/// <inheritdoc/>
public Optional<string> RootDir { get; set; }
/// <inheritdoc/>
public Optional<bool> SourceMap { get; set; }
/// <inheritdoc/>
public Optional<string> SourceRoot { get; set; }
/// <inheritdoc/>
public Optional<bool> SuppressExcessPropertyErrors { get; set; }
/// <inheritdoc/>
public Optional<bool> SuppressImplicitAnyIndexErrors { get; set; }
/// <inheritdoc/>
public Optional<ScriptTarget> Target { get; set; }
/// <inheritdoc/>
public Optional<bool> Version { get; set; }
/// <inheritdoc/>
public Optional<bool> Watch { get; set; }
/// <inheritdoc/>
public Optional<bool> IsolatedModules { get; set; }
/// <inheritdoc/>
public Optional<bool> ExperimentalDecorators { get; set; }
/// <inheritdoc/>
public Optional<bool> EmitDecoratorMetadata { get; set; }
/// <inheritdoc/>
public Optional<ModuleResolutionKind> ModuleResolution { get; set; }
/// <inheritdoc/>
public Optional<bool> AllowUnusedLabels { get; set; }
/// <inheritdoc/>
public Optional<bool> AllowUnreachableCode { get; set; }
/// <inheritdoc/>
public Optional<bool> NoImplicitReturns { get; set; }
/// <inheritdoc/>
public Optional<bool> NoFallthroughCasesInSwitch { get; set; }
/// <inheritdoc/>
public Optional<bool> ForceConsistentCasingInFileNames { get; set; }
/// <inheritdoc/>
public Optional<bool> AllowSyntheticDefaultImports { get; set; }
/// <inheritdoc/>
public Optional<bool> AllowJs { get; set; }
/// <nodoc/>
/* @internal */
public Optional<bool> StripInternal { get; set; }
/// <summary>
/// Skip checking lib.d.ts to help speed up tests.
/// </summary>
/* @internal */
public Optional<bool> SkipDefaultLibCheck { get; set; }
// [option: string]: string | int | bool;
}
/// <nodoc/>
public sealed class InferenceContext : IInferenceContext
{
/// <inheritdoc/>
public Optional<int> FailedTypeParameterIndex { get; set; }
/// <inheritdoc/>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Necessary functionality")]
public List<ITypeInferences> Inferences { get; set; }
/// <inheritdoc/>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Necessary functionality")]
public List<IType> InferredTypes { get; set; }
/// <inheritdoc/>
public bool InferUnionTypes { get; set; }
/// <inheritdoc/>
public ITypeMapper Mapper { get; set; }
/// <inheritdoc/>
public IReadOnlyList<ITypeParameter> TypeParameters { get; set; }
}
/// <nodoc/>
public sealed class TypeInferences : ITypeInferences
{
/// <inheritdoc/>
public bool IsFixed { get; set; }
/// <inheritdoc/>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Necessary functionality")]
public List<IType> Primary { get; set; }
/// <inheritdoc/>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Necessary functionality")]
public List<IType> Secondary { get; set; }
}
/// <nodoc/>
public sealed class ResolvedModule : IResolvedModule
{
/// <nodoc/>
public ResolvedModule(string resolvedFileName, bool isExternaLibraryImport)
{
Contract.Requires(!string.IsNullOrEmpty(resolvedFileName));
ResolvedFileName = resolvedFileName;
IsExternalLibraryImport = isExternaLibraryImport;
}
/// <inheritdoc/>
public string ResolvedFileName { get; }
/// <inheritdoc/>
public bool IsExternalLibraryImport { get; }
}
}
| 31.211538 | 163 | 0.561974 | [
"MIT"
] | BearerPipelineTest/BuildXL | Public/Src/FrontEnd/TypeScript.Net/TypeScript.Net/Types/Implementations.cs | 19,476 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using UnaryHeap.Utilities.Core;
using UnaryHeap.Utilities.D2;
using UnaryHeap.Utilities.Misc;
namespace UnaryHeap.Algorithms
{
/// <summary>
/// Provides an implementation of Fortune's algorithm for computing the Delaunay
/// triangulation and the Voronoi diagram of a set of points.
/// </summary>
public static class FortunesAlgorithm
{
/// <summary>
/// Calculate which of two adjacent beach line arcs is intersected by the vertical
/// line produced by a site.
/// </summary>
/// <param name="site">The site projecting the intersection line.</param>
/// <param name="arcAFocus">The site from which the first arc is produced.</param>
/// <param name="arcBFocus">The site from which the second arc is produced.</param>
/// <returns>-1, if arcA is intersected. 1, if arcB is intersected.
/// 0, if the intersection line contains the intersection point of the arcs.</returns>
public static int DetermineBeachLineArcIntersected(
Point2D site, Point2D arcAFocus, Point2D arcBFocus)
{
if (null == site)
throw new ArgumentNullException("site");
if (null == arcAFocus)
throw new ArgumentNullException("arcAFocus");
if (null == arcBFocus)
throw new ArgumentNullException("arcBFocus");
if (arcAFocus.Y == arcBFocus.Y)
{
if (arcAFocus.X >= arcBFocus.X)
throw new ArgumentException("Arc foci are not ordered correctly.");
return site.X.CompareTo((arcAFocus.X + arcBFocus.X) / 2);
}
if (site.Y == arcAFocus.Y)
return site.X.CompareTo(arcAFocus.X);
if (site.Y == arcBFocus.Y)
return site.X.CompareTo(arcBFocus.X);
var difference = Parabola.Difference(
Parabola.FromFocusDirectrix(arcAFocus, site.Y),
Parabola.FromFocusDirectrix(arcBFocus, site.Y));
if (difference.EvaluateDerivative(site.X) < 0)
return -difference.A.Sign;
return difference.Evaulate(site.X).Sign;
}
/// <summary>
/// Adds points to a set of points covering a square area which will guarantee
/// that the Voronoi vertices for the point set do not exceed the convex hull
/// of the augmented set.
/// </summary>
/// <param name="points">The points to which to add a boundary.</param>
public static Point2D[] AddBoundarySites(IEnumerable<Point2D> points)
{
if (null == points)
throw new ArgumentNullException("points");
var boundary = Orthotope2D.FromPoints(points).GetScaled(new Rational(5, 4));
if (boundary.X.Size != boundary.Y.Size)
throw new ArgumentException("Input points do not cover a square area.");
var result = points.ToList();
for (int i = 0; i < 5; i++)
{
var coeff = new Rational(2 * i + 1, 10);
result.Add(new Point2D(
boundary.X.Min + coeff * boundary.X.Size, boundary.Y.Min));
result.Add(new Point2D(
boundary.X.Min + coeff * boundary.X.Size, boundary.Y.Max));
result.Add(new Point2D(
boundary.X.Min, boundary.Y.Min + coeff * boundary.Y.Size));
result.Add(new Point2D(
boundary.X.Max, boundary.Y.Min + coeff * boundary.Y.Size));
}
return result.ToArray();
}
/// <summary>
/// Run Fortune's algorithm over a set of sites.
/// </summary>
/// <param name="sites">The input sites to the algorithm.</param>
/// <param name="listener">The listener </param>
public static void Execute(
IEnumerable<Point2D> sites, IFortunesAlgorithmListener listener)
{
if (null == sites)
throw new ArgumentNullException("sites");
if (null == listener)
throw new ArgumentNullException("listener");
var cachedSites = sites.ToList();
var uniqueSites = new SortedSet<Point2D>(cachedSites, new Point2DComparer());
if (uniqueSites.Contains(null))
throw new ArgumentNullException("sites");
if (uniqueSites.Count < cachedSites.Count)
throw new ArgumentException(
"Enumerable contains one or more duplicate points.", "sites");
if (uniqueSites.Count < 3)
throw new ArgumentException(
"Input sites are colinear.", "sites");
var siteEvents = new PriorityQueue<Circle2D>(
sites.Select(site => new Circle2D(site)), new CircleBottomComparer());
var topmostSites = RemoveTopmostSitesFromQueue(siteEvents);
if (siteEvents.IsEmpty)
throw new ArgumentException(
"Input sites are colinear.", "sites");
var beachLine = new BeachLine(topmostSites, listener);
while (true)
{
if (siteEvents.IsEmpty && beachLine.circleEvents.IsEmpty)
{
break;
}
else if (siteEvents.IsEmpty)
{
beachLine.RemoveArc(beachLine.circleEvents.Dequeue().Arc);
}
else if (beachLine.circleEvents.IsEmpty)
{
beachLine.AddSite(siteEvents.Dequeue().Center);
}
else
{
var site = siteEvents.Peek();
var circle = beachLine.circleEvents.Peek();
if (-1 == CircleBottomComparer.CompareCircles(
site, circle.Arc.Data.SqueezePoint))
beachLine.AddSite(siteEvents.Dequeue().Center);
else
beachLine.RemoveArc(beachLine.circleEvents.Dequeue().Arc);
}
}
if (false == beachLine.CircleEventHandled)
throw new ArgumentException("Input sites are colinear.", "sites");
beachLine.EmitRays();
listener.AlgorithmComplete();
}
private static List<Point2D> RemoveTopmostSitesFromQueue(
PriorityQueue<Circle2D> siteEvents)
{
var topmostSites = new List<Point2D>();
topmostSites.Add(siteEvents.Dequeue().Center);
while (!siteEvents.IsEmpty && siteEvents.Peek().Center.Y == topmostSites[0].Y)
topmostSites.Add(siteEvents.Dequeue().Center);
return topmostSites;
}
class CircleEvent : IComparable<CircleEvent>
{
public IBsllNode<BeachArc> Arc;
Circle2D initialSqueezePoint;
public CircleEvent(IBsllNode<BeachArc> arc)
{
Arc = arc;
initialSqueezePoint = arc.Data.SqueezePoint;
}
public bool IsStale
{
get { return Arc.Data.SqueezePoint != initialSqueezePoint; }
}
public int CompareTo(CircleEvent other)
{
if (null == other)
return -1;
return CircleBottomComparer.CompareCircles(
this.initialSqueezePoint, other.initialSqueezePoint);
}
}
class BeachArc
{
public Point2D Site;
public Circle2D SqueezePoint;
public BeachArc(Point2D site)
{
Site = site;
SqueezePoint = null;
}
}
class BeachLine
{
IComparer<Point2D> pointComparer = new Point2DComparer();
BinarySearchLinkedList<BeachArc> arcs;
public PriorityQueue<CircleEvent> circleEvents;
IFortunesAlgorithmListener listener;
SortedSet<Point2D> voronoiVertices;
SortedDictionary<Point2D, SortedDictionary<Point2D, Point2D>> voronoiRays;
public bool CircleEventHandled = false;
public BeachLine(List<Point2D> initialSites, IFortunesAlgorithmListener listener)
{
arcs = new BinarySearchLinkedList<BeachArc>(
initialSites.Select(site => new BeachArc(site)));
circleEvents = new PriorityQueue<CircleEvent>();
this.listener = listener;
InitializeListener(initialSites);
voronoiVertices = new SortedSet<Point2D>(pointComparer);
voronoiRays = new SortedDictionary<Point2D, SortedDictionary<Point2D, Point2D>>(
pointComparer);
}
void InitializeListener(List<Point2D> initialSites)
{
for (int i = 0; i < initialSites.Count; i++)
listener.EmitDelaunayVertex(initialSites[i]);
}
public void AddSite(Point2D site)
{
var searchResults = arcs.BinarySearch(site, ArcsBinarySearchDelegate);
listener.EmitDelaunayVertex(site);
IBsllNode<BeachArc> newArc;
if (1 == searchResults.Length)
{
var node = searchResults[0];
DeinitCircleEvent(node);
newArc = arcs.InsertAfter(node, new BeachArc(site));
arcs.InsertAfter(newArc, new BeachArc(node.Data.Site));
}
else
{
var left = searchResults[0];
var right = searchResults[1];
DeinitCircleEvent(left);
DeinitCircleEvent(right);
HandleVoronoiHalfEdges(left.Data.Site, site, right.Data.Site);
newArc = arcs.InsertAfter(left, new BeachArc(site));
}
InitCircleEvent(newArc.PrevNode);
InitCircleEvent(newArc.NextNode);
RemoveStaleCircleEvents();
}
static int ArcsBinarySearchDelegate(
Point2D searchValue, BeachArc predValue, BeachArc succValue)
{
return DetermineBeachLineArcIntersected(
searchValue, predValue.Site, succValue.Site);
}
public void RemoveArc(IBsllNode<BeachArc> arcNode)
{
var left = arcNode.PrevNode;
var right = arcNode.NextNode;
HandleVoronoiHalfEdges(left.Data.Site, arcNode.Data.Site, right.Data.Site);
DeinitCircleEvent(left);
DeinitCircleEvent(right);
arcs.Delete(arcNode);
InitCircleEvent(left);
InitCircleEvent(right);
RemoveStaleCircleEvents();
}
void InitCircleEvent(IBsllNode<BeachArc> arcNode)
{
if (null == arcNode || null == arcNode.PrevNode || null == arcNode.NextNode)
return;
var circumcircle = Circle2D.Circumcircle(
arcNode.PrevNode.Data.Site, arcNode.Data.Site, arcNode.NextNode.Data.Site);
if (null == circumcircle)
return;
var siteA = arcNode.PrevNode.Data.Site;
var siteB = arcNode.Data.Site;
var siteC = arcNode.NextNode.Data.Site;
var dxab = siteA.X - siteB.X;
var dyab = siteA.Y - siteB.Y;
var dxbc = siteC.X - siteB.X;
var dybc = siteC.Y - siteB.Y;
var det = dxab * dybc - dxbc * dyab;
if (det <= 0)
return;
arcNode.Data.SqueezePoint = circumcircle;
circleEvents.Enqueue(new CircleEvent(arcNode));
}
static void DeinitCircleEvent(IBsllNode<BeachArc> node)
{
if (null == node)
return;
node.Data.SqueezePoint = null;
}
void RemoveStaleCircleEvents()
{
while (false == circleEvents.IsEmpty && circleEvents.Peek().IsStale)
circleEvents.Dequeue();
}
void HandleVoronoiHalfEdges(Point2D site1, Point2D site2, Point2D site3)
{
CircleEventHandled = true;
var cc = Point2D.Circumcenter(site1, site2, site3);
if (!voronoiVertices.Contains(cc))
{
voronoiVertices.Add(cc);
listener.EmitVoronoiVertex(cc);
}
RecordHalfEdge(site1, site2, cc);
RecordHalfEdge(site2, site3, cc);
RecordHalfEdge(site3, site1, cc);
}
void RecordHalfEdge(Point2D siteA, Point2D siteB, Point2D endpoint)
{
if (voronoiRays.ContainsKey(siteA) && voronoiRays[siteA].ContainsKey(siteB))
{
var otherEndpoint = voronoiRays[siteA][siteB];
voronoiRays[siteA].Remove(siteB);
listener.EmitDualEdges(siteA, siteB, endpoint, otherEndpoint);
}
else if (voronoiRays.ContainsKey(siteB) &&
voronoiRays[siteB].ContainsKey(siteA))
{
var otherEndpoint = voronoiRays[siteB][siteA];
voronoiRays[siteB].Remove(siteA);
listener.EmitDualEdges(siteA, siteB, endpoint, otherEndpoint);
}
else
{
if (false == voronoiRays.ContainsKey(siteA))
voronoiRays.Add(siteA,
new SortedDictionary<Point2D, Point2D>(pointComparer));
voronoiRays[siteA].Add(siteB, endpoint);
}
}
public void EmitRays()
{
foreach (var entry in voronoiRays)
{
var site1 = entry.Key;
foreach (var subEntry in entry.Value)
{
var site2 = subEntry.Key;
var p = subEntry.Value;
listener.EmitDualEdges(site1, site2, p, null);
}
}
}
}
}
/// <summary>
/// Interface to listen for events in Fortune's algorithm and respond accordingly.
/// </summary>
public interface IFortunesAlgorithmListener
{
/// <summary>
/// Called when Fortune's algorithm encounters a site.
/// </summary>
/// <param name="p">The location of the site.</param>
void EmitDelaunayVertex(Point2D p);
/// <summary>
/// Called when Fortune's algorithm finds a Voronoi vertex. This is either
/// at circle events or when a site event intersects the beachline at one
/// of its intersection points.
/// </summary>
/// <param name="p">The location of the vertex.</param>
void EmitVoronoiVertex(Point2D p);
/// <summary>
/// Called when Fortune's algorithm identifies a dual pair of
/// Voronoi/Delaunay edges
/// </summary>
/// <param name="d1">The first endpoint of the Delaunay edge.</param>
/// <param name="d2">The second endpoint of the Delaunay edge.</param>
/// <param name="v1">The first endpoint of the Voronoi edge.</param>
/// <param name="v2">The second endpoint of the Voronoi edge, or null,
/// indicating that the Voronoi edge has one endpoint at infinity.
/// v2 may also be equal to v1.</param>
void EmitDualEdges(Point2D d1, Point2D d2, Point2D v1, Point2D v2);
/// <summary>
/// Called once all the vertices and edges of the Delaunay and Voronoi
/// graphs have been enumerated.
/// </summary>
void AlgorithmComplete();
}
#if INCLUDE_WORK_IN_PROGRESS
/// <summary>
/// Provides an implementation of the IFortunesAlgorithmListener interface
/// which produces a Graph2D object of the resulting graphs.
/// </summary>
public class GraphFortunesAlgorithmListener : IFortunesAlgorithmListener
{
/// <summary>
/// The Graph2D to which the output of Fortune's algorithm is recorded.
/// </summary>
public Graph2D Graph { get; private set; }
string delaunayColor;
string voronoiColor;
/// <summary>
/// Initializes a new instance of the GraphFortunesAlgorithmListener class.
/// </summary>
/// <param name="delaunayColor">
/// The color to apply to Delaunay diagram vertices/edges.</param>
/// <param name="voronoiColor">
/// The color to apply to Voronoi diagram vertices/edges.</param>
public GraphFortunesAlgorithmListener(string delaunayColor, string voronoiColor)
{
Graph = new Graph2D(false);
this.delaunayColor = delaunayColor;
this.voronoiColor = voronoiColor;
}
/// <summary>
/// Called when Fortune's algorithm encounters a site.
/// </summary>
/// <param name="p">The location of the site.</param>
public void EmitDelaunayVertex(Point2D p)
{
if (null == p)
throw new ArgumentNullException("p");
Graph.AddVertex(p);
Graph.SetVertexMetadatum(p, "color", delaunayColor);
}
/// <summary>
/// Called when Fortune's algorithm finds an edge between two input sites.
/// </summary>
/// <param name="p1">The first endpoint of the edge.</param>
/// <param name="p2">The second endpoint of the edge.</param>
public void EmitDelaunayEdge(Point2D p1, Point2D p2)
{
if (null == p1)
throw new ArgumentNullException("p1");
if (null == p2)
throw new ArgumentNullException("p2");
Graph.AddEdge(p1, p2);
Graph.SetEdgeMetadatum(p1, p2, "color", delaunayColor);
}
/// <summary>
/// Called when Fortune's algorithm finds a Voronoi vertex. This is either
/// at circle events or when a site event intersects the beachline at one
/// of its intersection points.
/// </summary>
/// <param name="p">The location of the vertex.</param>
public void EmitVoronoiVertex(Point2D p)
{
if (null == p)
throw new ArgumentNullException("p");
Graph.AddVertex(p);
Graph.SetVertexMetadatum(p, "color", voronoiColor);
}
/// <summary>
/// Called when Fortune's algorithm finds two Voronoi half-edges that
/// can be linked together.
/// </summary>
/// <param name="p1">The first endpoint of the edge.</param>
/// <param name="p2">The second endpoint of the edge.</param>
/// <param name="site1">The site on one side of the edge.</param>
/// <param name="site2">The site on the other side of the edge.</param>
public void EmitVoronoiEdge(Point2D p1, Point2D p2, Point2D site1, Point2D site2)
{
if (null == p1)
throw new ArgumentNullException("p1");
if (null == p2)
throw new ArgumentNullException("p2");
if (null == site1)
throw new ArgumentNullException("site1");
if (null == site2)
throw new ArgumentNullException("site2");
if (false == p1.Equals(p2))
{
Graph.AddEdge(p1, p2);
Graph.SetEdgeMetadatum(p1, p2, "color", voronoiColor);
}
}
/// <summary>
/// Called when Fortune's algorithm finds a Voronoi edge with one endpoint
/// at infinity.
/// </summary>
/// <param name="p">The finite endpoint of the edge.</param>
/// <param name="site1">The site on one side of the edge.</param>
/// <param name="site2">The site on the other side of the edge.</param>
public void EmitVoronoiRay(Point2D p, Point2D site1, Point2D site2)
{
}
}
#endif
} | 38.349005 | 97 | 0.527326 | [
"MIT"
] | SheepNine/UnaryHeap | source/UnaryHeap.Utilities/UnaryHeap.Utilities/FortunesAlgorithm.cs | 21,209 | C# |
using System;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using pdftron.Common;
using pdftron.SDF;
using TRN_ElementBuilder = System.IntPtr;
using TRN_Element = System.IntPtr;
namespace pdftron.PDF
{
/// <summary> ElementBuilder is used to build new PDF.Elements (e.g. image, text, path, etc)
/// from scratch. In conjunction with ElementWriter, ElementBuilder can be used to create
/// new page content.
///
/// </summary>
/// <remarks> Analogous to ElementReader, every call to ElementBuilder.Create? method destroys
/// the Element currently associated with the builder and all previous Element pointers are
/// invalidated. </remarks>
public class ElementBuilder : IDisposable
{
internal TRN_ElementBuilder mp_builder = IntPtr.Zero;
internal ElementBuilder(TRN_ElementBuilder imp)
{
this.mp_builder = imp;
}
/// <summary> Instantiates a new element builder.
///
/// </summary>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public ElementBuilder()
{
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreate(ref mp_builder));
}
/// <summary> The function sets the graphics state of this Element to the given value.
/// If 'gs' parameter is not specified or is NULL the function resets the
/// graphics state of this Element to the default graphics state (i.e. the
/// graphics state at the begining of the display list).
///
/// The function can be used in situations where the same ElementBuilder is used
/// to create content on several pages, XObjects, etc. If the graphics state is not
/// Reset() when moving to a new display list, the new Element will have the same
/// graphics state as the last Element in the previous display list (and this may
/// or may not be your intent).
///
/// Another use of Reset(gs) is to make sure that two Elements have the graphics
/// state.
///
/// </summary>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public void Reset()
{
Reset(null);
}
/// <summary> Reset.
///
/// </summary>
/// <param name="gs">the gs
/// </param>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public void Reset(GState gs)
{
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderReset(mp_builder, gs == null ? IntPtr.Zero : gs.mp_state));
}
// Image Element ------------------------------------------------
/// <summary> Create a content image Element out of a given document Image.
///
/// </summary>
/// <param name="img">the img
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateImage(Image img)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateImage(mp_builder, img.mp_image, ref result));
return new Element(result, this, img.m_ref);
}
/// <summary> Create a content image Element out of a given document Image.
///
/// </summary>
/// <param name="img">the img
/// </param>
/// <param name="mtx">the image transformation matrix.
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateImage(Image img, Matrix2D mtx)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateImageFromMatrix(mp_builder, img.mp_image, ref mtx.mp_mtx, ref result));
return new Element(result, this, img.m_ref);
}
/// <summary> Create a content image Element out of a given document Image with
/// the lower left corner at (x, y), and scale factors (hscale, vscale).
///
/// </summary>
/// <param name="img">the img
/// </param>
/// <param name="x">the x
/// </param>
/// <param name="y">the y
/// </param>
/// <param name="hscale">the hscale
/// </param>
/// <param name="vscale">the vscale
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateImage(Image img, Double x, Double y, Double hscale, Double vscale)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateImageScaled(mp_builder, img.mp_image, x, y, hscale, vscale, ref result));
return new Element(result, this, img.m_ref);
}
/// <summary> Create e_group_begin Element (i.e. 'q' operator in PDF content stream).
/// The function saves the current graphics state.
///
/// </summary>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateGroupBegin()
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateGroupBegin(mp_builder, ref result));
return new Element(result, this, null);
}
/// <summary> Create e_group_end Element (i.e. 'Q' operator in PDF content stream).
/// The function restores the previous graphics state.
///
/// </summary>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateGroupEnd()
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateGroupEnd(mp_builder, ref result));
return new Element(result, this, null);
}
/// <summary> Create a shading Element.
///
/// </summary>
/// <param name="sh">the sh
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateShading(Shading sh)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateShading(mp_builder, sh.mp_shade, ref result));
return new Element(result, this, sh.m_ref);
}
/// <summary> Create a Form XObject Element.
///
/// </summary>
/// <param name="form">a Form XObject content stream
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateForm(Obj form)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateFormFromStream(mp_builder, form.mp_obj, ref result));
return new Element(result, this, form.GetRefHandleInternal());
}
/// <summary> Create a Form XObject Element using the content of the existing page.
/// This method assumes that the XObject will be used in the same
/// document as the given page. If you need to create the Form XObject
/// in a different document use CreateForm(Page, Doc) method.
///
/// </summary>
/// <param name="page">A page used to create the Form XObject.
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateForm(Page page)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateFormFromPage(mp_builder, page.mp_page, ref result));
return new Element(result, this, page.m_ref);
}
/// <summary> Create a Form XObject Element using the content of the existing page.
/// Unlike CreateForm(Page) method, you can use this method to create form
/// in another document.
///
/// </summary>
/// <param name="page">A page used to create the Form XObject.
/// </param>
/// <param name="doc">Destination document for the Form XObject.
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateForm(Page page, PDFDoc doc)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateFormFromDoc(mp_builder, page.mp_page, doc.mp_doc, ref result));
return new Element(result, this, doc);
}
/// <summary> Start a text block ('BT' operator in PDF content stream).
/// The function installs the given font in the current graphics state.
///
/// </summary>
/// <param name="font">the font
/// </param>
/// <param name="font_sz">the font_sz
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateTextBegin(Font font, Double font_sz)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateTextBeginWithFont(mp_builder, font.mp_font, font_sz, ref result));
return new Element(result, this, font.m_ref);
}
/// <summary> Start a text block ('BT' operator in PDF content stream).
///
/// </summary>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateTextBegin()
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateTextBegin(mp_builder, ref result));
return new Element(result, this, null);
}
/// <summary> Ends a text block.
///
/// </summary>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateTextEnd()
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateTextEnd(mp_builder, ref result));
return new Element(result, this, null);
}
/// <summary> Create a text run using the given font.
///
/// </summary>
/// <param name="text_data">the text_data
/// </param>
/// <param name="font">the font
/// </param>
/// <param name="font_sz">the font_sz
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
/// <remarks> a text run can be created only within a text block </remarks>
public Element CreateTextRun(String text_data, Font font, Double font_sz)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateTextRun(mp_builder, text_data, font.mp_font, font_sz, ref result));
return new Element(result, this, font.m_ref);
}
/// <summary> Create a new text run.
///
/// </summary>
/// <param name="text_data">the text_data
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
/// <remarks> a text run can be created only within a text block
/// you must set the current Font and font size before calling this function. </remarks>
public Element CreateTextRun(String text_data)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateNewTextRun(mp_builder, text_data, ref result));
return new Element(result, this, null);
}
/// <summary> Create a new Unicode text run.
///
/// </summary>
/// <param name="text_data">the text_data
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
/// <remarks> you must set the current Font and font size before calling this function
/// and the font must be created using Font.CreateCIDTrueTypeFont() method.
/// a text run can be created only within a text block </remarks>
public Element CreateUnicodeTextRun(String text_data)
{
TRN_Element result = IntPtr.Zero;
IntPtr text_data_ptr = Marshal.StringToHGlobalUni(text_data);
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateUnicodeTextRun(mp_builder, text_data_ptr, System.Convert.ToUInt32(text_data.ToCharArray().Length), ref result));
return new Element(result, this, null);
}
/// <summary> Create a new Unicode text run.
///
/// </summary>
/// <param name="text_data">the text_data
/// </param>
/// <param name="font">font for the text run
/// </param>
/// <param name="font_sz">size of the font
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
/// <remarks> you must set the current Font and font size before calling this function
/// and the font must be created using Font.CreateCIDTrueTypeFont() method.
/// a text run can be created only within a text block </remarks>
public Element CreateUnicodeTextRun(String text_data, Font font, Double font_sz)
{
TRN_Element result = IntPtr.Zero;
IntPtr text_data_ptr = Marshal.StringToHGlobalUni(text_data);
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateUnicodeTextRun(mp_builder, text_data_ptr, System.Convert.ToUInt32(text_data.ToCharArray().Length), ref result));
return new Element(result, this, null);
}
/// <summary> Create e_text_new_line Element (i.e. a Td operator in PDF content stream).
/// Move to the start of the next line, offset from the start of the current
/// line by (dx , dy). dx and dy are numbers expressed in unscaled text space
/// units.
///
/// </summary>
/// <param name="dx">the dx
/// </param>
/// <param name="dy">the dy
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateTextNewLine(Double dx, Double dy)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateTextNewLineWithOffset(mp_builder, dx, dy, ref result));
return new Element(result, this, null);
}
/// <summary> Create e_text_new_line Element (i.e. a T* operator in PDF content stream).
///
/// </summary>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateTextNewLine()
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateTextNewLine(mp_builder, ref result));
return new Element(result, this, null);
}
// Path Element -------------------------------------------------
/// <summary> Create a rectangle path Element.
///
/// </summary>
/// <param name="x">the x
/// </param>
/// <param name="y">the y
/// </param>
/// <param name="width">the width
/// </param>
/// <param name="height">the height
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateRect(Double x, Double y, Double width, Double height)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateRect(mp_builder, x, y, width, height, ref result));
return new Element(result, this, null);
}
/// <summary> Create an ellipse (or circle, if rx == ry) path Element.
///
/// </summary>
/// <param name="cx">the cx
/// </param>
/// <param name="cy">the cy
/// </param>
/// <param name="rx">the rx
/// </param>
/// <param name="ry">the ry
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreateEllipse(Double cx, Double cy, Double rx, Double ry)
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreateEllipse(mp_builder, cx, cy, rx, ry, ref result));
return new Element(result, this, null);
}
//Element CreatePath(const Double points[], Int32 point_count, const Byte seg_types[], Int32 seg_types_count);
/// <summary> Create a path Element using given path segment data.
///
/// </summary>
/// <param name="points">the points
/// </param>
/// <param name="point_count">number of points in points array
/// </param>
/// <param name="seg_types_count">number of segment types in seg_types array
/// </param>
/// <param name="seg_types">the seg_types
/// </param>
/// <returns> the element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element CreatePath(double[] points, int point_count, byte[] seg_types, int seg_types_count)
{
TRN_Element result = IntPtr.Zero;
int psize = Marshal.SizeOf(seg_types[0]) * seg_types.Length;
IntPtr pnt = Marshal.AllocHGlobal(psize);
int psize2 = Marshal.SizeOf(points[0]) * points.Length;
IntPtr pnt2 = Marshal.AllocHGlobal(psize2);
try
{
Marshal.Copy(seg_types, 0, pnt, seg_types.Length);
Marshal.Copy(points, 0, pnt2, points.Length);
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCreatePath(mp_builder, pnt2, point_count, pnt, seg_types_count, ref result));
return new Element(result, this, null);
}
finally
{
// Free the unmanaged memory.
Marshal.FreeHGlobal(pnt);
Marshal.FreeHGlobal(pnt2);
}
}
/// <summary> Starts building a new path Element that can contain an arbitrary sequence
/// of lines, curves, and rectangles.
///
/// </summary>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public void PathBegin()
{
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderPathBegin(mp_builder));
}
/// <summary> Finishes building of the path Element.
///
/// </summary>
/// <returns> the path Element
/// </returns>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public Element PathEnd()
{
TRN_Element result = IntPtr.Zero;
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderPathEnd(mp_builder, ref result));
return new Element(result, this, null);
}
/// <summary> Add a rectangle to the current path as a complete subpath.
/// Setting the current point is not required before using this function.
///
/// </summary>
/// <param name="x">the x
/// </param>
/// <param name="y">the y
/// </param>
/// <param name="width">the width
/// </param>
/// <param name="height">the height
/// </param>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public void Rect(Double x, Double y, Double width, Double height)
{
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderRect(mp_builder, x, y, width, height));
}
/// <summary> Set the current point.
///
/// </summary>
/// <param name="x">the x
/// </param>
/// <param name="y">the y
/// </param>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public void MoveTo(Double x, Double y)
{
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderMoveTo(mp_builder, x, y));
}
/// <summary> Draw a line from the current point to the given point.
///
/// </summary>
/// <param name="x">the x
/// </param>
/// <param name="y">the y
/// </param>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public void LineTo(Double x, Double y)
{
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderLineTo(mp_builder, x, y));
}
/// <summary> Draw a Bezier curve from the current point to the given point (x2, y2) using
/// (cx1, cy1) and (cx2, cy2) as control points.
///
/// </summary>
/// <param name="cx1">the cx1
/// </param>
/// <param name="cy1">the cy1
/// </param>
/// <param name="cx2">the cx2
/// </param>
/// <param name="cy2">the cy2
/// </param>
/// <param name="x2">the x2
/// </param>
/// <param name="y2">the y2
/// </param>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public void CurveTo(Double cx1, Double cy1, Double cx2, Double cy2, Double x2, Double y2)
{
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderCurveTo(mp_builder, cx1, cy1, cx2, cy2, x2, y2));
}
/// <summary> Draw an arc with the specified parameters (upper left corner, width, height and angles).
///
/// </summary>
/// <param name="x">the x
/// </param>
/// <param name="y">the y
/// </param>
/// <param name="width">the width
/// </param>
/// <param name="height">the height
/// </param>
/// <param name="start"> starting angle of the arc in degrees
/// </param>
/// <param name="extent"> angular extent of the arc in degrees
/// </param>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public void ArcTo(Double x, Double y, Double width, Double height, Double start, Double extent)
{
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderArcTo(mp_builder, x, y, width, height, start, extent));
}
/// <summary> Draw an arc from the current point to the end point.
///
/// </summary>
/// <param name="xr">the xr
/// </param>
/// <param name="yr">the yr
/// </param>
/// <param name="rx"> x-axis rotation in degrees
/// </param>
/// <param name="isLargeArc"> indicates if smaller or larger arc is chosen
/// 1 - one of the two larger arc sweeps is chosen
/// 0 - one of the two smaller arc sweeps is chosen
/// </param>
/// <param name="sweep"> direction in which arc is drawn (1 - clockwise, 0 - counterclockwise)
/// </param>
/// <param name="endX">the end x
/// </param>
/// <param name="endY">the end y
/// </param>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
/// <remarks>The Arc is defined the same way as it is specified by SVG or XPS standards. For
/// further questions please refer to the XPS or SVG standards. </remarks>
public void ArcTo(Double xr, Double yr, Double rx, Boolean isLargeArc, Boolean sweep, Double endX, Double endY)
{
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderArcTo2(mp_builder, xr, yr, rx, isLargeArc, sweep, endX, endY));
}
/// <summary> Add an ellipse (or circle, if rx == ry) to the current path as a complete subpath.
/// Setting the current point is not required before using this function.
///
/// </summary>
/// <param name="cx">the cx
/// </param>
/// <param name="cy">the cy
/// </param>
/// <param name="rx">the rx
/// </param>
/// <param name="ry">the ry
/// </param>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public void Ellipse(double cx, double cy, double rx, double ry)
{
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderEllipse(mp_builder, cx, cy, rx, ry));
}
/// <summary> Closes the current subpath.
///
/// </summary>
/// <exception cref="PDFNetException"> PDFNetException the PDFNet exception </exception>
public void ClosePath()
{
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderClosePath(mp_builder));
}
/// <summary> Releases all resources used by the ElementBuilder </summary>
~ElementBuilder()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (disposing)
{
// Dispose managed resources.
}
// Clean up native resources
Destroy();
}
public void Destroy()
{
if (mp_builder != IntPtr.Zero)
{
PDFNetException.REX(PDFNetPINVOKE.TRN_ElementBuilderDestroy(mp_builder));
mp_builder = IntPtr.Zero;
}
}
}
} | 43.56869 | 183 | 0.588509 | [
"MIT"
] | moljac/Samples.AndroidX | samples/issues/0014/to-Xamarin/Common/PDF/ElementBuilder.cs | 27,274 | C# |
using System.Collections.Generic;
namespace Plugin.PushNotification
{
public interface IPushNotificationHandler
{
//Method triggered when an error occurs
void OnError(string error);
//Method triggered when a notification is opened by tapping an action
void OnAction(NotificationResponse response);
//Method triggered when a notification is opened
void OnOpened(NotificationResponse response);
//Method triggered when a notification is received
void OnReceived(IDictionary<string, object> parameters);
}
}
| 34.294118 | 77 | 0.718696 | [
"MIT"
] | CrossGeeks/PushNotificationPlugin | src/Plugin.PushNotification/IPushNotificationHandler.shared.cs | 585 | C# |
using System.ComponentModel;
namespace StatusBar.Core
{
public interface IMessageItem : INotifyPropertyChanged
{
string Id { get; }
string Message { get; }
MessageTypes MsgType { get; }
bool Accepted { get; set; }
}
}
| 20.307692 | 58 | 0.617424 | [
"Apache-2.0"
] | lothrop/StatusBar.iOS | StatusBar.Core/IMessageItem.cs | 266 | C# |
using System;
using SlothEnterprise.ProductApplication.Adapters;
using SlothEnterprise.ProductApplication.Applications;
namespace SlothEnterprise.ProductApplication
{
public class ProductApplicationService
{
private readonly ISubmissionServiceFactory _submissionServiceFactory;
public ProductApplicationService(ISubmissionServiceFactory submissionServiceFactory)
{
_submissionServiceFactory = submissionServiceFactory;
}
public int SubmitApplicationFor(ISellerApplication application)
{
if (application == null)
throw new ArgumentNullException(nameof(application));
var service = _submissionServiceFactory.GetService(application.Product);
return service.SubmitApplicationFor(application);
}
}
}
| 30.851852 | 92 | 0.728691 | [
"MIT"
] | igorslobodyanyuk/SlothEnterprise | SlothEnterprise.ProductApplication/ProductApplicationService.cs | 835 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Common.Core.Shell;
using Microsoft.Languages.Editor.Settings;
using Microsoft.Markdown.Editor.Commands;
using Microsoft.Markdown.Editor.ContentTypes;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.Languages.Editor.Application.Packages {
[ExcludeFromCodeCoverage]
[Export(typeof(IWpfTextViewConnectionListener))]
[ContentType(MdContentTypeDefinition.ContentType)]
[TextViewRole(PredefinedTextViewRoles.Document)]
[Name("Markdown Text View Connection Listener")]
[Order(Before = "Default")]
internal sealed class TestMdTextViewConnectionListener : MdTextViewConnectionListener {
[ImportingConstructor]
public TestMdTextViewConnectionListener(ICoreShell coreShell): base(coreShell.Services) { }
}
[ExcludeFromCodeCoverage]
[Export(typeof(IWritableEditorSettingsStorage))]
[ContentType(MdContentTypeDefinition.ContentType)]
[Name("Markdown Test settings")]
[Order(Before = "Default")]
internal sealed class MdSettingsStorage : SettingsStorage { }
}
| 41.40625 | 99 | 0.787925 | [
"MIT"
] | Bhaskers-Blu-Org2/RTVS | src/Windows/EditorTestApp/Packages/MarkdownPackage.cs | 1,327 | 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.Logz.Models.Api20201001Preview
{
using static Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Extensions;
public partial class LogzMonitorResource
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.ILogzMonitorResource.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.ILogzMonitorResource.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.ILogzMonitorResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject json ? new LogzMonitorResource(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject into a new instance of <see cref="LogzMonitorResource" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject instance to deserialize from.</param>
internal LogzMonitorResource(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_systemData = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject>("systemData"), out var __jsonSystemData) ? Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20.SystemData.FromJson(__jsonSystemData) : SystemData;}
{_property = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject>("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.MonitorProperties.FromJson(__jsonProperties) : Property;}
{_identity = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject>("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.IdentityProperties.FromJson(__jsonIdentity) : Identity;}
{_id = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonString>("id"), out var __jsonId) ? (string)__jsonId : (string)Id;}
{_name = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonString>("name"), out var __jsonName) ? (string)__jsonName : (string)Name;}
{_type = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonString>("type"), out var __jsonType) ? (string)__jsonType : (string)Type;}
{_tag = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject>("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.LogzMonitorResourceTags.FromJson(__jsonTags) : Tag;}
{_location = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonString>("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="LogzMonitorResource" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="LogzMonitorResource" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add );
}
AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add );
AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add );
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add );
}
AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add );
AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add );
AfterToJson(ref container);
return container;
}
}
} | 80.916031 | 277 | 0.694528 | [
"MIT"
] | Agazoth/azure-powershell | src/Logz/generated/api/Models/Api20201001Preview/LogzMonitorResource.json.cs | 10,470 | C# |
using System;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace UWPCode.Views
{
public sealed partial class Splash : UserControl
{
public Splash(SplashScreen splashScreen)
{
InitializeComponent();
Window.Current.SizeChanged += (s, e) => Resize(splashScreen);
Resize(splashScreen);
Opacity = 0;
}
private void Resize(SplashScreen splashScreen)
{
if (splashScreen.ImageLocation.Top == 0)
{
splashImage.Visibility = Visibility.Collapsed;
return;
}
else
{
rootCanvas.Background = null;
splashImage.Visibility = Visibility.Visible;
}
splashImage.Height = splashScreen.ImageLocation.Height;
splashImage.Width = splashScreen.ImageLocation.Width;
splashImage.SetValue(Canvas.TopProperty, splashScreen.ImageLocation.Top);
splashImage.SetValue(Canvas.LeftProperty, splashScreen.ImageLocation.Left);
ProgressTransform.TranslateY = splashImage.Height / 2;
}
private void Image_Loaded(object sender, RoutedEventArgs e)
{
Opacity = 1;
}
}
}
| 30.204545 | 87 | 0.595937 | [
"BSD-2-Clause"
] | MinhTuanTran/UWPCode | UWPCode/Views/Splash.xaml.cs | 1,329 | C# |
using Coldairarrow.Business.MiniPrograms;
using Coldairarrow.Entity.MiniPrograms;
using Coldairarrow.Util;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Coldairarrow.Api.Controllers.MiniPrograms
{
[Route("/MiniPrograms/[controller]/[action]")]
public class mini_pageController : BaseApiController
{
#region DI
public mini_pageController(Imini_pageBusiness mini_moduleBus)
{
_mini_moduleBus = mini_moduleBus;
}
Imini_pageBusiness _mini_moduleBus { get; }
#endregion
#region 获取
/// <summary>
/// 页面管理--查询(分页)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost]
public async Task<PageResult<Mini_PageDTO>> GetDataList(PageInput<ConditionDTO> input)
{
return await _mini_moduleBus.GetDataListAsync(input);
}
/// <summary>
/// 页面管理下拉框
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost]
public async Task<List<SelectOption>> GetOptionListAsync(OptionListInputDTO input)
{
return await _mini_moduleBus.GetOptionListAsync(input);
}
/// <summary>
/// 页面管理下拉框(包含历史失效的数据)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost]
public async Task<List<SelectOption>> GetALLOptionList(OptionListInputDTO input)
{
return await _mini_moduleBus.GetALLOptionList(input);
}
[HttpPost]
public async Task<mini_page> GetTheData(IdInputDTO input)
{
return await _mini_moduleBus.GetTheDataAsync(input.id);
}
#endregion
#region 提交
[HttpPost]
public async Task SaveData(mini_page data)
{
if (data.Id.IsNullOrEmpty())
{
InitEntity(data);
await _mini_moduleBus.AddDataAsync(data);
}
else
{
await _mini_moduleBus.UpdateDataAsync(data);
}
}
/// <summary>
/// 删除页面
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[HttpPost]
public async Task DeleteData(List<string> ids)
{
await _mini_moduleBus.DeleteDataAsync(ids);
}
#endregion
}
} | 26.092784 | 94 | 0.563019 | [
"MIT"
] | fanxinshun/HS.Admin.AntVue | src/Coldairarrow.Api/Controllers/MiniPrograms/mini_pageController.cs | 2,611 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using MinVer.Lib;
namespace MinVerTests.Lib.Infra
{
internal class TestLogger : ILogger
{
#if NET6_0_OR_GREATER
private readonly List<LogMessage> messages = new();
#else
private readonly List<LogMessage> messages = new List<LogMessage>();
#endif
public bool IsTraceEnabled => true;
public bool IsDebugEnabled => true;
public bool IsInfoEnabled => true;
public bool IsWarnEnabled => true;
public IEnumerable<LogMessage> Messages => this.messages;
public bool Trace(string message)
{
this.messages.Add(new LogMessage(LogLevel.Trace, message, 0));
return true;
}
public bool Debug(string message)
{
this.messages.Add(new LogMessage(LogLevel.Debug, message, 0));
return true;
}
public bool Info(string message)
{
this.messages.Add(new LogMessage(LogLevel.Info, message, 0));
return true;
}
public bool Warn(int code, string message)
{
this.messages.Add(new LogMessage(LogLevel.Warn, message, 0));
return true;
}
public override string ToString() => string.Join(Environment.NewLine, this.Messages.Select(message => message.ToString()));
}
}
| 27.056604 | 132 | 0.59484 | [
"Apache-2.0"
] | adamralph/min-ver | MinVerTests.Lib/Infra/TestLogger.cs | 1,434 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
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 DXPropertyGrid
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
}
public class ViewModel
{
public Customer DemoCustomer { get; set; }
public ViewModel()
{
DemoCustomer = new Customer()
{
ID = 0,
Name = "Anita Benson",
Email = "Anita_Benson@example.com",
Phone = "7138638137",
Products = new ProductList {
new Book
{
ID = 47583,
Author = "Arthur Cane",
Title = "Digging deeper",
Price = 14.79
}
}
};
}
}
public class Customer
{
[Browsable(false), ReadOnly(true)]
public int ID { get; set; }
[Category("Customer Info"), Description("Customer's full name")]
public string Name { get; set; }
[Category("Contact"), Description("Customer's email address")]
public string Email { get; set; }
[Category("Contact"), Description("Customer's phone number")]
public string Phone { get; set; }
[Category("Order Info"), Description("Ordered items"), DisplayName("Ordered Items")]
public ProductList Products { get; set; }
}
public class Book
{
[DisplayName("ISBN")]
public int ID { get; set; }
public string Author { get; set; }
public string Title { get; set; }
public double Price { get; set; }
}
public class ProductList : List<Object>
{
public ProductList() : base() { }
public override string ToString()
{
return "Product List";
}
}
}
| 20.265957 | 86 | 0.673491 | [
"MIT"
] | yacper/DevexpressLearning | Devexpress/Controls/PropertyGrid/4.Attributes/MainWindow.xaml.cs | 1,905 | C# |
using System;
using System.Diagnostics;
namespace EfEnumToLookup.LookupGenerator
{
/// <summary>
/// Information needed to construct a foreign key from a referencing
/// table to a generated enum lookup.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
internal class EnumReference
{
public string ReferencingTable { get; set; }
public string ReferencingField { get; set; }
public Type EnumType { get; set; }
// ReSharper disable once UnusedMember.Local
private string DebuggerDisplay
{
get { return string.Format("EnumReference: {0}.{1} ({2})", ReferencingTable, ReferencingField, EnumType.Name); }
}
}
}
| 26.708333 | 115 | 0.722309 | [
"MIT"
] | timabell/ef-enum-to-lookup | EfEnumToLookup/LookupGenerator/EnumReference.cs | 641 | C# |
#pragma checksum "..\..\UX.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "F7C626C187FBC3BF3A1BA07F9C5E22AB277AD06E"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
using notesdb;
namespace notesdb {
/// <summary>
/// UX
/// </summary>
public partial class UX : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/notesdb;component/ux.xaml", System.UriKind.Relative);
#line 1 "..\..\UX.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
this._contentLoaded = true;
}
}
}
| 38.315789 | 141 | 0.663462 | [
"MIT"
] | romero126/Devops-Toolkit | notesdb/obj/Debug/UX.g.cs | 2,914 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CryptoLab.Domain.Domain;
using CryptoLab.Domain.IRepositories;
using CryptoLab.Infrastructure.IServices;
using System.Linq;
using CryptoLab.Infrastructure.CryptoCompareApi;
using AutoMapper;
using CryptoLab.Infrastructure.DTO;
namespace CryptoLab.Infrastructure.Services
{
public class WalletService : IWalletService
{
private readonly IWalletRepository _walletRepository;
private readonly IUserRepository _userRepository;
private readonly IMapper _mapper;
public WalletService(IWalletRepository walletRepository, IUserRepository userRepository, IMapper mapper)
{
_walletRepository = walletRepository;
_userRepository = userRepository;
_mapper = mapper;
}
public async Task<IEnumerable<WalletDto>> GetAllAsync(Guid userId)
{
var userWallets = await _walletRepository.GetByUserIdAsync(userId);
return _mapper.Map<IEnumerable<Wallet>, IEnumerable<WalletDto>>(userWallets);
}
public async Task AddAsync(IEnumerable<string> currencies, Guid userId)
{
var user = await _userRepository.FindAsync(userId);
var userWallets = await _walletRepository.GetByUserIdAsync(userId);
decimal amountOfMoney = 0.0m;
foreach(var currency in currencies)
{
var walletIsExist = userWallets.Select(x => x.Currency == currency).FirstOrDefault();
if(walletIsExist == true)
throw new Exception("This wallet is exist for this user");
if(currency == "USD")
amountOfMoney = 50000;
else amountOfMoney = 0;
var wallet = new Wallet(currency, amountOfMoney, user);
await _walletRepository.AddAsync(wallet);
}
}
}
} | 34.701754 | 112 | 0.649141 | [
"MIT"
] | szatkoaleksander/CryptoLab | CryptoLab.Infrastructure/Services/WalletService.cs | 1,978 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using AutoMapper;
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Commands.Compute.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute
{
[Cmdlet("Remove", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VMSqlServerExtension")]
[OutputType(typeof(PSAzureOperationResponse))]
public class RemoveAzureVMSqlServerExtensionCommand : VirtualMachineExtensionBaseCmdlet
{
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ResourceGroupCompleter()]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Alias("ResourceName")]
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The virtual machine name.")]
[ValidateNotNullOrEmpty]
public string VMName { get; set; }
[Alias("ExtensionName")]
[Parameter(
Mandatory = true,
Position = 2,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Name of the ARM resource that represents the extension. This is defaulted to 'Microsoft.SqlServer.Management.SqlIaaSAgent'.")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ExecuteClientAction(() =>
{
if (string.IsNullOrEmpty(Name))
{
Name = VirtualMachineSqlServerExtensionContext.ExtensionPublishedNamespace + "." + VirtualMachineSqlServerExtensionContext.ExtensionPublishedName;
}
if (this.ShouldContinue(Properties.Resources.VirtualMachineExtensionRemovalConfirmation, Properties.Resources.VirtualMachineExtensionRemovalCaption))
{
var op = this.VirtualMachineExtensionClient.DeleteWithHttpMessagesAsync(
this.ResourceGroupName,
this.VMName,
this.Name).GetAwaiter().GetResult();
var result = ComputeAutoMapperProfile.Mapper.Map<PSAzureOperationResponse>(op);
WriteObject(result);
}
});
}
}
}
| 42.417722 | 167 | 0.604596 | [
"MIT"
] | FonsecaSergio/azure-powershell | src/ResourceManager/Compute/Commands.Compute/Extension/SqlServer/RemoveAzureVMSqlServerExtensionCommand.cs | 3,275 | 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.Buffers;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal
{
internal sealed partial class SocketConnection : TransportConnection
{
private static readonly int MinAllocBufferSize = PinnedBlockMemoryPool.BlockSize / 2;
private readonly Socket _socket;
private readonly ISocketsTrace _trace;
private readonly SocketReceiver _receiver;
private SocketSender? _sender;
private readonly SocketSenderPool _socketSenderPool;
private readonly IDuplexPipe _originalTransport;
private readonly CancellationTokenSource _connectionClosedTokenSource = new CancellationTokenSource();
private readonly object _shutdownLock = new object();
private volatile bool _socketDisposed;
private volatile Exception? _shutdownReason;
private Task? _sendingTask;
private Task? _receivingTask;
private readonly TaskCompletionSource _waitForConnectionClosedTcs = new TaskCompletionSource();
private bool _connectionClosed;
private readonly bool _waitForData;
private int _connectionStarted;
internal SocketConnection(Socket socket,
MemoryPool<byte> memoryPool,
PipeScheduler transportScheduler,
ISocketsTrace trace,
SocketSenderPool socketSenderPool,
PipeOptions inputOptions,
PipeOptions outputOptions,
bool waitForData = true)
{
Debug.Assert(socket != null);
Debug.Assert(memoryPool != null);
Debug.Assert(trace != null);
_socket = socket;
MemoryPool = memoryPool;
_trace = trace;
_waitForData = waitForData;
_socketSenderPool = socketSenderPool;
LocalEndPoint = _socket.LocalEndPoint;
RemoteEndPoint = _socket.RemoteEndPoint;
ConnectionClosed = _connectionClosedTokenSource.Token;
// On *nix platforms, Sockets already dispatches to the ThreadPool.
// Yes, the IOQueues are still used for the PipeSchedulers. This is intentional.
// https://github.com/aspnet/KestrelHttpServer/issues/2573
var awaiterScheduler = OperatingSystem.IsWindows() ? transportScheduler : PipeScheduler.Inline;
_receiver = new SocketReceiver(awaiterScheduler);
var pair = DuplexPipe.CreateConnectionPair(inputOptions, outputOptions);
_originalTransport = pair.Transport;
Application = pair.Application;
Transport = new SocketDuplexPipe(this);
InitializeFeatures();
}
public IDuplexPipe InnerTransport => _originalTransport;
public PipeWriter Input => Application.Output;
public PipeReader Output => Application.Input;
public override MemoryPool<byte> MemoryPool { get; }
private void EnsureStarted()
{
if (_connectionStarted == 1 || Interlocked.CompareExchange(ref _connectionStarted, 1, 0) == 1)
{
return;
}
// Offload these to avoid potentially blocking the first read/write/flush
_receivingTask = Task.Run(DoReceive);
_sendingTask = Task.Run(DoSend);
}
public override void Abort(ConnectionAbortedException abortReason)
{
// Try to gracefully close the socket to match libuv behavior.
Shutdown(abortReason);
// Cancel ProcessSends loop after calling shutdown to ensure the correct _shutdownReason gets set.
Output.CancelPendingRead();
}
// Only called after connection middleware is complete which means the ConnectionClosed token has fired.
public override async ValueTask DisposeAsync()
{
// Just in case we haven't started the connection, start it here so we can clean up properly.
EnsureStarted();
_originalTransport.Input.Complete();
_originalTransport.Output.Complete();
try
{
// Now wait for both to complete
if (_receivingTask != null)
{
await _receivingTask;
}
if (_sendingTask != null)
{
await _sendingTask;
}
}
catch (Exception ex)
{
_trace.LogError(0, ex, $"Unexpected exception in {nameof(SocketConnection)}.");
}
finally
{
_receiver.Dispose();
_sender?.Dispose();
}
_connectionClosedTokenSource.Dispose();
}
private async Task DoReceive()
{
Exception? error = null;
try
{
while (true)
{
if (_waitForData)
{
// Wait for data before allocating a buffer.
await _receiver.WaitForDataAsync(_socket);
}
// Ensure we have some reasonable amount of buffer space
var buffer = Input.GetMemory(MinAllocBufferSize);
var bytesReceived = await _receiver.ReceiveAsync(_socket, buffer);
if (bytesReceived == 0)
{
// FIN
_trace.ConnectionReadFin(this);
break;
}
Input.Advance(bytesReceived);
var flushTask = Input.FlushAsync();
var paused = !flushTask.IsCompleted;
if (paused)
{
_trace.ConnectionPause(this);
}
var result = await flushTask;
if (paused)
{
_trace.ConnectionResume(this);
}
if (result.IsCompleted || result.IsCanceled)
{
// Pipe consumer is shut down, do we stop writing
break;
}
}
}
catch (SocketException ex) when (IsConnectionResetError(ex.SocketErrorCode))
{
// This could be ignored if _shutdownReason is already set.
error = new ConnectionResetException(ex.Message, ex);
// There's still a small chance that both DoReceive() and DoSend() can log the same connection reset.
// Both logs will have the same ConnectionId. I don't think it's worthwhile to lock just to avoid this.
if (!_socketDisposed)
{
_trace.ConnectionReset(this);
}
}
catch (Exception ex)
when ((ex is SocketException socketEx && IsConnectionAbortError(socketEx.SocketErrorCode)) ||
ex is ObjectDisposedException)
{
// This exception should always be ignored because _shutdownReason should be set.
error = ex;
if (!_socketDisposed)
{
// This is unexpected if the socket hasn't been disposed yet.
_trace.ConnectionError(this, error);
}
}
catch (Exception ex)
{
// This is unexpected.
error = ex;
_trace.ConnectionError(this, error);
}
finally
{
// If Shutdown() has already bee called, assume that was the reason ProcessReceives() exited.
Input.Complete(_shutdownReason ?? error);
FireConnectionClosed();
await _waitForConnectionClosedTcs.Task;
}
}
private async Task DoSend()
{
Exception? shutdownReason = null;
Exception? unexpectedError = null;
try
{
while (true)
{
var result = await Output.ReadAsync();
if (result.IsCanceled)
{
break;
}
var buffer = result.Buffer;
if (!buffer.IsEmpty)
{
_sender = _socketSenderPool.Rent();
await _sender.SendAsync(_socket, buffer);
// We don't return to the pool if there was an exception, and
// we keep the _sender assigned so that we can dispose it in StartAsync.
_socketSenderPool.Return(_sender);
_sender = null;
}
Output.AdvanceTo(buffer.End);
if (result.IsCompleted)
{
break;
}
}
}
catch (SocketException ex) when (IsConnectionResetError(ex.SocketErrorCode))
{
shutdownReason = new ConnectionResetException(ex.Message, ex);
_trace.ConnectionReset(this);
}
catch (Exception ex)
when ((ex is SocketException socketEx && IsConnectionAbortError(socketEx.SocketErrorCode)) ||
ex is ObjectDisposedException)
{
// This should always be ignored since Shutdown() must have already been called by Abort().
shutdownReason = ex;
}
catch (Exception ex)
{
shutdownReason = ex;
unexpectedError = ex;
_trace.ConnectionError(this, unexpectedError);
}
finally
{
Shutdown(shutdownReason);
// Complete the output after disposing the socket
Output.Complete(unexpectedError);
// Cancel any pending flushes so that the input loop is un-paused
Input.CancelPendingFlush();
}
}
private void FireConnectionClosed()
{
// Guard against scheduling this multiple times
if (_connectionClosed)
{
return;
}
_connectionClosed = true;
ThreadPool.UnsafeQueueUserWorkItem(state =>
{
state.CancelConnectionClosedToken();
state._waitForConnectionClosedTcs.TrySetResult();
},
this,
preferLocal: false);
}
private void Shutdown(Exception? shutdownReason)
{
lock (_shutdownLock)
{
if (_socketDisposed)
{
return;
}
// Make sure to close the connection only after the _aborted flag is set.
// Without this, the RequestsCanBeAbortedMidRead test will sometimes fail when
// a BadHttpRequestException is thrown instead of a TaskCanceledException.
_socketDisposed = true;
// shutdownReason should only be null if the output was completed gracefully, so no one should ever
// ever observe the nondescript ConnectionAbortedException except for connection middleware attempting
// to half close the connection which is currently unsupported.
_shutdownReason = shutdownReason ?? new ConnectionAbortedException("The Socket transport's send loop completed gracefully.");
_trace.ConnectionWriteFin(this, _shutdownReason.Message);
try
{
// Try to gracefully close the socket even for aborts to match libuv behavior.
_socket.Shutdown(SocketShutdown.Both);
}
catch
{
// Ignore any errors from Socket.Shutdown() since we're tearing down the connection anyway.
}
_socket.Dispose();
}
}
private void CancelConnectionClosedToken()
{
try
{
_connectionClosedTokenSource.Cancel();
}
catch (Exception ex)
{
_trace.LogError(0, ex, $"Unexpected exception in {nameof(SocketConnection)}.{nameof(CancelConnectionClosedToken)}.");
}
}
private static bool IsConnectionResetError(SocketError errorCode)
{
return errorCode == SocketError.ConnectionReset ||
errorCode == SocketError.Shutdown ||
(errorCode == SocketError.ConnectionAborted && OperatingSystem.IsWindows());
}
private static bool IsConnectionAbortError(SocketError errorCode)
{
// Calling Dispose after ReceiveAsync can cause an "InvalidArgument" error on *nix.
return errorCode == SocketError.OperationAborted ||
errorCode == SocketError.Interrupted ||
(errorCode == SocketError.InvalidArgument && !OperatingSystem.IsWindows());
}
}
}
| 36.34375 | 141 | 0.536328 | [
"Apache-2.0"
] | phenning/AspNetCore | src/Servers/Kestrel/Transport.Sockets/src/Internal/SocketConnection.cs | 13,956 | C# |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
#pragma warning disable
using System;
using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Endo;
namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier
{
public class GlvMultiplier
: AbstractECMultiplier
{
protected readonly ECCurve curve;
protected readonly GlvEndomorphism glvEndomorphism;
public GlvMultiplier(ECCurve curve, GlvEndomorphism glvEndomorphism)
{
if (curve == null || curve.Order == null)
throw new ArgumentException("Need curve with known group order", "curve");
this.curve = curve;
this.glvEndomorphism = glvEndomorphism;
}
protected override ECPoint MultiplyPositive(ECPoint p, BigInteger k)
{
if (!curve.Equals(p.Curve))
throw new InvalidOperationException();
BigInteger n = p.Curve.Order;
BigInteger[] ab = glvEndomorphism.DecomposeScalar(k.Mod(n));
BigInteger a = ab[0], b = ab[1];
ECPointMap pointMap = glvEndomorphism.PointMap;
if (glvEndomorphism.HasEfficientPointMap)
{
return ECAlgorithms.ImplShamirsTrickWNaf(p, a, pointMap, b);
}
return ECAlgorithms.ImplShamirsTrickWNaf(p, a, pointMap.Map(p), b);
}
}
}
#pragma warning restore
#endif
| 32.911111 | 91 | 0.617826 | [
"Apache-2.0"
] | Cl0udG0d/Asteroid | Assets/Import/Best HTTP (Pro)/BestHTTP/SecureProtocol/math/ec/multiplier/GlvMultiplier.cs | 1,481 | C# |
// KDTree.cs - A Stark, September 2009.
// This class implements a data structure that stores a list of points in space.
// A common task in game programming is to take a supplied point and discover which
// of a stored set of points is nearest to it. For example, in path-plotting, it is often
// useful to know which waypoint is nearest to the player's current
// position. The kd-tree allows this "nearest neighbour" search to be carried out quickly,
// or at least much more quickly than a simple linear search through the list.
// At present, the class only allows for construction (using the MakeFromPoints static method)
// and nearest-neighbour searching (using FindNearest). More exotic kd-trees are possible, and
// this class may be extended in the future if there seems to be a need.
// The nearest-neighbour search returns an integer index - it is assumed that the original
// array of points is available for the lifetime of the tree, and the index refers to that
// array.
using UnityEngine;
using System.Collections;
namespace PixelComrades {
public class KDTree {
public KDTree[] lr;
public Vector3 pivot;
public int pivotIndex;
public int axis;
// Change this value to 2 if you only need two-dimensional X,Y points. The search will
// be quicker in two dimensions.
const int numDims = 3;
public KDTree() {
lr = new KDTree[2];
}
// Make a new tree from a list of points.
public static KDTree MakeFromPoints(params Vector3[] points) {
int[] indices = BuildIndices(points.Length);
return MakeFromPointsInner(0, 0, points.Length - 1, points, indices);
}
// Recursively build a tree by separating points at plane boundaries.
private static KDTree MakeFromPointsInner(
int depth,
int stIndex, int enIndex,
Vector3[] points,
int[] inds
) {
KDTree root = new KDTree();
root.axis = depth%numDims;
int splitPoint = FindPivotIndex(points, inds, stIndex, enIndex, root.axis);
root.pivotIndex = inds[splitPoint];
root.pivot = points[root.pivotIndex];
int leftEndIndex = splitPoint - 1;
if (leftEndIndex >= stIndex) {
root.lr[0] = MakeFromPointsInner(depth + 1, stIndex, leftEndIndex, points, inds);
}
int rightStartIndex = splitPoint + 1;
if (rightStartIndex <= enIndex) {
root.lr[1] = MakeFromPointsInner(depth + 1, rightStartIndex, enIndex, points, inds);
}
return root;
}
static void SwapElements(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
// Simple "median of three" heuristic to find a reasonable splitting plane.
private static int FindSplitPoint(Vector3[] points, int[] inds, int stIndex, int enIndex, int axis) {
float a = points[inds[stIndex]][axis];
float b = points[inds[enIndex]][axis];
int midIndex = (stIndex + enIndex)/2;
float m = points[inds[midIndex]][axis];
if (a > b) {
if (m > a) {
return stIndex;
}
if (b > m) {
return enIndex;
}
return midIndex;
}
else {
if (a > m) {
return stIndex;
}
if (m > b) {
return enIndex;
}
return midIndex;
}
}
// Find a new pivot index from the range by splitting the points that fall either side
// of its plane.
private static int FindPivotIndex(Vector3[] points, int[] inds, int stIndex, int enIndex, int axis) {
int splitPoint = FindSplitPoint(points, inds, stIndex, enIndex, axis);
// int splitPoint = Random.Range(stIndex, enIndex);
Vector3 pivot = points[inds[splitPoint]];
SwapElements(inds, stIndex, splitPoint);
int currPt = stIndex + 1;
int endPt = enIndex;
while (currPt <= endPt) {
Vector3 curr = points[inds[currPt]];
if ((curr[axis] > pivot[axis])) {
SwapElements(inds, currPt, endPt);
endPt--;
}
else {
SwapElements(inds, currPt - 1, currPt);
currPt++;
}
}
return currPt - 1;
}
private static int[] BuildIndices(int num) {
int[] result = new int[num];
for (int i = 0; i < num; i++) {
result[i] = i;
}
return result;
}
// Find the nearest point in the set to the supplied point.
public int FindNearest(Vector3 pt) {
float bestSqDist = 1000000000f;
int bestIndex = -1;
Search(pt, ref bestSqDist, ref bestIndex);
return bestIndex;
}
public float FindNearest_R(Vector3 pt) {
float bestSqDist = 1000000000f;
int bestIndex = -1;
Search(pt, ref bestSqDist, ref bestIndex);
return (Mathf.Sqrt(bestSqDist));
}
// Recursively search the tree.
private void Search(Vector3 pt, ref float bestSqSoFar, ref int bestIndex) {
float mySqDist = (pivot - pt).sqrMagnitude;
if (mySqDist < bestSqSoFar) {
bestSqSoFar = mySqDist;
bestIndex = pivotIndex;
}
float planeDist = pt[axis] - pivot[axis]; //DistFromSplitPlane(pt, pivot, axis);
int selector = planeDist <= 0 ? 0 : 1;
if (lr[selector] != null) {
lr[selector].Search(pt, ref bestSqSoFar, ref bestIndex);
}
selector = (selector + 1)%2;
float sqPlaneDist = planeDist*planeDist;
if ((lr[selector] != null) && (bestSqSoFar > sqPlaneDist)) {
lr[selector].Search(pt, ref bestSqSoFar, ref bestIndex);
}
}
// Get a point's distance from an axis-aligned plane.
float DistFromSplitPlane(Vector3 pt, Vector3 planePt, int axis) {
return pt[axis] - planePt[axis];
}
public int FindNearestK(Vector3 pt, int k) {
// Find and returns k-th nearest neighbour
float bestSqDist = 1000000000f;
float minSqDist = 0f;
int bestIndex = -1;
for (int i = 0; i < k - 1; i++) {
SearchK(pt, ref bestSqDist, ref minSqDist, ref bestIndex);
minSqDist = bestSqDist;
bestSqDist = 1000000000f;
bestIndex = -1;
}
SearchK(pt, ref bestSqDist, ref minSqDist, ref bestIndex);
return bestIndex;
}
public int[] FindNearestsK(Vector3 pt, int k) {
// Find and returns all k neighbours
float bestSqDist = 1000000000f;
float minSqDist = 0f;
int bestIndex = -1;
int[] bestIndexK = new int[k];
for (int i = 0; i < k - 1; i++) {
SearchK(pt, ref bestSqDist, ref minSqDist, ref bestIndex);
bestIndexK[i] = bestIndex;
minSqDist = bestSqDist;
bestSqDist = 1000000000f;
bestIndex = -1;
}
SearchK(pt, ref bestSqDist, ref minSqDist, ref bestIndex);
bestIndexK[k - 1] = bestIndex;
return bestIndexK;
}
public float FindNearestK_R(Vector3 pt, int k) {
// Find and returns k-th nearest neighbour distance
float bestSqDist = 1000000000f;
float minSqDist = 0f;
int bestIndex = -1;
for (int i = 0; i < k - 1; i++) {
SearchK(pt, ref bestSqDist, ref minSqDist, ref bestIndex);
minSqDist = bestSqDist;
bestSqDist = 1000000000f;
bestIndex = -1;
}
SearchK(pt, ref bestSqDist, ref minSqDist, ref bestIndex);
return (Mathf.Sqrt(bestSqDist));
}
public float[] FindNearestsK_R(Vector3 pt, int k) {
// Find and returns all k neighbours distances
float bestSqDist = 1000000000f;
float minSqDist = 0f;
int bestIndex = -1;
float[] bestDistances = new float[k];
for (int i = 0; i < k - 1; i++) {
SearchK(pt, ref bestSqDist, ref minSqDist, ref bestIndex);
bestDistances[i] = Mathf.Sqrt(bestSqDist);
minSqDist = bestSqDist;
bestSqDist = 1000000000f;
bestIndex = -1;
}
SearchK(pt, ref bestSqDist, ref minSqDist, ref bestIndex);
bestDistances[k - 1] = Mathf.Sqrt(bestSqDist);
return bestDistances;
}
private void SearchK(Vector3 pt, ref float bestSqSoFar, ref float minSqDist, ref int bestIndex) {
float mySqDist = (pivot - pt).sqrMagnitude;
if (mySqDist < bestSqSoFar) {
if (mySqDist > minSqDist) {
bestSqSoFar = mySqDist;
bestIndex = pivotIndex;
}
}
float planeDist = pt[axis] - pivot[axis]; //DistFromSplitPlane(pt, pivot, axis);
int selector = planeDist <= 0 ? 0 : 1;
if (lr[selector] != null) {
lr[selector].SearchK(pt, ref bestSqSoFar, ref minSqDist, ref bestIndex);
}
selector = (selector + 1)%2;
float sqPlaneDist = planeDist*planeDist;
if ((lr[selector] != null) && (bestSqSoFar > sqPlaneDist)) {
lr[selector].SearchK(pt, ref bestSqSoFar, ref minSqDist, ref bestIndex);
}
}
// Simple output of tree structure - mainly useful for getting a rough
// idea of how deep the tree is (and therefore how well the splitting
// heuristic is performing).
public string Dump(int level) {
string result = pivotIndex.ToString().PadLeft(level) + "\n";
if (lr[0] != null) {
result += lr[0].Dump(level + 2);
}
if (lr[1] != null) {
result += lr[1].Dump(level + 2);
}
return result;
}
}
}
| 31.026471 | 109 | 0.53806 | [
"MIT"
] | FuzzySlipper/Framework | Assets/Framework/Data/Structures/KDTree.cs | 10,549 | C# |
using Gedcom4Sharp.Models.Gedcom;
using Gedcom4Sharp.Models.Gedcom.Enums;
using Gedcom4Sharp.Models.Utils;
using Gedcom4Sharp.Parser.Base;
using Gedcom4Sharp.Utility.Extensions;
namespace Gedcom4Sharp.Parser
{
public class HeaderSourceDataParser : AbstractParser<HeaderSourceData>
{
public HeaderSourceDataParser(GedcomParser gedcomParser, StringTree stringTree, HeaderSourceData loadInto)
: base(gedcomParser, stringTree, loadInto)
{
}
public override void Parse()
{
_loadInto.Name = new StringWithCustomFacts(_stringTree.Value);
if(_stringTree.Children != null)
{
foreach(var ch in _stringTree.Children)
{
if (Tag.DATE.Desc().Equals(ch.Tag))
{
_loadInto.PublishDate = ParseStringWithCustomFacts(ch);
}
else if (Tag.COPYRIGHT.Desc().Equals(ch.Tag))
{
_loadInto.Copyright = ParseStringWithCustomFacts(ch);
}
else
{
UnknownTag(ch, _loadInto);
}
}
}
}
}
} | 31.925 | 114 | 0.534064 | [
"MIT"
] | ThomasPe/Gedcom4Sharp | Gedcom4Sharp/Parser/HeaderSourceDataParser.cs | 1,279 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using UnitBoilerplate.Sandbox.Classes;
using UnitBoilerplate.Sandbox.Classes.Cases;
namespace UnitTestBoilerplate.SelfTest.Cases
{
[TestClass]
public class ConstructorInjectedClassMultipleTests
{
private MockRepository mockRepository;
private Mock<ISomeInterface> mockSomeInterface;
private Mock<ISomeOtherInterface> mockSomeOtherInterface;
[TestInitialize]
public void TestInitialize()
{
this.mockRepository = new MockRepository(MockBehavior.Strict);
this.mockSomeInterface = this.mockRepository.Create<ISomeInterface>();
this.mockSomeOtherInterface = this.mockRepository.Create<ISomeOtherInterface>();
}
[TestCleanup]
public void TestCleanup()
{
this.mockRepository.VerifyAll();
}
private ConstructorInjectedClassMultiple CreateConstructorInjectedClassMultiple()
{
return new ConstructorInjectedClassMultiple(
this.mockSomeInterface.Object,
this.mockSomeOtherInterface.Object);
}
[TestMethod]
public void TestMethod1()
{
// Arrange
var unitUnderTest = this.CreateConstructorInjectedClassMultiple();
// Act
// Assert
Assert.Fail();
}
}
}
| 23.313725 | 83 | 0.777124 | [
"MIT"
] | fredatgithub/UnitTestBoilerplateGenerator | SelfTestFiles/Expected/VisualStudio_Moq_ConstructorInjectedClassMultiple.cs | 1,189 | C# |
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Sample.AspNetCore.Data;
using Sample.AspNetCore.Models;
namespace Sample.AspNetCore.Controllers
{
public class ProductsController : Controller
{
private readonly StoreDbContext context;
public ProductsController(StoreDbContext storeDbContext)
{
this.context = storeDbContext;
}
// GET: Products/Create
public IActionResult Create()
{
return View();
}
// POST: Products/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Reference,ImageUrl,ItemUrl,Type,Class,Price")]
Product product)
{
if (ModelState.IsValid)
{
this.context.Add(product);
await this.context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(product);
}
// POST: Products/Delete/5
[HttpPost]
[ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var product = await this.context.Products.FindAsync(id);
this.context.Products.Remove(product);
await this.context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
// GET: Products/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var product = await this.context.Products
.FirstOrDefaultAsync(m => m.ProductId == id);
if (product == null)
{
return NotFound();
}
return View(product);
}
// GET: Products/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var product = await this.context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return View(product);
}
// POST: Products/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id,
[Bind("Id,Name,Reference,ImageUrl,ItemUrl,Type,Class,Price")]
Product product)
{
if (id != product.ProductId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
this.context.Update(product);
await this.context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(product.ProductId))
{
return NotFound();
}
throw;
}
return RedirectToAction(nameof(Index));
}
return View(product);
}
// GET: Products
public async Task<IActionResult> Index()
{
return View(await this.context.Products.ToListAsync());
}
private bool ProductExists(int id)
{
return this.context.Products.Any(e => e.ProductId == id);
}
}
} | 27.192053 | 111 | 0.508524 | [
"Apache-2.0"
] | Nacorpio/swedbank-pay-sdk-dotnet | src/Samples/Sample.AspNetCore/Controllers/ProductsController.cs | 4,108 | C# |
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Microsoft.Azure.Mobile;
namespace AppStatistics.Droid
{
[Activity(Label = "AppStatistics", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
MobileCenter.Configure("09a2c7f3-cfe1-4bb6-889a-bf3b31d943be");
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
| 28.46875 | 190 | 0.693743 | [
"MIT"
] | jongfeel/AppStatistics | AppStatistics/AppStatistics.Droid/MainActivity.cs | 913 | C# |
using System;
using System.Text;
using System.Linq;
using Xunit;
using FluentAssertions;
using Nexogen.Libraries.Metrics.Extensions.Buckets;
namespace Nexogen.Libraries.Metrics.UnitTests.Extensions
{
public class LinearBucketGeneratorTest
{
LinearBucketGenerator generator = new LinearBucketGenerator();
[Fact]
public void Buckets_for_IHistogramBuilder_null_builder_throws()
{
IHistogramBuilder builder = null;
Assert.Throws<ArgumentNullException>("builder", () => builder.LinearBuckets(12, 34, 1));
}
[Fact]
public void Buckets_for_ILabelledHistogramBuilder_null_builder_throws()
{
ILabelledHistogramBuilder builder = null;
Assert.Throws<ArgumentNullException>("builder", () => builder.LinearBuckets(12, 34, 1));
}
[Theory]
[InlineDataAttribute(0)]
[InlineDataAttribute(-1)]
public void LinearBuckets_for_invalid_count_throws(int count)
{
Assert.Throws<ArgumentException>("count", () => generator.LinearBuckets(12, 34, count));
}
[Theory]
[InlineDataAttribute(-0.1)]
[InlineDataAttribute(0)]
[InlineDataAttribute(double.NegativeInfinity)]
[InlineDataAttribute(double.PositiveInfinity)]
[InlineDataAttribute(double.NaN)]
public void LinerBuckets_for_invalid_width_throws(double width)
{
Assert.Throws<ArgumentException>("width", () => generator.LinearBuckets(12, width, 2));
}
[Theory]
[InlineDataAttribute(double.NegativeInfinity)]
[InlineDataAttribute(double.PositiveInfinity)]
[InlineDataAttribute(double.NaN)]
public void LinerBuckets_for_invalid_min_throws(double min)
{
Assert.Throws<ArgumentException>("min", () => generator.LinearBuckets(min, 34, 2));
}
[Fact]
public void LinearBuckets_single_bucket_is_generated_properly()
{
var expectedBuckets = new[] {
new Bucket(double.NegativeInfinity, 12),
new Bucket(12, double.PositiveInfinity)
};
var buckets = generator.LinearBuckets(12, 34, 1);
buckets.ShouldAllBeEquivalentTo(expectedBuckets);
}
[Fact]
public void LinearBuckets_multiple_buckets_are_generated_properly()
{
var expectedBuckets = new[] {
new Bucket(double.NegativeInfinity, -12),
new Bucket(-12, 12),
new Bucket(12, 36),
new Bucket(36, double.PositiveInfinity)
};
var buckets = generator.LinearBuckets(-12, 24, 3);
buckets.ShouldAllBeEquivalentTo(expectedBuckets);
}
}
}
| 32.443182 | 100 | 0.615061 | [
"MIT"
] | saxus/Nexogen.Libraries.Metrics | Nexogen.Libraries.Metrics.UnitTests/Extensions/LinearBucketGeneratorTest.cs | 2,857 | 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 RVisUI.AppInf
{
/// <summary>
/// Interaction logic for InverseGammaDistributionView.xaml
/// </summary>
public partial class InverseGammaDistributionView : UserControl
{
public InverseGammaDistributionView()
{
InitializeComponent();
}
}
}
| 22.896552 | 65 | 0.771084 | [
"MIT"
] | GMPtk/RVis | UI/RVisUI.AppInf/Controls/Views/Distributions/InverseGammaDistributionView.xaml.cs | 666 | C# |
/*
* Copyright (c) 2015 Andrew Johnson
*
* 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 Newtonsoft.Json;
using System;
namespace B2BackblazeBridge.Processing
{
[Serializable]
[JsonObject(MemberSerialization.OptIn)]
internal sealed class ListFileNamesRequest
{
[JsonProperty(PropertyName = "bucketId")]
public string BucketID { get; set; }
[JsonProperty(PropertyName = "startFileName")]
public string StartFileName { get; set; }
[JsonProperty(PropertyName = "maxFileCount")]
public int MaxFileCount { get; set; }
}
}
| 39.707317 | 84 | 0.732801 | [
"MIT"
] | helios2k6/B2-Backblaze-API | B2BackblazeBridge/Processing/ListFileNamesRequest.cs | 1,630 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using System.Net;
using K4os.Compression.LZ4;
namespace Snowball
{
public interface IDataChannel
{
short ChannelID { get; }
QosType Qos { get; }
Compression Compression { get; }
void Received(ComNode node, object data);
object FromStream(ref BytePacker packer);
void ToStream(object data, ref BytePacker packer);
int GetDataSize(object data);
}
public class DataChannel<T> : IDataChannel
{
public short ChannelID { get; private set; }
public QosType Qos { get; private set; }
public Compression Compression { get; private set; }
public delegate void ReceivedHandler(ComNode node, T data);
public ReceivedHandler OnReceived { get; private set; }
Converter converter;
Converter lz4converter;
public DataChannel(short channelID, QosType qos, Compression compression, ReceivedHandler onReceived)
{
ChannelID = channelID;
Qos = qos;
Compression = Compression;
OnReceived += onReceived;
converter = DataSerializer.GetConverter(typeof(T));
lz4converter = DataSerializer.GetConverter(typeof(byte[]));
}
public object FromStream(ref BytePacker packer)
{
if (Compression == Compression.LZ4)
{
byte[] encoded = (byte[])lz4converter.Deserialize(packer);
BytePacker lz4packer = new BytePacker(encoded);
return converter.Deserialize(lz4packer);
}
else
{
return converter.Deserialize(packer);
}
}
public void ToStream(object data, ref BytePacker packer)
{
if (Compression == Compression.LZ4)
{
int size = lz4converter.GetDataSize(data);
byte[] buf = new byte[size];
BytePacker lz4packer = new BytePacker(buf);
lz4converter.Serialize(lz4packer, data);
byte[] encoded = LZ4Pickler.Pickle(buf);
converter.Serialize(packer, encoded);
}
else
{
converter.Serialize(packer, data);
}
}
public int GetDataSize(object data)
{
return converter.GetDataSize(data);
}
public void Received(ComNode node, object data)
{
if (OnReceived != null) OnReceived(node, (T)data);
}
}
}
| 27.21875 | 109 | 0.566399 | [
"MIT"
] | InstytutXR/Snowball | samples/Chat/Snowball.ChatClientUnity/Assets/Snowball/Scripts/Snowball/DataChannel.cs | 2,615 | C# |
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
////#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
namespace TruCam.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "TruCam.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
config.SetSampleForMediaType(
new TextSample("Binary JSON content. See http://bsonspec.org for details."),
new MediaTypeHeaderValue("application/bson"));
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
//// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
//// and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
//// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
//// on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
//// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
} | 57.371681 | 149 | 0.665433 | [
"MIT"
] | alevel-cherkashin/TruCam | TruCam/Areas/HelpPage/App_Start/HelpPageConfig.cs | 6,483 | C# |
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace EncompassRest.Settings.Personas
{
/// <summary>
/// MilestoneWorkflowManagementRights
/// </summary>
public sealed class MilestoneWorkflowManagementRights : DirtyExtensibleObject
{
private DirtyList<EntityReference>? _acceptFiles;
private DirtyList<EntityReference>? _returnFiles;
private DirtyList<EntityReference>? _changeExpectedDate;
private DirtyList<EntityReference>? _finishMilestones;
private DirtyList<LoanTeamMemberRights>? _assignLoanTeamMembers;
private DirtyList<EntityReference>? _editComments;
/// <summary>
/// MilestoneWorkflowManagementRights AcceptFiles
/// </summary>
[AllowNull]
public IList<EntityReference> AcceptFiles { get => GetField(ref _acceptFiles); set => SetField(ref _acceptFiles, value); }
/// <summary>
/// MilestoneWorkflowManagementRights ReturnFiles
/// </summary>
[AllowNull]
public IList<EntityReference> ReturnFiles { get => GetField(ref _returnFiles); set => SetField(ref _returnFiles, value); }
/// <summary>
/// MilestoneWorkflowManagementRights ChangeExpectedDate
/// </summary>
[AllowNull]
public IList<EntityReference> ChangeExpectedDate { get => GetField(ref _changeExpectedDate); set => SetField(ref _changeExpectedDate, value); }
/// <summary>
/// MilestoneWorkflowManagementRights FinishMilestones
/// </summary>
[AllowNull]
public IList<EntityReference> FinishMilestones { get => GetField(ref _finishMilestones); set => SetField(ref _finishMilestones, value); }
/// <summary>
/// MilestoneWorkflowManagementRights AssignLoanTeamMembers
/// </summary>
[AllowNull]
public IList<LoanTeamMemberRights> AssignLoanTeamMembers { get => GetField(ref _assignLoanTeamMembers); set => SetField(ref _assignLoanTeamMembers, value); }
/// <summary>
/// MilestoneWorkflowManagementRights EditComments
/// </summary>
[AllowNull]
public IList<EntityReference> EditComments { get => GetField(ref _editComments); set => SetField(ref _editComments, value); }
}
} | 42.518519 | 165 | 0.682927 | [
"MIT"
] | EncompassRest/EncompassREST | src/EncompassRest/Settings/Personas/MilestoneWorkflowManagementRights.cs | 2,298 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Bloom;
using Bloom.Book;
using Bloom.Collection;
using Bloom.Edit;
using NUnit.Framework;
using Palaso.IO;
using Palaso.Reporting;
using Palaso.TestUtilities;
namespace BloomTests.Edit
{
[TestFixture]
public class ConfiguratorTest
{
private FileLocator _fileLocator;
private BookStarter _starter;
private TemporaryFolder _shellCollectionFolder;
private TemporaryFolder _libraryFolder;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetDllDirectory(string lpPathName);
[SetUp]
public void Setup()
{
var library = new Moq.Mock<CollectionSettings>();
library.SetupGet(x => x.IsSourceCollection).Returns(false);
library.SetupGet(x => x.Language2Iso639Code).Returns("en");
library.SetupGet(x => x.Language1Iso639Code).Returns("xyz");
library.SetupGet(x => x.XMatterPackName).Returns("Factory");
ErrorReport.IsOkToInteractWithUser = false;
_fileLocator = new FileLocator(new string[]
{
FileLocator.GetDirectoryDistributedWithApplication( "factoryCollections"),
FileLocator.GetDirectoryDistributedWithApplication( "factoryCollections", "Templates"),
FileLocator.GetDirectoryDistributedWithApplication( "factoryCollections", "Templates", "Basic Book"),
FileLocator.GetDirectoryDistributedWithApplication( "factoryCollections", "Templates", "Wall Calendar"),
FileLocator.GetDirectoryDistributedWithApplication( "BloomBrowserUI"),
FileLocator.GetDirectoryDistributedWithApplication("BloomBrowserUI/bookLayout"),
FileLocator.GetDirectoryDistributedWithApplication( "xMatter")
});
var projectFolder = new TemporaryFolder("BookStarterTests_ProjectCollection");
var collectionSettings = new CollectionSettings(Path.Combine(projectFolder.Path, "test.bloomCollection"));
_starter = new BookStarter(_fileLocator, dir => new BookStorage(dir, _fileLocator, new BookRenamedEvent(), collectionSettings), library.Object);
_shellCollectionFolder = new TemporaryFolder("BookStarterTests_ShellCollection");
_libraryFolder = new TemporaryFolder("BookStarterTests_LibraryCollection");
Browser.SetUpXulRunner();
}
[Test]
public void IsConfigurable_Calendar_True()
{
Assert.IsTrue(Configurator.IsConfigurable(Get_NotYetConfigured_CalendardBookStorage().FolderPath));
}
[Test, Ignore("UI-By hand")]
[STAThread]
public void ShowConfigureDialog()
{
var c = new Configurator(_libraryFolder.Path, new NavigationIsolator());
var stringRep = DynamicJson.Serialize(new
{
library = new { calendar = new { year = "2088" } }
});
c.CollectJsonData(stringRep);
c.ShowConfigurationDialog(Get_NotYetConfigured_CalendardBookStorage().FolderPath);
Assert.IsTrue(c.GetLibraryData().Contains("year"));
}
[Test]
public void GetAllData_LocalOnly_ReturnLocal()
{
var c = new Configurator(_libraryFolder.Path, new NavigationIsolator());
dynamic j = new DynamicJson();
j.one = 1;
c.CollectJsonData(j.ToString());
Assert.AreEqual(j, DynamicJson.Parse(c.GetAllData()));
}
[Test]
public void LibrarySettingsAreRoundTriped()
{
var first = new Configurator(_libraryFolder.Path, new NavigationIsolator());
var stringRep = DynamicJson.Serialize(new
{
library = new {stuff = "foo"}
});
first.CollectJsonData(stringRep.ToString());
var second = new Configurator(_libraryFolder.Path, new NavigationIsolator());
dynamic j = (DynamicJson)DynamicJson.Parse(second.GetLibraryData());
Assert.AreEqual("foo", j.library.stuff);
}
[Test]
public void CollectJsonData_NewTopLevelData_DataMerged()
{
var firstData = DynamicJson.Serialize(new
{
library = new { one = "1", color="red" }
});
var secondData = DynamicJson.Serialize(new
{
library = new { two = "2", color = "blue" }
});
var first = new Configurator(_libraryFolder.Path, new NavigationIsolator());
first.CollectJsonData(firstData.ToString());
first.CollectJsonData(secondData.ToString());
var second = new Configurator(_libraryFolder.Path, new NavigationIsolator());
dynamic j= (DynamicJson) DynamicJson.Parse(second.GetLibraryData());
Assert.AreEqual("2", j.library.two);
Assert.AreEqual("1", j.library.one);
Assert.AreEqual("blue", j.library.color);
}
[Test]
public void CollectJsonData_HasArrayValue_DataMerged()
{
var firstData = "{\"library\":{\"days\":[\"1\",\"2\"]}}";
var secondData = "{\"library\":{\"days\":[\"one\",\"two\"]}}";
var first = new Configurator(_libraryFolder.Path, new NavigationIsolator());
first.CollectJsonData(firstData.ToString());
first.CollectJsonData(secondData.ToString());
var second = new Configurator(_libraryFolder.Path, new NavigationIsolator());
dynamic j = (DynamicJson)DynamicJson.Parse(second.GetLibraryData());
Assert.AreEqual("one", j.library.days[0]);
Assert.AreEqual("two", j.library.days[1]);
}
[Test]
public void CollectJsonData_NewArrayItems_DataMerged()
{
var firstData = DynamicJson.Serialize(new
{
library = new {food = new {veg="v", fruit = "f"}}
});
var secondData = DynamicJson.Serialize(new
{
library = new { food = new { bread = "b", fruit = "f" } }
});
var first = new Configurator(_libraryFolder.Path, new NavigationIsolator());
first.CollectJsonData(firstData.ToString());
first.CollectJsonData(secondData.ToString());
var second = new Configurator(_libraryFolder.Path, new NavigationIsolator());
dynamic j = (DynamicJson)DynamicJson.Parse(second.GetLibraryData());
Assert.AreEqual("v", j.library.food.veg);
Assert.AreEqual("f", j.library.food.fruit);
Assert.AreEqual("b", j.library.food.bread);
}
private void AssertEqual(string a, string b)
{
Assert.AreEqual(DynamicJson.Parse(a), DynamicJson.Parse(b));
}
[Test]
public void WhenCollectedNoLocalDataThenLocalDataIsEmpty()
{
var first = new Configurator(_libraryFolder.Path, new NavigationIsolator());
dynamic j = new DynamicJson();
j.library = new DynamicJson();
j.library.librarystuff = "foo";
first.CollectJsonData(j.ToString());
AssertEmpty(first.LocalData);
}
private static void AssertEmpty(string json)
{
Assert.IsTrue(DynamicJson.Parse(json).IsEmpty);
}
[Test]
public void WhenCollectedNoGlobalDataThenGlobalDataIsEmpty()
{
var first = new Configurator(_libraryFolder.Path, new NavigationIsolator());
dynamic j = new DynamicJson();
j.one = 1;
first.CollectJsonData(j.ToString());
Assert.AreEqual(j, DynamicJson.Parse(first.LocalData));
}
[Test]
public void GetLibraryData_NoGlobalData_Empty()
{
var first = new Configurator(_libraryFolder.Path, new NavigationIsolator());
dynamic j = new DynamicJson();
j.one = 1;
first.CollectJsonData(j.ToString());
Assert.AreEqual("{}", first.GetLibraryData());
}
[Test]
public void GetLibraryData_NothingCollected_Empty()
{
var first = new Configurator(_libraryFolder.Path, new NavigationIsolator());
Assert.AreEqual("{}", first.GetLibraryData());
}
[Test]
public void LocalData_NothingCollected_Empty()
{
var first = new Configurator(_libraryFolder.Path, new NavigationIsolator());
Assert.AreEqual("", first.LocalData);
}
private BookStorage Get_NotYetConfigured_CalendardBookStorage()
{
var source = FileLocator.GetDirectoryDistributedWithApplication("factoryCollections", "Templates", "Wall Calendar");
var path = GetPathToHtml(_starter.CreateBookOnDiskFromTemplate(source, _libraryFolder.Path));
var projectFolder = new TemporaryFolder("ConfiguratorTests_ProjectCollection");
//review
var collectionSettings = new CollectionSettings(Path.Combine(projectFolder.Path, "test.bloomCollection"));
var bs = new BookStorage(Path.GetDirectoryName(path), _fileLocator, new BookRenamedEvent(), collectionSettings);
return bs;
}
private string GetPathToHtml(string bookFolderPath)
{
return Path.Combine(bookFolderPath, Path.GetFileName(bookFolderPath)) + ".htm";
}
}
}
| 33.003984 | 147 | 0.723081 | [
"MIT"
] | phillip-hopper/BloomDesktop | src/BloomTests/Edit/ConfiguratorTest.cs | 8,286 | C# |
using System;
using System.Linq;
using static MoreLinq.Extensions.ScanExtension;
using static MoreLinq.Extensions.RepeatExtension;
using static MoreLinq.Extensions.TakeUntilExtension;
namespace aoc_runner
{
public class Day18
{
public long Part1(string[] input) =>
input.Select(x => Expression.Parse(x).Solve())
.Sum();
public long Part2(string[] input) =>
input.Select(ParenthesisHack)
.Select(x => Expression.Parse(x).Solve())
.Sum();
public record Expression(object[] Items)
{
private static long GetValue(object expressionOrNumber) => expressionOrNumber switch
{
Expression e => e.Solve(),
long l => l,
_ => throw new ArgumentOutOfRangeException(nameof(expressionOrNumber), expressionOrNumber, null)
};
public long Solve() => Items.Zip(Items.Append(null).Skip(1)).Aggregate(
long.MinValue,
(acc, next) => next switch
{
({ } lhs, _) when acc == long.MinValue => GetValue(lhs),
('+', { } rhs) => acc + GetValue(rhs),
('*', { } rhs) => acc * GetValue(rhs),
_ => acc
}
);
public static Expression Parse(string input)
{
var parsers = new Func<char[], (object?, char[])>[]
{
// digits
str =>
{
var digits = str.TakeWhile(char.IsDigit).ToArray();
return long.TryParse(new string(digits), out var num)
? (num, str[digits.Length ..])
: (null, str);
},
// operators
str => str[0] is '+' or '*' ? (str[0], str[1..]) : (null, str),
// subexpressions
str =>
{
var bracketCount = 0;
var expr = str.TakeWhile(x => x switch
{
'(' => ++bracketCount,
')' => --bracketCount,
_ => bracketCount
} != 0
).ToArray();
return expr.Any()
? (Parse(new string(expr[1..])), str[(expr.Length + 1) ..])
: (null, str);
},
// spaces
str => (null, str[0] == ' ' ? str[1..] : str)
};
var items =
parsers
.Repeat()
.Scan((item: (object?) null, remaining: input.ToCharArray()), (acc, next) => next(acc.remaining))
.TakeUntil(x => !x.remaining.Any())
.Where(x => x.item != null)
.Select(x => x.item!);
return new Expression(items.ToArray());
}
}
public static string ParenthesisHack(string input) =>
"((" +
input.Replace("(", "((")
.Replace(")", "))")
.Replace("+", ") + (")
.Replace("*", ")) * ((")
+ "))";
}
} | 36.773196 | 123 | 0.378189 | [
"MIT"
] | andi0b/-advent-of-code-2020 | src/Day18.cs | 3,569 | C# |
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using OxyPlot;
using OxyPlot.Series;
using PingLogger.Extensions;
using PingLogger.Models;
using PingLogger.Workers;
using ReactiveUI;
using Serilog;
using System;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reactive;
using System.Text;
using System.Threading.Tasks;
namespace PingLogger.ViewModels
{
public class PingControlViewModel : ViewModelBase
{
public Host Host { get; set; }
private Pinger _pinger;
public ReactiveCommand<bool, Unit> PingCommand { get; }
public ReactiveCommand<Unit, Unit> OpenTraceRouteCommand { get; }
public ReactiveCommand<Unit, Unit> OpenLogFolderCommand { get; }
public ReactiveCommand<Unit, Unit> WatchLogCommand { get; }
public ReactiveCommand<Unit, Unit> WindowExpanderCommand { get; }
readonly DispatcherTimer _timer;
private readonly FixedList<long> _pingTimes = new(23);
private long _totalPings = 0;
public delegate void HostNameUpdatedHandler(object sender, HostNameUpdatedEventArgs e);
public event HostNameUpdatedHandler HostNameUpdated;
public delegate void TraceRouteCallbackHandler(object sender, TraceRouteCallbackEventArgs e);
public event TraceRouteCallbackHandler TraceRouteCallback;
public delegate void WindowExpansionHandler(object sender, bool expand);
public event WindowExpansionHandler WindowExpandedEvent;
readonly DispatcherTimer _updateIPTimer;
readonly DispatcherTimer _checkValueTimer;
public PingControlViewModel()
{
PingCommand = ReactiveCommand.Create<bool>(TriggerPinger);
OpenTraceRouteCommand = ReactiveCommand.Create(OpenTraceRoute);
OpenLogFolderCommand = ReactiveCommand.Create(OpenLogFolder);
WatchLogCommand = ReactiveCommand.Create(WatchLog);
WindowExpanderCommand = ReactiveCommand.Create(ToggleWindow);
_timer = new DispatcherTimer()
{
Interval = TimeSpan.FromMilliseconds(100),
IsEnabled = true
};
_timer.Tick += Timer_Tick;
_timer.Start();
_updateIPTimer = new DispatcherTimer()
{
Interval = TimeSpan.FromMilliseconds(250),
IsEnabled = false
};
_updateIPTimer.Tick += UpdateIPTimer_Tick;
SetupGraphs();
showRightTabs = Config.WindowExpanded;
expanderIcon = Config.WindowExpanded ? "fas fa-angle-double-left" : "fas fa-angle-double-right";
_checkValueTimer = new DispatcherTimer()
{
Interval = TimeSpan.FromMilliseconds(500),
IsEnabled = false
};
_checkValueTimer.Tick += (_, _) => CheckValues();
}
private async void ToggleWindow()
{
Config.WindowExpanded = !Config.WindowExpanded;
ExpanderIcon = Config.WindowExpanded ? "fas fa-angle-double-left" : "fas fa-angle-double-right";
WindowExpandedEvent?.Invoke(this, Config.WindowExpanded);
await Task.Delay(10);
ShowRightTabs = Config.WindowExpanded;
}
private void WatchLog()
{
var wlVM = new WatchLogViewModel()
{
Host = Host
};
var watchLogWindow = new Views.WatchLogWindow()
{
DataContext = wlVM
};
watchLogWindow.Closing += (_, _) => { wlVM.Closing(); };
wlVM.Start();
watchLogWindow.Show();
}
public void SetupGraphs()
{
GraphModel = new PlotModel();
GraphModel.Axes.Add(new OxyPlot.Axes.LinearAxis
{
Position = OxyPlot.Axes.AxisPosition.Left
});
GraphModel.Axes.Add(new OxyPlot.Axes.DateTimeAxis()
{
Position = OxyPlot.Axes.AxisPosition.Bottom,
StringFormat = "hh:mm:ss",
IntervalType = OxyPlot.Axes.DateTimeIntervalType.Seconds
});
GraphModel.Series.Add(new LineSeries { LineStyle = LineStyle.Solid });
GraphModel.Padding = new OxyThickness(5);
StatusModel = new PlotModel();
StatusModel.Series.Add(new PieSeries() { Diameter = 0.8 });
(StatusModel.Series[0] as PieSeries).Slices.Add(new PieSlice("Success", 0) { Fill = OxyColor.FromRgb(51, 204, 0) });
(StatusModel.Series[0] as PieSeries).Slices.Add(new PieSlice("Warning", 0) { Fill = OxyColor.FromRgb(235, 224, 19) });
(StatusModel.Series[0] as PieSeries).Slices.Add(new PieSlice("Failure", 0) { Fill = OxyColor.FromRgb(194, 16, 16) });
StatusModel.Padding = new OxyThickness(5);
switch (Config.Theme)
{
case Theme.Dark:
GraphModel.Background = OxyColor.Parse("#2A2A2A");
GraphModel.LegendTextColor = OxyColor.Parse("#F0F0F0");
graphModel.TextColor = OxyColor.Parse("#F0F0F0");
StatusModel.Background = OxyColor.Parse("#2A2A2A");
StatusModel.LegendTextColor = OxyColor.Parse("#F0F0F0");
StatusModel.TextColor = OxyColor.Parse("#F0F0F0");
break;
case Theme.Auto:
if (App.DarkMode)
{
GraphModel.Background = OxyColor.Parse("#2A2A2A");
GraphModel.LegendTextColor = OxyColor.Parse("#F0F0F0");
graphModel.TextColor = OxyColor.Parse("#F0F0F0");
StatusModel.Background = OxyColor.Parse("#2A2A2A");
StatusModel.LegendTextColor = OxyColor.Parse("#F0F0F0");
StatusModel.TextColor = OxyColor.Parse("#F0F0F0");
}
break;
}
}
private void UpdateIPTimer_Tick(object sender, EventArgs e)
{
UpdateIP();
UpdateHost();
_updateIPTimer.Stop();
}
private void OpenLogFolder()
{
#if Windows
Process.Start("explorer.exe", $"{Config.LogSavePath}{Host.HostName}");
#elif Linux
Process.Start("xdg-open", $"{Config.LogSavePath}{Path.DirectorySeparatorChar}{Host.HostName}");
#elif OSX
Process.Start("open", $"{Config.LogSavePath}{Path.DirectorySeparatorChar}{Host.HostName}");
#endif
}
private void OpenTraceRoute()
{
var traceRouteVM = new TraceRouteViewModel()
{
Host = Host,
_pinger = _pinger
};
traceRouteVM.TraceRouteCallback += (object s, TraceRouteCallbackEventArgs e) => TraceRouteCallback?.Invoke(s, e);
var traceRouteWindow = new Views.TraceRouteWindow()
{
DataContext = traceRouteVM
};
if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
traceRouteWindow.ShowDialog(desktop.MainWindow);
}
}
private void Timer_Tick(object sender, EventArgs e)
{
if (_pinger is not null && _pinger.Running)
{
StopButtonEnabled = true;
StartButtonEnabled = false;
StringBuilder sb = new();
for (int i = 0; i < _pinger.Replies.Count - 1; i++)
{
_totalPings++;
var success = _pinger.Replies.TryTake(out Reply reply);
if (success)
{
if (Config.WindowExpanded)
{
var s = (LineSeries)GraphModel.Series[0];
var maxPoints = (Host.Interval * 30) / 1000;
if (s.Points.Count > maxPoints)
s.Points.RemoveAt(0);
s.Points.Add(new DataPoint(reply.DateTime.ToOADate(), reply.RoundTrip));
Dispatcher.UIThread.InvokeAsync(() => GraphModel.InvalidatePlot(true), DispatcherPriority.Background);
var p = (PieSeries)StatusModel.Series[0];
if (reply.Succeeded.Value)
{
if (reply.RoundTrip > Host.Threshold)
{
var oldValue = p.Slices[1].Value;
p.Slices[1] = new PieSlice("Warning", oldValue + 1) { Fill = OxyColor.FromRgb(235, 224, 19) };
}
else
{
var oldValue = p.Slices[0].Value;
p.Slices[0] = new PieSlice("Success", oldValue + 1) { Fill = OxyColor.FromRgb(51, 204, 0) };
}
}
else
{
var oldValue = p.Slices[2].Value;
p.Slices[2] = new PieSlice("Failure", oldValue + 1) { Fill = OxyColor.FromRgb(194, 16, 16) };
}
Dispatcher.UIThread.InvokeAsync(() => StatusModel.InvalidatePlot(true), DispatcherPriority.Background);
}
Log.Debug("Ping Success");
sb.Append($"[{reply.DateTime:T}] ");
if (reply.RoundTrip > 0)
{
_pingTimes.Add(reply.RoundTrip);
Log.Debug($"{HostName} RoundTrip Time > 0: {reply.RoundTrip}");
}
if (reply.TimedOut)
{
TimeoutCount++;
Log.Debug($"{HostName} Reply timed out. Number of Timeouts: {TimeoutCount}");
sb.Append($"Timed out to host");
}
else
{
sb.Append($"Ping round trip: {reply.RoundTrip}ms");
if (reply.RoundTrip >= WarningThreshold)
{
WarningCount++;
sb.Append(" [Warning]");
}
}
sb.Append(Environment.NewLine);
}
}
PingStatusText += sb.ToString();
var lines = PingStatusText.Split(Environment.NewLine).ToList();
if (lines.Count > _pingTimes.MaxSize)
{
lines.RemoveAt(0);
PingStatusText = string.Join(Environment.NewLine, lines);
}
if (_pingTimes.Count > 0)
{
AveragePing = Math.Ceiling(_pingTimes.Average()).ToString() + "ms";
}
PacketLoss = $"{Math.Round(TimeoutCount / (double)_totalPings * 100, 2)}%";
}
else
{
StopButtonEnabled = false;
if (Host.IP == "Invalid Host Name")
{
StartButtonEnabled = false;
}
else
{
StartButtonEnabled = true;
}
}
CheckForFolder();
//CheckValues();
}
private bool DirExists = false;
private bool LogExists = false;
private void CheckValues()
{
if (Interval < 250 || Interval == 0)
{
Interval = 250;
}
else if (Interval > 6000)
{
Interval = 6000;
}
if (WarningThreshold < 1 || WarningThreshold == 0)
{
WarningThreshold = 1;
}
else if (WarningThreshold > 6000)
{
WarningThreshold = 6000;
}
if (PacketSize < 2 || PacketSize == 0)
{
PacketSize = 2;
}
else if (PacketSize > 65527)
{
PacketSize = 65527;
}
if (Timeout < 50 || Timeout == 0)
{
Timeout = 50;
}
else if (Timeout > 6000)
{
Timeout = 6000;
}
_checkValueTimer.Stop();
}
private void CheckForFolder()
{
if (!DirExists)
{
if (Directory.Exists($"{Config.LogSavePath}{HostName}"))
{
DirExists = true;
OpenLogFolderVisible = true;
}
else
{
OpenLogFolderVisible = false;
}
}
if (!LogExists)
{
if (File.Exists($"{Config.LogSavePath}{HostName}{Path.DirectorySeparatorChar}{HostName}-{DateTime.Now:yyyyMMdd}.log"))
{
LogExists = true;
WatchLogVisible = true;
}
else
{
WatchLogVisible = false;
}
}
}
private void UpdateHost()
{
try
{
Host.HostName = hostName;
var index = Config.Hosts.IndexOf(Host);
Config.Hosts[index] = Host;
}
catch
{
}
}
public void TriggerPinger(bool start)
{
if (start)
{
CheckValues();
Log.Debug("TriggerPinger(true)");
StartButtonEnabled = false;
StopButtonEnabled = true;
HostNameBoxEnabled = false;
IntervalBoxEnabled = false;
WarningBoxEnabled = false;
TimeoutBoxEnabled = false;
PacketSizeBoxEnabled = false;
IPEnabled = false;
_pinger = new Pinger(Host);
_pinger.Start();
}
else
{
Log.Debug("TriggerPinger(false)");
StartButtonEnabled = true;
StopButtonEnabled = false;
HostNameBoxEnabled = true;
IntervalBoxEnabled = true;
WarningBoxEnabled = true;
TimeoutBoxEnabled = true;
PacketSizeBoxEnabled = true;
IPEnabled = true;
_pinger?.Stop();
}
}
private string hostName = string.Empty;
public string HostName
{
get
{
if (string.IsNullOrWhiteSpace(hostName))
hostName = Host.HostName;
return hostName;
}
set
{
StartButtonEnabled = false;
_updateIPTimer.Stop();
_updateIPTimer.Start();
HostNameUpdated?.Invoke(this, new HostNameUpdatedEventArgs(value, Host.Id.ToString()));
this.RaiseAndSetIfChanged(ref hostName, value);
}
}
private string ipAddress = string.Empty;
public string IPAddress
{
get
{
if (string.IsNullOrEmpty(ipAddress))
UpdateIP();
return ipAddress;
}
set
{
this.RaiseAndSetIfChanged(ref ipAddress, value);
Host.IP = value;
}
}
[Range(250, 6000, ErrorMessage = "Interval must be between 250 and 6,000 milliseconds")]
private int interval = 0;
public int Interval
{
get
{
if (interval == 0)
interval = Host.Interval;
return interval;
}
set
{
_checkValueTimer.Stop();
_checkValueTimer.Start();
this.RaiseAndSetIfChanged(ref interval, value);
Host.Interval = value;
UpdateHost();
}
}
[Range(1, 6000, ErrorMessage = "Warning threshold must be between 1 and 6,000 milliseconds")]
private int warningThreshold = 0;
public int WarningThreshold
{
get
{
if (warningThreshold == 0)
warningThreshold = Host.Threshold;
return warningThreshold;
}
set
{
_checkValueTimer.Stop();
_checkValueTimer.Start();
this.RaiseAndSetIfChanged(ref warningThreshold, value);
Host.Threshold = value;
UpdateHost();
}
}
[Range(1, 6000, ErrorMessage = "Timeout must be between 1 and 6,000 milliseconds")]
private int timeout = 0;
public int Timeout
{
get
{
if (timeout == 0)
timeout = Host.Timeout;
return timeout;
}
set
{
_checkValueTimer.Stop();
_checkValueTimer.Start();
this.RaiseAndSetIfChanged(ref timeout, value);
Host.Timeout = value;
UpdateHost();
}
}
[Range(2, 65526, ErrorMessage = "Packet size must be between 2 and 65,527 bytes")]
private int packetSize = 0;
public int PacketSize
{
get
{
if (packetSize == 0)
packetSize = Host.PacketSize;
return packetSize;
}
set
{
_checkValueTimer.Stop();
_checkValueTimer.Start();
this.RaiseAndSetIfChanged(ref packetSize, value);
Host.PacketSize = value;
UpdateHost();
}
}
private bool ipEnabled = true;
public bool IPEnabled
{
get => ipEnabled;
set => this.RaiseAndSetIfChanged(ref ipEnabled, value);
}
private bool startButtonEnabled = true;
public bool StartButtonEnabled
{
get => startButtonEnabled;
private set => this.RaiseAndSetIfChanged(ref startButtonEnabled, value);
}
private bool stopButtonEnabled = false;
public bool StopButtonEnabled
{
get => stopButtonEnabled;
private set => this.RaiseAndSetIfChanged(ref stopButtonEnabled, value);
}
private bool hostNameBoxEnabled = true;
public bool HostNameBoxEnabled
{
get => hostNameBoxEnabled;
private set => this.RaiseAndSetIfChanged(ref hostNameBoxEnabled, value);
}
private bool intervalBoxEnabled = true;
public bool IntervalBoxEnabled
{
get => intervalBoxEnabled;
private set => this.RaiseAndSetIfChanged(ref intervalBoxEnabled, value);
}
private bool warningBoxEnabled = true;
public bool WarningBoxEnabled
{
get => warningBoxEnabled;
private set => this.RaiseAndSetIfChanged(ref warningBoxEnabled, value);
}
private bool timeoutBoxEnabled = true;
public bool TimeoutBoxEnabled
{
get => timeoutBoxEnabled;
private set => this.RaiseAndSetIfChanged(ref timeoutBoxEnabled, value);
}
private bool packetSizeBoxEnabled = true;
public bool PacketSizeBoxEnabled
{
get => packetSizeBoxEnabled;
private set => this.RaiseAndSetIfChanged(ref packetSizeBoxEnabled, value);
}
private int warningCount = 0;
public int WarningCount
{
get => warningCount;
private set => this.RaiseAndSetIfChanged(ref warningCount, value);
}
private int timeoutCount = 0;
public int TimeoutCount
{
get => timeoutCount;
private set => this.RaiseAndSetIfChanged(ref timeoutCount, value);
}
private string packetLoss = "0%";
public string PacketLoss
{
get => packetLoss;
private set => this.RaiseAndSetIfChanged(ref packetLoss, value);
}
private string averagePing = "0ms";
public string AveragePing
{
get => averagePing;
private set => this.RaiseAndSetIfChanged(ref averagePing, value);
}
private string pingStatusText = string.Empty;
public string PingStatusText
{
get => pingStatusText;
private set => this.RaiseAndSetIfChanged(ref pingStatusText, value);
}
private bool openLogFolderVisible = false;
public bool OpenLogFolderVisible
{
get => openLogFolderVisible;
set => this.RaiseAndSetIfChanged(ref openLogFolderVisible, value);
}
private bool watchLogVisible = false;
public bool WatchLogVisible
{
get => watchLogVisible;
set => this.RaiseAndSetIfChanged(ref watchLogVisible, value);
}
private PlotModel graphModel;
public PlotModel GraphModel
{
get => graphModel;
set => this.RaiseAndSetIfChanged(ref graphModel, value);
}
private PlotModel statusModel;
public PlotModel StatusModel
{
get => statusModel;
set => this.RaiseAndSetIfChanged(ref statusModel, value);
}
private bool showRightTabs = true;
public bool ShowRightTabs
{
get => showRightTabs;
set => this.RaiseAndSetIfChanged(ref showRightTabs, value);
}
private string expanderIcon = "fas fa-angle-double-left";
public string ExpanderIcon
{
get => expanderIcon;
set => this.RaiseAndSetIfChanged(ref expanderIcon, value);
}
public static bool TraceRouteEnabled
{
get => OperatingSystem.IsWindows();
}
private async void UpdateIP()
{
try
{
foreach (var ip in await Dns.GetHostAddressesAsync(HostName))
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
IPAddress = ip.ToString();
this.RaisePropertyChanged(nameof(IPAddress));
return;
}
}
if (System.Net.IPAddress.TryParse(HostName, out _))
{
IPAddress = HostName;
this.RaisePropertyChanged(nameof(IPAddress));
}
}
catch (System.Net.Sockets.SocketException)
{
IPAddress = "Invalid Host Name";
}
}
}
}
| 25.795287 | 122 | 0.671025 | [
"MIT"
] | vouksh/PingLogger | ViewModels/PingControlViewModel.cs | 17,517 | C# |
using Laser.Orchard.FidelityGateway.Models;
using Orchard.Localization;
using Orchard.Workflows.Models;
using Orchard.Workflows.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Laser.Orchard.FidelityGateway.Activities
{
public class AddPointsActivity : Event
{
public Localizer T { get; set; }
public AddPointsActivity()
{
T = NullLocalizer.Instance;
}
public override bool CanStartWorkflow
{
get { return true; }
}
public override string Name
{
get
{
return "AddFidelityPoints";
}
}
public override LocalizedString Category
{
get
{
return T("Fidelity");
}
}
public override LocalizedString Description
{
get
{
return T("Manage Adding Fidelity Points");
}
}
public override IEnumerable<LocalizedString> GetPossibleOutcomes(WorkflowContext workflowContext, ActivityContext activityContext)
{
return new[] { T("Success"), T("Error") };
}
public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
{
APIResult<CardPointsCampaign> res = (APIResult<CardPointsCampaign>)(workflowContext.Tokens["result"]);
CardPointsCampaign card = res.data;
if (res.success)
{
workflowContext.SetState<string>("customerId", card.idCustomer);
workflowContext.SetState<string>("campaignId", card.idCampaign);
workflowContext.SetState<double>("points", card.points);
yield return T("Success");
}
else
{
yield return T("Error");
}
}
}
} | 26.586667 | 138 | 0.564694 | [
"Apache-2.0"
] | INVA-Spa/Laser.Orchard.Platform | src/Modules/Laser.Orchard.FidelityGateway/Activities/AddPointsActivity.cs | 1,996 | C# |
namespace ReverseString
{
using System;
using System.Linq;
public class StartUp
{
public static void Main()
{
char[] input = Console.ReadLine().ToCharArray();
char[] output = input.Reverse().ToArray();
Console.WriteLine(string.Join("", output));
}
}
} | 19.705882 | 60 | 0.543284 | [
"MIT"
] | lapd87/SoftUniProgrammingFundamentalsCSharp | ProgrammingFundamentalsCSharp/11StringsAndTextProcessing/001ReverseString/ReverseString.cs | 337 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace InteractiveScheduler.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.677419 | 151 | 0.585116 | [
"Apache-2.0"
] | BrianMcGough/IUMediaHelperApps | InteractiveScheduler/Properties/Settings.Designer.cs | 1,077 | C# |
/* license
MFReadWrite.cs - Part of MediaFoundationLib, which provide access to MediaFoundation interfaces via .NET
Copyright (C) 2015, by the Administrators of the Media Foundation .NET SourceForge Project
http://mfnet.sourceforge.net
This is free software; you can redistribute it and/or modify it under the terms of either:
a) The Lesser General Public License version 2.1 (see license.txt)
b) The BSD License (see BSDL.txt)
*/
using System;
using System.Runtime.InteropServices;
using System.Security;
using MediaFoundation.Misc;
using MediaFoundation.Transform;
namespace MediaFoundation.ReadWrite
{
#region COM Class Objects
[UnmanagedName("CLSID_MFReadWriteClassFactory"),
ComImport,
Guid("48e2ed0f-98c2-4a37-bed5-166312ddd83f")]
public class MFReadWriteClassFactory
{
}
#endregion
#region Declarations
[Flags, UnmanagedName("MF_SOURCE_READER_FLAG")]
public enum MF_SOURCE_READER_FLAG
{
None = 0,
Error = 0x00000001,
EndOfStream = 0x00000002,
NewStream = 0x00000004,
NativeMediaTypeChanged = 0x00000010,
CurrentMediaTypeChanged = 0x00000020,
AllEffectsRemoved = 0x00000200,
StreamTick = 0x00000100
}
[UnmanagedName("Unnamed enum")]
public enum MF_SOURCE_READER
{
InvalidStreamIndex = unchecked((int)0xFFFFFFFF),
AllStreams = unchecked((int)0xFFFFFFFE),
AnyStream = unchecked((int)0xFFFFFFFE),
FirstAudioStream = unchecked((int)0xFFFFFFFD),
FirstVideoStream = unchecked((int)0xFFFFFFFC),
FirstSourcePhotoStream = unchecked((int)0xFFFFFFFB),
PreferredSourceVideoStreamForPreview = unchecked((int)0xFFFFFFFA),
PreferredSourceVideoStreamForRecord = unchecked((int)0xFFFFFFF9),
FirstSourceIndependentPhotoStream = unchecked((int)0xFFFFFFF8),
PreferredSourceStreamForVideoRecord = unchecked((int)0xFFFFFFF9),
PreferredSourceStreamForPhoto = unchecked((int)0xFFFFFFF8),
PreferredSourceStreamForAudio = unchecked((int)0xFFFFFFF7),
MediaSource = unchecked((int)0xFFFFFFFF),
}
[UnmanagedName("MF_SOURCE_READER_CONTROL_FLAG")]
public enum MF_SOURCE_READER_CONTROL_FLAG
{
None = 0,
Drain = 0x00000001
}
[UnmanagedName("Unnamed enum")]
public enum MF_SINK_WRITER
{
InvalidStreamIndex = unchecked((int)0xFFFFFFFF),
AllStreams = unchecked((int)0xFFFFFFFE),
MediaSink = unchecked((int)0xFFFFFFFF)
}
[StructLayout(LayoutKind.Sequential), UnmanagedName("MF_SINK_WRITER_STATISTICS")]
public struct MF_SINK_WRITER_STATISTICS
{
public int cb;
public long llLastTimestampReceived;
public long llLastTimestampEncoded;
public long llLastTimestampProcessed;
public long llLastStreamTickReceived;
public long llLastSinkSampleRequest;
public long qwNumSamplesReceived;
public long qwNumSamplesEncoded;
public long qwNumSamplesProcessed;
public long qwNumStreamTicksReceived;
public int dwByteCountQueued;
public long qwByteCountProcessed;
public int dwNumOutstandingSinkSampleRequests;
public int dwAverageSampleRateReceived;
public int dwAverageSampleRateEncoded;
public int dwAverageSampleRateProcessed;
}
#endregion
#region Interfaces
#if ALLOW_UNTESTED_INTERFACES
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("17C3779E-3CDE-4EDE-8C60-3899F5F53AD6")]
public interface IMFSinkWriterEncoderConfig
{
[PreserveSig]
HResult SetTargetMediaType(
int dwStreamIndex,
IMFMediaType pTargetMediaType,
IMFAttributes pEncodingParameters
);
[PreserveSig]
HResult PlaceEncodingParameters(
int dwStreamIndex,
IMFAttributes pEncodingParameters
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("CF839FE6-8C2A-4DD2-B6EA-C22D6961AF05")]
public interface IMFSourceReaderCallback2 : IMFSourceReaderCallback
{
#region IMFSourceReaderCallback
[PreserveSig]
new HResult OnReadSample(
HResult hrStatus,
int dwStreamIndex,
MF_SOURCE_READER_FLAG dwStreamFlags,
long llTimestamp,
IMFSample pSample
);
[PreserveSig]
new HResult OnFlush(
int dwStreamIndex
);
[PreserveSig]
new HResult OnEvent(
int dwStreamIndex,
IMFMediaEvent pEvent
);
#endregion
[PreserveSig]
HResult OnTransformChange();
[PreserveSig]
HResult OnStreamError(
int dwStreamIndex,
HResult hrStatus);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("2456BD58-C067-4513-84FE-8D0C88FFDC61")]
public interface IMFSinkWriterCallback2 : IMFSinkWriterCallback
{
#region IMFSinkWriterCallback
[PreserveSig]
new HResult OnFinalize(
HResult hrStatus
);
[PreserveSig]
new HResult OnMarker(
int dwStreamIndex,
IntPtr pvContext
);
#endregion
[PreserveSig]
HResult OnTransformChange();
[PreserveSig]
HResult OnStreamError(
int dwStreamIndex,
HResult hrStatus);
}
#endif
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("3137f1cd-fe5e-4805-a5d8-fb477448cb3d")]
public interface IMFSinkWriter
{
[PreserveSig]
HResult AddStream(
IMFMediaType pTargetMediaType,
out int pdwStreamIndex
);
[PreserveSig]
HResult SetInputMediaType(
int dwStreamIndex,
IMFMediaType pInputMediaType,
IMFAttributes pEncodingParameters
);
[PreserveSig]
HResult BeginWriting();
[PreserveSig]
HResult WriteSample(
int dwStreamIndex,
IMFSample pSample
);
[PreserveSig]
HResult SendStreamTick(
int dwStreamIndex,
long llTimestamp
);
[PreserveSig]
HResult PlaceMarker(
int dwStreamIndex,
IntPtr pvContext
);
[PreserveSig]
HResult NotifyEndOfSegment(
int dwStreamIndex
);
[PreserveSig]
HResult Flush(
int dwStreamIndex
);
[PreserveSig]
HResult Finalize_();
[PreserveSig]
HResult GetServiceForStream(
int dwStreamIndex,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid guidService,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
[MarshalAs(UnmanagedType.IUnknown)] out object ppvObject
);
[PreserveSig]
HResult GetStatistics(
int dwStreamIndex,
out MF_SINK_WRITER_STATISTICS pStats
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("666f76de-33d2-41b9-a458-29ed0a972c58")]
public interface IMFSinkWriterCallback
{
[PreserveSig]
HResult OnFinalize(
HResult hrStatus
);
[PreserveSig]
HResult OnMarker(
int dwStreamIndex,
IntPtr pvContext
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("E7FE2E12-661C-40DA-92F9-4F002AB67627")]
public interface IMFReadWriteClassFactory
{
[PreserveSig]
HResult CreateInstanceFromURL(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid clsid,
[In, MarshalAs(UnmanagedType.LPWStr)] string pwszURL,
IMFAttributes pAttributes,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
[MarshalAs(UnmanagedType.IUnknown)] out object ppvObject
);
[PreserveSig]
HResult CreateInstanceFromObject(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid clsid,
[MarshalAs(UnmanagedType.IUnknown)] object punkObject,
IMFAttributes pAttributes,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
[MarshalAs(UnmanagedType.IUnknown)] out object ppvObject
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("70ae66f2-c809-4e4f-8915-bdcb406b7993")]
public interface IMFSourceReader
{
[PreserveSig]
HResult GetStreamSelection(
int dwStreamIndex,
[MarshalAs(UnmanagedType.Bool)] out bool pfSelected
);
[PreserveSig]
HResult SetStreamSelection(
int dwStreamIndex,
[MarshalAs(UnmanagedType.Bool)] bool fSelected
);
[PreserveSig]
HResult GetNativeMediaType(
int dwStreamIndex,
int dwMediaTypeIndex,
out IMFMediaType ppMediaType
);
[PreserveSig]
HResult GetCurrentMediaType(
int dwStreamIndex,
out IMFMediaType ppMediaType
);
[PreserveSig]
HResult SetCurrentMediaType(
int dwStreamIndex,
[In, Out] MFInt pdwReserved,
IMFMediaType pMediaType
);
[PreserveSig]
HResult SetCurrentPosition(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid guidTimeFormat,
[In, MarshalAs(UnmanagedType.LPStruct)] ConstPropVariant varPosition
);
[PreserveSig]
HResult ReadSample(
int dwStreamIndex,
MF_SOURCE_READER_CONTROL_FLAG dwControlFlags,
out int pdwActualStreamIndex,
out MF_SOURCE_READER_FLAG pdwStreamFlags,
out long pllTimestamp,
out IMFSample ppSample
);
[PreserveSig]
HResult Flush(
int dwStreamIndex
);
[PreserveSig]
HResult GetServiceForStream(
int dwStreamIndex,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid guidService,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
[MarshalAs(UnmanagedType.IUnknown)] out object ppvObject
);
[PreserveSig]
HResult GetPresentationAttribute(
int dwStreamIndex,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid guidAttribute,
[In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = "IMFSourceReader.GetPresentationAttribute", MarshalTypeRef = typeof(PVMarshaler))] PropVariant pvarAttribute
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("deec8d99-fa1d-4d82-84c2-2c8969944867")]
public interface IMFSourceReaderCallback
{
[PreserveSig]
HResult OnReadSample(
HResult hrStatus,
int dwStreamIndex,
MF_SOURCE_READER_FLAG dwStreamFlags,
long llTimestamp,
IMFSample pSample
);
[PreserveSig]
HResult OnFlush(
int dwStreamIndex
);
[PreserveSig]
HResult OnEvent(
int dwStreamIndex,
IMFMediaEvent pEvent
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("7b981cf0-560e-4116-9875-b099895f23d7")]
public interface IMFSourceReaderEx : IMFSourceReader
{
#region IMFSourceReader Methods
[PreserveSig]
new HResult GetStreamSelection(
int dwStreamIndex,
[MarshalAs(UnmanagedType.Bool)] out bool pfSelected
);
[PreserveSig]
new HResult SetStreamSelection(
int dwStreamIndex,
[MarshalAs(UnmanagedType.Bool)] bool fSelected
);
[PreserveSig]
new HResult GetNativeMediaType(
int dwStreamIndex,
int dwMediaTypeIndex,
out IMFMediaType ppMediaType
);
[PreserveSig]
new HResult GetCurrentMediaType(
int dwStreamIndex,
out IMFMediaType ppMediaType
);
[PreserveSig]
new HResult SetCurrentMediaType(
int dwStreamIndex,
[In, Out] MFInt pdwReserved,
IMFMediaType pMediaType
);
[PreserveSig]
new HResult SetCurrentPosition(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid guidTimeFormat,
[In, MarshalAs(UnmanagedType.LPStruct)] ConstPropVariant varPosition
);
[PreserveSig]
new HResult ReadSample(
int dwStreamIndex,
MF_SOURCE_READER_CONTROL_FLAG dwControlFlags,
out int pdwActualStreamIndex,
out MF_SOURCE_READER_FLAG pdwStreamFlags,
out long pllTimestamp,
out IMFSample ppSample
);
[PreserveSig]
new HResult Flush(
int dwStreamIndex
);
[PreserveSig]
new HResult GetServiceForStream(
int dwStreamIndex,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid guidService,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
[MarshalAs(UnmanagedType.IUnknown)] out object ppvObject
);
[PreserveSig]
new HResult GetPresentationAttribute(
int dwStreamIndex,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid guidAttribute,
[In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalCookie = "IMFSourceReaderEx.GetPresentationAttribute", MarshalTypeRef = typeof(PVMarshaler))] PropVariant pvarAttribute
);
#endregion
[PreserveSig]
HResult SetNativeMediaType(
int dwStreamIndex,
IMFMediaType pMediaType,
out MF_SOURCE_READER_FLAG pdwStreamFlags);
[PreserveSig]
HResult AddTransformForStream(
int dwStreamIndex,
[MarshalAs(UnmanagedType.IUnknown)] object pTransformOrActivate);
[PreserveSig]
HResult RemoveAllTransformsForStream(
int dwStreamIndex);
[PreserveSig]
HResult GetTransformForStream(
int dwStreamIndex,
int dwTransformIndex,
out Guid pGuidCategory,
out IMFTransform ppTransform);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("588d72ab-5Bc1-496a-8714-b70617141b25")]
public interface IMFSinkWriterEx : IMFSinkWriter
{
#region IMFSinkWriter methods
[PreserveSig]
new HResult AddStream(
IMFMediaType pTargetMediaType,
out int pdwStreamIndex
);
[PreserveSig]
new HResult SetInputMediaType(
int dwStreamIndex,
IMFMediaType pInputMediaType,
IMFAttributes pEncodingParameters
);
[PreserveSig]
new HResult BeginWriting();
[PreserveSig]
new HResult WriteSample(
int dwStreamIndex,
IMFSample pSample
);
[PreserveSig]
new HResult SendStreamTick(
int dwStreamIndex,
long llTimestamp
);
[PreserveSig]
new HResult PlaceMarker(
int dwStreamIndex,
IntPtr pvContext
);
[PreserveSig]
new HResult NotifyEndOfSegment(
int dwStreamIndex
);
[PreserveSig]
new HResult Flush(
int dwStreamIndex
);
[PreserveSig]
new HResult Finalize_();
[PreserveSig]
new HResult GetServiceForStream(
int dwStreamIndex,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid guidService,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
[MarshalAs(UnmanagedType.IUnknown)] out object ppvObject
);
[PreserveSig]
new HResult GetStatistics(
int dwStreamIndex,
out MF_SINK_WRITER_STATISTICS pStats
);
#endregion
[PreserveSig]
HResult GetTransformForStream(
int dwStreamIndex,
int dwTransformIndex,
out Guid pGuidCategory,
out IMFTransform ppTransform);
}
#endregion
}
| 28.494098 | 189 | 0.630289 | [
"MIT"
] | mikecopperwhite/DSGraphEdit | MediaFoundationNet/src/MFReadWrite.cs | 16,899 | C# |
using System;
using System.Linq;
using System.Windows;
using System.Data.Common;
using System.Windows.Controls;
using System.Collections.Generic;
using System.Windows.Media.Effects;
using System.Data.Entity.Infrastructure;
using log4net;
using CargoDelivery.BL;
using CargoDelivery.DAL;
using CargoDelivery.Classes;
namespace CargoDelivery
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
/// <summary>
/// Contains information of current creating/editing order.
/// </summary>
private Order _order;
/// <summary>
/// Validator instance.
/// </summary>
private readonly Validator _validator;
/// <summary>
/// Sign if new order is creating or editing an existent.
/// </summary>
private bool _isEditing;
/// <summary>
/// Logger instance.
/// </summary>
private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Unit of work instance object to manage database tables.
/// </summary>
private static readonly UnitOfWork UnitOfWorkInstance = new UnitOfWork();
/// <summary>
/// Parameterless constructor of application's main window.
/// </summary>
public MainWindow()
{
InitializeComponent();
EditOrderButton.IsEnabled = false;
DeletOrderButton.IsEnabled = false;
_isEditing = false;
_validator = new Validator(
new List<TextBox>
{
FirstName,
LastName,
Email,
PhoneNumber,
ClientAddressCity,
ClientAddressStreet,
ClientAddressBuildingNumber,
ShopName,
ShopAddressCity,
ShopAddressStreet,
ShopAddressBuildingNumber,
GoodsCode,
GoodsWeight
},
Email,
PhoneNumber);
ResetOrderInstance();
}
/// <summary>
/// Fires when user opens pop-up window with a list of available oredrs.
/// </summary>
/// <param name="sender">The button New that the action is for.</param>
/// <param name="e">Arguments that the implementor of this event may find useful.</param>
private void ExploreOrders(object sender, RoutedEventArgs e)
{
try
{
var ordersDict = UnitOfWorkInstance.GetOrders().ToDictionary(order => order.Id,
order => $"{order.ClientData.FirstName} {order.ClientData.LastName}");
if (ordersDict.Count > 0)
{
OrdersList.ItemsSource = ordersDict;
OrdersExplorer.IsOpen = true;
ResetOrderInstance();
WindowMain.IsEnabled = false;
EditOrderButton.IsEnabled = false;
DeletOrderButton.IsEnabled = false;
Opacity = 0.5;
Effect = new BlurEffect();
}
else
{
Util.Info("Explore orders", "Orders table is empty!");
}
}
catch (DbException exc)
{
Cancel(sender, e);
Logger.Error($"Error occurred while retrieving orders from the database.\nError: {exc}");
Util.Error("Exploring orders error", exc.Message);
}
catch (Exception exc)
{
Cancel(sender, e);
Logger.Error($"Unknown error occurred while exploring orders.\nError: {exc}");
Util.Error("Exploring orders error", exc.Message);
}
}
/// <summary>
/// Fires when user presses 'Edit' button on pop-up window.
/// </summary>
/// <param name="sender">The button New that the action is for.</param>
/// <param name="e">Arguments that the implementor of this event may find useful.</param>
private void SetTargetEditingOrder(object sender, RoutedEventArgs e)
{
try
{
if (OrdersList.SelectedItems.Count == 1)
{
var selectedItem = (dynamic)OrdersList.SelectedItems[0];
_order = UnitOfWorkInstance.Orders.GetById(selectedItem.Key);
DataContext = _order;
}
OrdersList.SelectedItem = null;
OrdersExplorer.IsOpen = false;
EditOrderButton.IsEnabled = false;
DeletOrderButton.IsEnabled = false;
WindowMain.IsEnabled = true;
Opacity = 1;
Effect = null;
_isEditing = true;
}
catch (Exception exc)
{
Logger.Error($"Error occurred while setting order for editing.\nError: {exc}");
Util.Error("Can't set order for editing", exc.Message);
}
}
/// <summary>
/// Fires when user rejects pop-up window by pressing 'Cancel' button.
/// </summary>
/// <param name="sender">The button New that the action is for.</param>
/// <param name="e">Arguments that the implementor of this event may find useful.</param>
private void Cancel(object sender, RoutedEventArgs e)
{
OrdersExplorer.IsOpen = false;
EditOrderButton.IsEnabled = false;
DeletOrderButton.IsEnabled = false;
WindowMain.IsEnabled = true;
Opacity = 1;
Effect = null;
}
/// <summary>
/// Fires when user creates or updates an order.
/// </summary>
/// <param name="sender">The button New that the action is for.</param>
/// <param name="e">Arguments that the implementor of this event may find useful.</param>
private void SaveOrder(object sender, RoutedEventArgs e)
{
try
{
_validator.Validate();
if (_isEditing)
{
UnitOfWorkInstance.Orders.Update(_order);
}
else
{
UnitOfWorkInstance.Orders.Insert(_order);
}
UnitOfWorkInstance.Save();
Util.Info("Cargo Delivery", "An order was saved successfully!");
}
catch (InvalidCastException exc)
{
Logger.Error($"Error occurred while vaidating inputs.\nError: {exc}");
Util.Error("Order saving error", exc.Message);
}
catch (DbUpdateException exc)
{
Logger.Error($"Error occurred while updating the databse.\nError: {exc}");
Util.Error("Order saving error", exc.Message);
}
catch (Exception exc)
{
Logger.Error($"Error occurred while order saving or updating.\nError: {exc}");
Util.Error("Order saving error", exc.Message);
}
}
/// <summary>
/// Fires when user selects some input field.
/// </summary>
/// <param name="sender">The button New that the action is for.</param>
/// <param name="e">Arguments that the implementor of this event may find useful.</param>
private void InputFocused(object sender, RoutedEventArgs e)
{
if (e.OriginalSource is TextBox textBox)
{
textBox.SelectAll();
}
}
/// <summary>
/// Fires when user presses on items in pop-up window's list view.
/// </summary>
/// <param name="sender">The button New that the action is for.</param>
/// <param name="e">Arguments that the implementor of this event may find useful.</param>
private void ItemIsSelected(object sender, RoutedEventArgs e)
{
EditOrderButton.IsEnabled = true;
DeletOrderButton.IsEnabled = true;
}
/// <summary>
/// Fires when user resets input fields for creating new order by pressing 'New' button.
/// </summary>
/// <param name="sender">The button New that the action is for.</param>
/// <param name="e">Arguments that the implementor of this event may find useful.</param>
private void NewOrder(object sender, RoutedEventArgs e)
{
_isEditing = false;
ResetOrderInstance();
}
/// <summary>
/// Fires when user deletes order by pressing 'Delete' button on pop-up window.
/// </summary>
/// <param name="sender">The button New that the action is for.</param>
/// <param name="e">Arguments that the implementor of this event may find useful.</param>
private void DeleteOrder(object sender, RoutedEventArgs e)
{
try
{
if (OrdersList.SelectedItems.Count != 1)
{
return;
}
var selectedItem = (dynamic) OrdersList.SelectedItems[0];
UnitOfWorkInstance.DeleteOrder(selectedItem.Key);
UnitOfWorkInstance.Save();
OrdersList.SelectedItem = null;
EditOrderButton.IsEnabled = false;
DeletOrderButton.IsEnabled = false;
var orders = UnitOfWorkInstance.GetOrders().ToDictionary(order => order.Id,
order => $"{order.ClientData.FirstName} {order.ClientData.LastName}");
if (orders.Count < 1)
{
OrdersExplorer.IsOpen = false;
Opacity = 1;
Effect = null;
WindowMain.IsEnabled = true;
}
else
{
OrdersList.ItemsSource = orders;
}
}
catch (DbUpdateException exc)
{
Cancel(sender, e);
Logger.Error($"Error occurred while deleting from the databse.\nError: {exc}");
Util.Error("Order deleting error", exc.Message);
}
catch (Exception exc)
{
Cancel(sender, e);
Logger.Error($"Error occurred while deleting an order.\nError: {exc}");
Util.Error("Order deleting error", exc.ToString());
}
}
/// <summary>
/// Resets _order field: set _order to new Order with id = -1.
/// </summary>
private void ResetOrderInstance()
{
_order = new Order();
DataContext = _order;
}
}
}
| 28.942953 | 124 | 0.671072 | [
"MIT"
] | university-courses/PofCIS-Term4 | CargoDelivery/MainWindow.xaml.cs | 8,627 | C# |
using System;
using AutoMapper;
using DataGenerator;
using FluentAssertions;
using MediatR.CommandQuery.Commands;
using MediatR.CommandQuery.EntityFrameworkCore.SqlServer.Tests.Constants;
using MediatR.CommandQuery.EntityFrameworkCore.SqlServer.Tests.Domain.Task.Models;
using MediatR.CommandQuery.Queries;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.JsonPatch.Operations;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
using Task = System.Threading.Tasks.Task;
namespace MediatR.CommandQuery.EntityFrameworkCore.SqlServer.Tests.Acceptance
{
public class TaskTests : DatabaseTestBase
{
public TaskTests(ITestOutputHelper output, DatabaseFixture databaseFixture)
: base(output, databaseFixture)
{
}
[Fact]
public async Task FullTest()
{
var mediator = ServiceProvider.GetService<IMediator>();
mediator.Should().NotBeNull();
var mapper = ServiceProvider.GetService<IMapper>();
mapper.Should().NotBeNull();
// Create Entity
var createModel = Generator.Default.Single<TaskCreateModel>();
createModel.Title = "Testing";
createModel.Description = "Test " + DateTime.Now.Ticks;
createModel.StatusId = StatusConstants.NotStarted;
createModel.TenantId = TenantConstants.Test;
var createCommand = new EntityCreateCommand<TaskCreateModel, TaskReadModel>(MockPrincipal.Default, createModel);
var createResult = await mediator.Send(createCommand).ConfigureAwait(false);
createResult.Should().NotBeNull();
// Get Entity by Key
var identifierQuery = new EntityIdentifierQuery<Guid, TaskReadModel>(MockPrincipal.Default, createResult.Id);
var identifierResult = await mediator.Send(identifierQuery).ConfigureAwait(false);
identifierResult.Should().NotBeNull();
identifierResult.Title.Should().Be(createModel.Title);
// Query Entity
var entityQuery = new EntityQuery
{
Sort = new[] { new EntitySort { Name = "Updated", Direction = "Descending" } },
Filter = new EntityFilter { Name = "StatusId", Value = StatusConstants.NotStarted }
};
var listQuery = new EntityPagedQuery<TaskReadModel>(MockPrincipal.Default, entityQuery);
var listResult = await mediator.Send(listQuery).ConfigureAwait(false);
listResult.Should().NotBeNull();
// Patch Entity
var patchModel = new JsonPatchDocument<Task>();
patchModel.Operations.Add(new Operation<Task>
{
op = "replace",
path = "/Title",
value = "Patch Update"
});
var patchCommand = new EntityPatchCommand<Guid, TaskReadModel>(MockPrincipal.Default, createResult.Id, patchModel);
var patchResult = await mediator.Send(patchCommand).ConfigureAwait(false);
patchResult.Should().NotBeNull();
patchResult.Title.Should().Be("Patch Update");
// Update Entity
var updateModel = mapper.Map<TaskUpdateModel>(patchResult);
updateModel.Title = "Update Command";
var updateCommand = new EntityUpdateCommand<Guid, TaskUpdateModel, TaskReadModel>(MockPrincipal.Default, createResult.Id, updateModel);
var updateResult = await mediator.Send(updateCommand).ConfigureAwait(false);
updateResult.Should().NotBeNull();
updateResult.Title.Should().Be("Update Command");
// Delete Entity
var deleteCommand = new EntityDeleteCommand<Guid, TaskReadModel>(MockPrincipal.Default, createResult.Id);
var deleteResult = await mediator.Send(deleteCommand).ConfigureAwait(false);
deleteResult.Should().NotBeNull();
deleteResult.Id.Should().Be(createResult.Id);
}
[Fact]
public async Task Upsert()
{
var key = Guid.NewGuid();
var mediator = ServiceProvider.GetService<IMediator>();
mediator.Should().NotBeNull();
var mapper = ServiceProvider.GetService<IMapper>();
mapper.Should().NotBeNull();
// Update Entity
var updateModel = Generator.Default.Single<TaskUpdateModel>();
updateModel.Title = "Upsert Test";
updateModel.Description = "Insert " + DateTime.Now.Ticks;
updateModel.StatusId = StatusConstants.NotStarted;
updateModel.TenantId = TenantConstants.Test;
var upsertCommandNew = new EntityUpsertCommand<Guid, TaskUpdateModel, TaskReadModel>(MockPrincipal.Default, key, updateModel);
var upsertResultNew = await mediator.Send(upsertCommandNew).ConfigureAwait(false);
upsertResultNew.Should().NotBeNull();
// Get Entity by Key
var identifierQuery = new EntityIdentifierQuery<Guid, TaskReadModel>(MockPrincipal.Default, key);
var identifierResult = await mediator.Send(identifierQuery).ConfigureAwait(false);
identifierResult.Should().NotBeNull();
identifierResult.Title.Should().Be(updateModel.Title);
// update model
updateModel.Description = "Update " + DateTime.Now.Ticks;
// Upsert again, should be update
var upsertCommandUpdate = new EntityUpsertCommand<Guid, TaskUpdateModel, TaskReadModel>(MockPrincipal.Default, key, updateModel);
var upsertResultUpdate = await mediator.Send(upsertCommandUpdate).ConfigureAwait(false);
upsertResultUpdate.Should().NotBeNull();
upsertResultUpdate.Description.Should().NotBe(upsertResultNew.Description);
}
[Fact]
public async Task TenantDoesNotMatch()
{
var mediator = ServiceProvider.GetService<IMediator>();
mediator.Should().NotBeNull();
var mapper = ServiceProvider.GetService<IMapper>();
mapper.Should().NotBeNull();
// Create Entity
var createModel = Generator.Default.Single<TaskCreateModel>();
createModel.Title = "Testing";
createModel.Description = "Test " + DateTime.Now.Ticks;
createModel.StatusId = StatusConstants.NotStarted;
createModel.TenantId = Guid.NewGuid();
var createCommand = new EntityCreateCommand<TaskCreateModel, TaskReadModel>(MockPrincipal.Default, createModel);
await Assert.ThrowsAsync<DomainException>(() => mediator.Send(createCommand));
}
[Fact]
public async Task TenantSetDefault()
{
var mediator = ServiceProvider.GetService<IMediator>();
mediator.Should().NotBeNull();
var mapper = ServiceProvider.GetService<IMapper>();
mapper.Should().NotBeNull();
// Create Entity
var createModel = Generator.Default.Single<TaskCreateModel>();
createModel.Title = "Testing";
createModel.Description = "Test " + DateTime.Now.Ticks;
createModel.StatusId = StatusConstants.NotStarted;
createModel.TenantId = Guid.Empty;
var createCommand = new EntityCreateCommand<TaskCreateModel, TaskReadModel>(MockPrincipal.Default, createModel);
var createResult = await mediator.Send(createCommand).ConfigureAwait(false);
createResult.Should().NotBeNull();
createResult.TenantId.Should().Be(TenantConstants.Test);
}
[Fact]
public async Task EntityPageQuery()
{
var mediator = ServiceProvider.GetService<IMediator>();
mediator.Should().NotBeNull();
var mapper = ServiceProvider.GetService<IMapper>();
mapper.Should().NotBeNull();
var filter = new EntityFilter { Name = "StatusId", Value = StatusConstants.NotStarted };
var entityQuery = new EntityQuery {Filter = filter};
var pagedQuery = new EntityPagedQuery<TaskReadModel>(MockPrincipal.Default, entityQuery);
var selectResult = await mediator.Send(pagedQuery).ConfigureAwait(false);
selectResult.Should().NotBeNull();
}
[Fact]
public async Task EntitySelectQuery()
{
var mediator = ServiceProvider.GetService<IMediator>();
mediator.Should().NotBeNull();
var mapper = ServiceProvider.GetService<IMapper>();
mapper.Should().NotBeNull();
var filter = new EntityFilter { Name = "StatusId", Value = StatusConstants.NotStarted };
var select = new EntitySelect(filter);
var selectQuery = new EntitySelectQuery<TaskReadModel>(MockPrincipal.Default, select);
var selectResult = await mediator.Send(selectQuery).ConfigureAwait(false);
selectResult.Should().NotBeNull();
}
[Fact]
public async Task EntitySelectQueryDelete()
{
var mediator = ServiceProvider.GetService<IMediator>();
mediator.Should().NotBeNull();
var mapper = ServiceProvider.GetService<IMapper>();
mapper.Should().NotBeNull();
var filter = new EntityFilter { Name = "IsDeleted", Value = true };
var select = new EntitySelect(filter);
var selectQuery = new EntitySelectQuery<TaskReadModel>(MockPrincipal.Default, select);
var selectResult = await mediator.Send(selectQuery).ConfigureAwait(false);
selectResult.Should().NotBeNull();
}
[Fact]
public async Task EntitySelectQueryDeleteNested()
{
var mediator = ServiceProvider.GetService<IMediator>();
mediator.Should().NotBeNull();
var mapper = ServiceProvider.GetService<IMapper>();
mapper.Should().NotBeNull();
var filter = new EntityFilter
{
Filters = new[]
{
new EntityFilter {Name = "IsDeleted", Value = true},
new EntityFilter { Name = "StatusId", Value = StatusConstants.NotStarted }
}
};
var select = new EntitySelect(filter);
var selectQuery = new EntitySelectQuery<TaskReadModel>(MockPrincipal.Default, select);
var selectResult = await mediator.Send(selectQuery).ConfigureAwait(false);
selectResult.Should().NotBeNull();
}
}
}
| 42.596 | 147 | 0.635459 | [
"MIT"
] | loresoft/MediatR.CommandQuery | test/MediatR.CommandQuery.EntityFrameworkCore.SqlServer.Tests/Acceptance/TaskTests.cs | 10,651 | C# |
using Xunit;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.Hosting;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;
using FluentAssertions;
using Codit.LevelTwo.Models;
using Codit.LevelTwo.Extensions;
using Codit.LevelTwo;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Codit.IntegrationTest
{
[Collection("TestServer")]
public class ProblemJsonTest
{
TestServerFixture fixture;
public ProblemJsonTest(TestServerFixture fixture)
{
this.fixture = fixture;
}
[Fact]
public async Task ProblemJson_RouteNotExists_404_Test()
{
//Arrange
var request = new HttpRequestMessage(new HttpMethod("GET"), "/codito/api/v1/car");
//Act
var response = await fixture._httpClient.SendAsync(request);
//Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
response.Content.Headers.ContentLength.Should().BeGreaterThan(0);
response.ShouldBeProblemJson();
}
[Fact]
public async Task ProblemJson_Validation_400_Test()
{
//Arrange
var customization = new NewCustomizationDto
{
Name = "My customization",
};
var request = TestExtensions.GetJsonRequest(customization, "POST", "/codito/v1/customization");
//Act
var response = await fixture._httpClient.SendAsync(request);
//Assert
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
response.Content.Headers.ContentLength.Should().BeGreaterThan(0);
response.ShouldBeProblemJson();
}
[Fact]
public async Task ProblemJson_ContentNegotiationNotOk_406_Test()
{
//Arrange
var request = new HttpRequestMessage(new HttpMethod("GET"), "/codito/codito/car");
request.Headers.Add("Accept", "custom/content+type");
//Act
var response = await fixture._httpClient.SendAsync(request);
//Assert
response.StatusCode.Should().Be(HttpStatusCode.NotAcceptable);
response.Content.Headers.Should().BeNullOrEmpty(); // With 406 the body is suppressed
}
[Fact]
public async Task ProblemJson_UnsupportedContentType_415_Test()
{
//Arrange
var customization = new NewCustomizationDto
{
Name = "My customization",
CarId = 1
};
var request = TestExtensions.GetJsonRequest(customization, "POST", "/codito/v1/customization/", "application/pdf");
//Act
var response = await fixture._httpClient.SendAsync(request);
//Assert
response.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType);
response.Content.Headers.ContentLength.Should().BeGreaterThan(0);
response.ShouldBeProblemJson();
}
[Fact]
public async Task ProblemJson_InternalServerError_500_Test()
{
//Arrange
var customization = new NewCustomizationDto
{
Name = "My customization",
CarId = -9999 // "evil" request
};
var request = TestExtensions.GetJsonRequest(customization, "POST", "/codito/v1/customization");
//Act
var response = await fixture._httpClient.SendAsync(request);
//Assert
response.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
response.Content.Headers.ContentLength.Should().BeGreaterThan(0);
response.ShouldBeProblemJson();
}
}
}
| 35.240741 | 127 | 0.606936 | [
"MIT"
] | Codit/practical-api-guidelines | maturity-level-two/tests/Codit.IntegrationTest/ProblemJsonTest.cs | 3,808 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace NWaves.Signals.Builders
{
/// <summary>
/// Abstract class for representing any signal builder (generator)
/// </summary>
public abstract class SignalBuilder
{
/// <summary>
/// Number of delay samples
/// </summary>
private int _delay;
/// <summary>
/// Number of times to repeat the signal
/// </summary>
private int _repeatTimes;
/// <summary>
/// List of signals to be superimposed with the resulting signal
/// </summary>
private readonly List<DiscreteSignal> _toSuperimpose = new List<DiscreteSignal>();
/// <summary>
/// Resulting signal
/// </summary>
protected DiscreteSignal Signal { get; set; }
/// <summary>
/// The length of the signal
/// </summary>
protected int Length { get; set; } = 1;
/// <summary>
/// Sampling rate of the signal
/// </summary>
protected int SamplingRate { get; set; } = 1;
/// <summary>
/// Dictionary of setters for each parameter
/// </summary>
protected Dictionary<string, Action<double>> ParameterSetters { get; set; }
/// <summary>
/// Brief descriptions of parameters (list of their names)
/// </summary>
/// <returns></returns>
public virtual string[] GetParametersInfo()
{
return ParameterSetters.Keys.ToArray();
}
/// <summary>
/// Method for setting parameter values
/// </summary>
/// <param name="parameterName"></param>
/// <param name="parameterValue"></param>
/// <returns></returns>
public virtual SignalBuilder SetParameter(string parameterName, double parameterValue)
{
foreach (var parameterKey in ParameterSetters.Keys)
{
var keywords = parameterKey.Split(',').Select(s => s.Trim());
if (keywords.Any(keyword => string.Compare(keyword, parameterName, StringComparison.OrdinalIgnoreCase) == 0))
{
var setter = ParameterSetters[parameterKey];
setter.Invoke(parameterValue);
return this;
}
}
return this;
}
/// <summary>
/// Method for online sample generation (must be implemented in subclasses)
/// </summary>
/// <returns></returns>
public abstract float NextSample();
/// <summary>
/// Reset online builder
/// </summary>
public virtual void Reset()
{
}
/// <summary>
/// Method for generating signal of particular shape
/// </summary>
/// <returns>Generated signal</returns>
protected virtual DiscreteSignal Generate()
{
var signal = new DiscreteSignal(SamplingRate, Length);
for (var i = 0; i < signal.Length; i++)
{
signal[i] = NextSample();
}
return signal;
}
/// <summary>
/// Final or intermediate build step
/// </summary>
/// <returns>The signal that is currently built</returns>
public virtual DiscreteSignal Build()
{
var signal = Generate();
// perhaps, superimpose
signal = _toSuperimpose.Aggregate(signal, (current, s) => current.Superimpose(s));
// perhaps, delay
if (_delay != 0)
{
signal = signal.Delay(_delay);
}
// and perhaps, repeat
if (_repeatTimes > 1)
{
signal = signal.Repeat(_repeatTimes);
}
return signal;
}
/// <summary>
///
/// </summary>
/// <param name="sampleCount"></param>
/// <returns></returns>
public virtual SignalBuilder OfLength(int sampleCount)
{
Length = sampleCount;
return this;
}
/// <summary>
///
/// </summary>
/// <param name="samplingRate"></param>
/// <returns></returns>
public virtual SignalBuilder SampledAt(int samplingRate)
{
if (samplingRate <= 0)
{
throw new ArgumentException("Sampling rate must be positive!");
}
SamplingRate = samplingRate;
return this;
}
/// <summary>
///
/// </summary>
/// <param name="delay"></param>
/// <returns></returns>
public virtual SignalBuilder DelayedBy(int delay)
{
_delay += delay;
return this;
}
/// <summary>
///
/// </summary>
/// <param name="signal"></param>
/// <returns></returns>
public virtual SignalBuilder SuperimposedWith(DiscreteSignal signal)
{
_toSuperimpose.Add(signal);
return this;
}
/// <summary>
///
/// </summary>
/// <param name="times"></param>
/// <returns></returns>
public virtual SignalBuilder RepeatedTimes(int times)
{
_repeatTimes += times;
return this;
}
}
}
| 27.923469 | 125 | 0.501736 | [
"MIT"
] | RachamimYaakobov/NWaves | NWaves/Signals/Builders/SignalBuilder.cs | 5,475 | C# |
/**
* Copyright 2017 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using Newtonsoft.Json;
namespace IBM.WatsonDeveloperCloud.Discovery.v1.Model
{
/// <summary>
/// Entity text to provide context for the queried entity and rank based on that association. For example, if you wanted to query the city of London in England your query would look for `London` with the context of `England`.
/// </summary>
public class QueryEntitiesContext
{
/// <summary>
/// Entity text to provide context for the queried entity and rank based on that association. For example, if you wanted to query the city of London in England your query would look for `London` with the context of `England`.
/// </summary>
/// <value>Entity text to provide context for the queried entity and rank based on that association. For example, if you wanted to query the city of London in England your query would look for `London` with the context of `England`.</value>
[JsonProperty("text", NullValueHandling = NullValueHandling.Ignore)]
public string Text { get; set; }
}
}
| 45.861111 | 248 | 0.723804 | [
"Apache-2.0"
] | mediumTaj/dotnet-standard-sdk-generated | src/IBM.WatsonDeveloperCloud.Discovery.v1/Model/QueryEntitiesContext.cs | 1,651 | C# |
using System.Collections.Generic;
using System.Linq;
using AppKit;
using CoreGraphics;
namespace Microsoft.Maui.Graphics.Native
{
public class NativeFontRegistry
{
private static NativeFontRegistry _instance = new NativeFontRegistry();
private readonly Dictionary<string, CGFont> _customFonts = new Dictionary<string, CGFont>();
private readonly string _systemFontName;
protected NativeFontRegistry()
{
var font = NSFont.SystemFontOfSize(NSFont.SystemFontSize);
_systemFontName = font.FontName;
font.Dispose();
}
public static NativeFontRegistry Instance => _instance ?? (_instance = new NativeFontRegistry());
public Dictionary<string, CGFont>.ValueCollection CustomFonts => _customFonts.Values;
public void RegisterFont(CGFont font)
{
_customFonts.Add(font.FullName, font);
}
public bool IsCustomFont(string name)
{
return name != null && _customFonts.ContainsKey(name);
}
public CGFont GetCustomFont(string name)
{
if (name == null) return CGFont.CreateWithFontName(_systemFontName);
if (_customFonts.TryGetValue(name, out var font))
{
return font;
}
return CGFont.CreateWithFontName(_systemFontName);
}
public void ClearCustomFonts()
{
var keys = _customFonts.Keys.ToArray();
foreach (var key in keys)
{
var font = _customFonts[key];
_customFonts.Remove(key);
font.Dispose();
}
}
}
}
| 22.967213 | 99 | 0.728051 | [
"MIT"
] | JimBobSquarePants/Microsoft.Maui.Graphics | src/Microsoft.Maui.Graphics/Mac/NativeFontRegistry.cs | 1,401 | C# |
using System;
namespace Encryption
{
public static class StringExtensions
{
/// <summary>
/// Converts the passed hexadecimal encoded string to its byte[] equivalent.
/// </summary>
/// <param name="hexString">The hexadecimal encoded string to convert into a byte array.</param>
public static byte[] ToByteArray(this string hexString)
{
if (!IsHex(hexString))
{
throw new ArgumentException($"StringExtensions.cs: ToByteArray() '{nameof(hexString)}' format error -> string must be hexadecimally encoded in order to convert to byte array.");
}
int hexLength = hexString.Length;
byte[] hexBytes = new byte[hexLength / 2];
for (int i = 0; i < hexLength; i += 2)
{
hexBytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
}
return hexBytes;
}
/// <summary>
/// Converts a byte array to its hexadecimal encoded string equivalent.
/// </summary>
/// <param name="bytes">The bytes to convert to the hexadecimal encoded string.</param>
public static string ToHexString(this byte[] bytes)
{
return BitConverter.ToString(bytes).Replace("-", "");
}
/// <summary>
/// Determines if the passed string is hexadecimally formatted.
/// </summary>
/// <param name="str">The string of characters to verify.</param>
private static bool IsHex(this string str)
{
for (int i = 0; i < str.Length; i++)
{
if (str[i] >= '0' && str[i] <= '9' || str[i] >= 'a' && str[i] <= 'f' || str[i] >= 'A' && str[i] <= 'F')
continue;
return false;
}
return true;
}
}
} | 35.018519 | 193 | 0.522475 | [
"MIT"
] | doubletruth/RSA-RM-Encryption | RSA-RM-Encryption/StringExtensions.cs | 1,891 | 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 Steeltoe.Common.Discovery;
namespace Steeltoe.Discovery.Eureka
{
public class EurekaClientOptions : EurekaClientConfig, IDiscoveryClientOptions
{
public const string EUREKA_CLIENT_CONFIGURATION_PREFIX = "eureka:client";
public new const int Default_InstanceInfoReplicationIntervalSeconds = 30;
public EurekaClientOptions()
{
#pragma warning disable CS0618 // Type or member is obsolete
InstanceInfoReplicationIntervalSeconds = Default_InstanceInfoReplicationIntervalSeconds;
#pragma warning restore CS0618 // Type or member is obsolete
EurekaServer = new EurekaServerConfig(this);
Health = new EurekaHealthConfig(this);
}
// Configuration property: eureka:client:accessTokenUri
public string AccessTokenUri { get; set; }
// Configuration property: eureka:client:clientSecret
public string ClientSecret { get; set; }
// Configuration property: eureka:client:clientId
public string ClientId { get; set; }
// Configuration property: eureka:client:serviceUrl
public string ServiceUrl
{
get
{
return this.EurekaServerServiceUrls;
}
set
{
this.EurekaServerServiceUrls = value;
}
}
// Configuration property: eureka:client:validate_certificates
public bool Validate_Certificates
{
get
{
return this.ValidateCertificates;
}
set
{
this.ValidateCertificates = value;
}
}
// Configuration property: eureka:client:eurekaServer
public EurekaServerConfig EurekaServer { get; set; }
// Configuration property: eureka:client:health
public EurekaHealthConfig Health { get; set; }
public class EurekaHealthConfig
{
private EurekaClientOptions _options;
public EurekaHealthConfig(EurekaClientOptions options)
{
_options = options;
}
// Configuration property: eureka:client:health:enabled
public bool Enabled
{
get
{
return _options.HealthContribEnabled;
}
set
{
_options.HealthContribEnabled = value;
}
}
// Configuration property: eureka:client:health:monitoredApps
public string MonitoredApps
{
get
{
return _options.HealthMonitoredApps;
}
set
{
_options.HealthMonitoredApps = value;
}
}
// Configuration property: eureka:client:health:checkEnabled
public bool CheckEnabled
{
get
{
return _options.HealthCheckEnabled;
}
set
{
_options.HealthCheckEnabled = value;
}
}
}
public class EurekaServerConfig
{
private EurekaClientOptions _options;
public EurekaServerConfig(EurekaClientOptions options)
{
_options = options;
}
/// <summary>
/// Gets or sets configuration property: eureka:client:eurekaServer:proxyHost
/// </summary>
public string ProxyHost
{
get
{
return _options.ProxyHost;
}
set
{
_options.ProxyHost = value;
}
}
/// <summary>
/// Gets or sets configuration property: eureka:client:eurekaServer:proxyPort
/// </summary>
public int ProxyPort
{
get
{
return _options.ProxyPort;
}
set
{
_options.ProxyPort = value;
}
}
/// <summary>
/// Gets or sets configuration property: eureka:client:eurekaServer:proxyUserName
/// </summary>
public string ProxyUserName
{
get
{
return _options.ProxyUserName;
}
set
{
_options.ProxyUserName = value;
}
}
/// <summary>
/// Gets or sets configuration property: eureka:client:eurekaServer:proxyPassword
/// </summary>
public string ProxyPassword
{
get
{
return _options.ProxyPassword;
}
set
{
_options.ProxyPassword = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether configuration property: eureka:client:eurekaServer:shouldGZipContent
/// </summary>
public bool ShouldGZipContent
{
get
{
return _options.ShouldGZipContent;
}
set
{
_options.ShouldGZipContent = value;
}
}
/// <summary>
/// Gets or sets configuration property: eureka:client:eurekaServer:connectTimeoutSeconds
/// </summary>
public int ConnectTimeoutSeconds
{
get
{
return _options.EurekaServerConnectTimeoutSeconds;
}
set
{
_options.EurekaServerConnectTimeoutSeconds = value;
}
}
/// <summary>
/// Gets or sets configuration property: eureka:client:eurekaServer:retryCount
/// </summary>
public int RetryCount
{
get
{
return _options.EurekaServerRetryCount;
}
set
{
_options.EurekaServerRetryCount = value;
}
}
}
}
}
| 28.607143 | 125 | 0.494521 | [
"Apache-2.0"
] | acesyde/steeltoe | src/Discovery/src/EurekaBase/EurekaClientOptions.cs | 7,211 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
namespace DataBase
{
public class StyleColumnTable
{
public string spsql = "SP_StyleColumnTable";
#region Column 1
public int AddCol1(string Name)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "ADD_COL1");
p[1] = new SqlParameter("@ColumnName", Name);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int AddCol1New(string C1Name, string image1,string brandStatus, string ID)
{
string connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection connection = new SqlConnection(connectionString);
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction("AddCol1New");
command.Connection = connection;
command.Transaction = transaction;
try
{
int result = 0;
command.Parameters.AddWithValue("@C1Name", C1Name);
command.Parameters.AddWithValue("@image1", image1);
command.Parameters.AddWithValue("@brandStatus", brandStatus);
if (ID.Equals("0"))
{
command.CommandText = "INSERT INTO Column1 (C1Name,brandImage,brandStatus) " +
" Values (@C1Name,@image1,@brandStatus)";
}
else
{
string query = "update Column1 set C1Name=@C1Name,brandStatus=@brandStatus";
if(!image1.Equals(""))
{
query += ",brandImage=@image1";
}
query += " where Col1ID=@Col1ID";
command.CommandText = query;
command.Parameters.AddWithValue("@Col1ID", ID);
}
command.ExecuteNonQuery();
command.Parameters.Clear();
transaction.Commit();
if (connection.State == ConnectionState.Open)
connection.Close();
return result;
}
catch (Exception ex)
{
try
{
transaction.Rollback();
if (connection.State == ConnectionState.Open)
connection.Close();
RecordExceptionCls rex = new RecordExceptionCls();
rex.recordException(ex);
return -1;
}
catch (Exception ex2)
{
if (connection.State == ConnectionState.Open)
connection.Close();
RecordExceptionCls rex = new RecordExceptionCls();
rex.recordException(ex2);
return -1;
}
}
}
public DataSet BindCol1()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_COL1");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet GetCol1ByID(int ColumnID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "GET_COL1_BY_ID");
p[1] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int UpdateCol1(string Name, string ColumnID)
{
SqlParameter[] p = new SqlParameter[3];
p[0] = new SqlParameter("@MODE", "UPDATE_COL1");
p[1] = new SqlParameter("@ColumnName", Name);
p[2] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
#region Column 2
public int AddCol2(string Name)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "ADD_COL2");
p[1] = new SqlParameter("@ColumnName", Name);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol2()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_COL2");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet GetCol2ByID(int ColumnID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "GET_COL2_BY_ID");
p[1] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int UpdateCol2(string Name, string ColumnID)
{
SqlParameter[] p = new SqlParameter[3];
p[0] = new SqlParameter("@MODE", "UPDATE_COL2");
p[1] = new SqlParameter("@ColumnName", Name);
p[2] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
#region Column 3
public int AddCol3(string Name)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "ADD_COL3");
p[1] = new SqlParameter("@ColumnName", Name);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol3()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_COL3");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet GetCol3ByID(int ColumnID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "GET_COL3_BY_ID");
p[1] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int UpdateCol3(string Name, string ColumnID)
{
SqlParameter[] p = new SqlParameter[3];
p[0] = new SqlParameter("@MODE", "UPDATE_COL3");
p[1] = new SqlParameter("@ColumnName", Name);
p[2] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
#region Column 4
public int AddCol4(string Name)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "ADD_COL4");
p[1] = new SqlParameter("@ColumnName", Name);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol4()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_COL4");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet GetCol4ByID(int ColumnID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "GET_COL4_BY_ID");
p[1] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int UpdateCol4(string Name, string ColumnID)
{
SqlParameter[] p = new SqlParameter[3];
p[0] = new SqlParameter("@MODE", "UPDATE_COL4");
p[1] = new SqlParameter("@ColumnName", Name);
p[2] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
#region Column 5
public int AddCol5(string Name)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "ADD_COL5");
p[1] = new SqlParameter("@ColumnName", Name);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol5()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_COL5");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet GetCol5ByID(int ColumnID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "GET_COL5_BY_ID");
p[1] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int UpdateCol5(string Name, string ColumnID)
{
SqlParameter[] p = new SqlParameter[3];
p[0] = new SqlParameter("@MODE", "UPDATE_COL5");
p[1] = new SqlParameter("@ColumnName", Name);
p[2] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
#region Column 6
public int AddCol6(string Name)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "ADD_COL6");
p[1] = new SqlParameter("@ColumnName", Name);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol6()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_COL6");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet GetCol6ByID(int ColumnID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "GET_COL6_BY_ID");
p[1] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int UpdateCol6(string Name, string ColumnID)
{
SqlParameter[] p = new SqlParameter[3];
p[0] = new SqlParameter("@MODE", "UPDATE_COL6");
p[1] = new SqlParameter("@ColumnName", Name);
p[2] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
#region Column 7
public int AddCol7(string Name)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "ADD_COL7");
p[1] = new SqlParameter("@ColumnName", Name);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol7()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_COL7");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet GetCol7ByID(int ColumnID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "GET_COL7_BY_ID");
p[1] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int UpdateCol7(string Name, string ColumnID)
{
SqlParameter[] p = new SqlParameter[3];
p[0] = new SqlParameter("@MODE", "UPDATE_COL7");
p[1] = new SqlParameter("@ColumnName", Name);
p[2] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
#region Column 8
public int AddCol8(string Name)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "ADD_COL8");
p[1] = new SqlParameter("@ColumnName", Name);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol8()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_COL8");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet GetCol8ByID(int ColumnID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "GET_COL8_BY_ID");
p[1] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int UpdateCol8(string Name, string ColumnID)
{
SqlParameter[] p = new SqlParameter[3];
p[0] = new SqlParameter("@MODE", "UPDATE_COL8");
p[1] = new SqlParameter("@ColumnName", Name);
p[2] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
#region Column 9
public int AddCol9(string Name)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "ADD_COL9");
p[1] = new SqlParameter("@ColumnName", Name);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol9()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_COL9");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet GetCol9ByID(int ColumnID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "GET_COL9_BY_ID");
p[1] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int UpdateCol9(string Name, string ColumnID)
{
SqlParameter[] p = new SqlParameter[3];
p[0] = new SqlParameter("@MODE", "UPDATE_COL9");
p[1] = new SqlParameter("@ColumnName", Name);
p[2] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
#region Column 10
public int AddCol10(string Name)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "ADD_COL10");
p[1] = new SqlParameter("@ColumnName", Name);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol10()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_COL10");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet GetCol10ByID(int ColumnID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "GET_COL10_BY_ID");
p[1] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int UpdateCol10(string Name, string ColumnID)
{
SqlParameter[] p = new SqlParameter[3];
p[0] = new SqlParameter("@MODE", "UPDATE_COL10");
p[1] = new SqlParameter("@ColumnName", Name);
p[2] = new SqlParameter("@ColumnID", ColumnID);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
#region Column Table Settings
public DataSet BindColSetting()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_COL_SETTING");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindAssignedColSetting()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_ASSIGNED_COL_SETTING");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int UpdateColSetting(string SettingName, bool IsAssigned, string CSID)
{
SqlParameter[] p = new SqlParameter[4];
p[0] = new SqlParameter("@MODE", "UPDATE_COL_SETTING");
p[1] = new SqlParameter("@SettingName", SettingName);
p[2] = new SqlParameter("@CTSettingID", CSID);
p[3] = new SqlParameter("@IsAssigned", IsAssigned);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
#region Column Control Settings
public DataSet BindColControlSetting()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_COL_CONTROL_SETTING");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int AddVirtualLocationSetting(string SettingName, bool IsAssigned, string StyleCSID, string LocationID)
{
SqlParameter[] p = new SqlParameter[5];
p[0] = new SqlParameter("@MODE", "ADD_VIRTUAL_LOCATION_SETTING");
p[1] = new SqlParameter("@SettingName", SettingName);
p[2] = new SqlParameter("@StyleCSID", StyleCSID);
p[3] = new SqlParameter("@IsAssigned", IsAssigned);
p[4] = new SqlParameter("@LocationID", LocationID);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public int UpdateColControlSetting(string SettingName, bool IsAssigned, string StyleCSID)
{
SqlParameter[] p = new SqlParameter[4];
p[0] = new SqlParameter("@MODE", "UPDATE_COL_CONTROL_SETTING");
p[1] = new SqlParameter("@SettingName", SettingName);
p[2] = new SqlParameter("@StyleCSID", StyleCSID);
p[3] = new SqlParameter("@IsAssigned", IsAssigned);
return DataBase.SqlHelper.ExecuteNonQuery(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindAssignedColControlSetting()
{
SqlParameter[] p = new SqlParameter[1];
p[0] = new SqlParameter("@MODE", "BIND_ASSIGN_COL_CONTROL_SETTING");
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindVirtualLocationSetting(string LocationID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "BIND_VIRTUAL_LOCATION_SETTING");
p[1] = new SqlParameter("@LocationID", LocationID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
#region Item style search
public DataSet BindCol1ByItemCatID(string ItemcatID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "BIND_COL1_BY_ITEMCATID");
p[1] = new SqlParameter("@ItemCatID", ItemcatID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol2ByItemCatID(string ItemcatID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "BIND_COL2_BY_ITEMCATID");
p[1] = new SqlParameter("@ItemCatID", ItemcatID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol3ByItemCatID(string ItemcatID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "BIND_COL3_BY_ITEMCATID");
p[1] = new SqlParameter("@ItemCatID", ItemcatID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol4ByItemCatID(string ItemcatID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "BIND_COL4_BY_ITEMCATID");
p[1] = new SqlParameter("@ItemCatID", ItemcatID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol5ByItemCatID(string ItemcatID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "BIND_COL5_BY_ITEMCATID");
p[1] = new SqlParameter("@ItemCatID", ItemcatID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol6ByItemCatID(string ItemcatID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "BIND_COL6_BY_ITEMCATID");
p[1] = new SqlParameter("@ItemCatID", ItemcatID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol7ByItemCatID(string ItemcatID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "BIND_COL7_BY_ITEMCATID");
p[1] = new SqlParameter("@ItemCatID", ItemcatID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol8ByItemCatID(string ItemcatID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "BIND_COL8_BY_ITEMCATID");
p[1] = new SqlParameter("@ItemCatID", ItemcatID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol9ByItemCatID(string ItemcatID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "BIND_COL9_BY_ITEMCATID");
p[1] = new SqlParameter("@ItemCatID", ItemcatID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
public DataSet BindCol10ByItemCatID(string ItemcatID)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = new SqlParameter("@MODE", "BIND_COL10_BY_ITEMCATID");
p[1] = new SqlParameter("@ItemCatID", ItemcatID);
return DataBase.SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, spsql, p);
}
#endregion
}
} | 41.843994 | 145 | 0.608791 | [
"MIT"
] | hasnainsayed/MNMNew | App_Code/Subject/StyleColumnTable.cs | 26,824 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ET2017_TuningTool.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ET2017_TuningTool.Model.Tests
{
[TestClass()]
public class PIDListModelTests
{
[TestMethod()]
public void SaveAsFileTest()
{
Assert.Fail();
}
}
} | 20.8 | 52 | 0.685096 | [
"MIT"
] | TK-R/ET2017-TuningTool | ET2017-TuningToolTests/Model/PIDListModelTests.cs | 418 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace PerformanceEf6.EF6.Models
{
[Table("Person.Person")]
public partial class Person
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Person()
{
BusinessEntityContacts = new HashSet<BusinessEntityContact>();
EmailAddresses = new HashSet<EmailAddress>();
Customers = new HashSet<Customer>();
PersonCreditCards = new HashSet<PersonCreditCard>();
PersonPhones = new HashSet<PersonPhone>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int BusinessEntityID { get; set; }
[Required]
[StringLength(2)]
public string PersonType { get; set; }
public bool NameStyle { get; set; }
[StringLength(8)]
public string Title { get; set; }
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[StringLength(50)]
public string MiddleName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
[StringLength(10)]
public string Suffix { get; set; }
public int EmailPromotion { get; set; }
[Column(TypeName = "xml")]
public string AdditionalContactInfo { get; set; }
[Column(TypeName = "xml")]
public string Demographics { get; set; }
public Guid rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public virtual Employee Employee { get; set; }
public virtual BusinessEntity BusinessEntity { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<BusinessEntityContact> BusinessEntityContacts { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<EmailAddress> EmailAddresses { get; set; }
public virtual Password Password { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Customer> Customers { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PersonCreditCard> PersonCreditCards { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PersonPhone> PersonPhones { get; set; }
}
}
| 35.670732 | 128 | 0.673162 | [
"BSD-3-Clause"
] | Manishkr117/DesignPattern | DOTNETCORE/EFCoreSamples/PerformanceEf6/EF6/Models/Person.cs | 2,925 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace CORS
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.EnableCors();
}
}
}
| 22.703704 | 62 | 0.569331 | [
"MIT"
] | MarcinHoppe/AspNet.WebApi.Security.Samples | CORS/CORS/App_Start/WebApiConfig.cs | 615 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ipscan
{
class Range
{
public string from;
public string to;
public Range(string from, string to)
{
this.from = from;
this.to = to;
}
}
}
| 16.333333 | 44 | 0.580175 | [
"Apache-2.0"
] | n0ise9914/ipscan | ipscan/Range.cs | 345 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Core;
namespace slimCODE.Extensions
{
/// <summary>
/// Provides extension methods for <see cref="CoreDispatcher"/> instances.
/// </summary>
public static partial class CoreDispatcherExtensions
{
/// <summary>
/// Runs the provided <see cref="DispatchedHandler"/> action on a <see cref="CoreDispatcher"/> with normal priority.
/// </summary>
/// <param name="dispatcher"></param>
/// <param name="ct"></param>
/// <param name="agileCallback"></param>
/// <returns></returns>
public static Task RunNormalAsync(this CoreDispatcher dispatcher, CancellationToken ct, DispatchedHandler agileCallback)
{
return dispatcher
.RunAsync(CoreDispatcherPriority.Normal, agileCallback)
.AsTask(ct);
}
/// <summary>
/// Runs the provided <see cref="Func{TResult}"/> on a <see cref="CoreDispatcher"/> in normal priority.
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="dispatcher"></param>
/// <param name="func"></param>
/// <returns></returns>
public static async Task<TResult> RunNormalAsync<TResult>(
this CoreDispatcher dispatcher,
Func<TResult> func)
{
var source = new TaskCompletionSource<TResult>();
await dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
() =>
{
try
{
source.SetResult(func());
}
catch (Exception error)
{
source.SetException(error);
}
});
return await source.Task;
}
/// <summary>
/// Runs an async function on a <see cref="CoreDispatcher"/> in normal priority.
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="dispatcher"></param>
/// <param name="ct"></param>
/// <param name="asyncFunc"></param>
/// <returns></returns>
public static async Task<TResult> RunNormalAsync<TResult>(
this CoreDispatcher dispatcher,
CancellationToken ct,
Func<CancellationToken, Task<TResult>> asyncFunc)
{
var source = new TaskCompletionSource<TResult>();
await dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
async () =>
{
try
{
source.SetResult(await asyncFunc(ct));
}
catch (Exception error)
{
source.SetException(error);
}
});
// TODO: ct
return await source.Task;
}
/// <summary>
/// Logs an error if the current thread is not the expected thread compared to a <see cref="CoreDispatcher"/>.
/// </summary>
/// <param name="dispatcher"></param>
/// <param name="mustBeOnUIThread"></param>
public static void VerifyThread(this CoreDispatcher dispatcher, bool mustBeOnUIThread)
{
if (dispatcher.HasThreadAccess != mustBeOnUIThread)
{
/*
Logs.UseLogger(logger =>
logger.ReportError(
"Wrong thread. Was expecting {0}.".FormatInvariant(mustBeOnUIThread ? "dispatcher" : "!dispatcher")));
*/
}
}
}
}
| 34.681818 | 128 | 0.513761 | [
"MIT"
] | slimCODE/slim-lib | src/slimLIB.Uno/Extensions/CoreDispatcherExtensions.cs | 3,817 | C# |
// -------------------------------------------
// Control Freak 2
// Copyright (C) 2013-2016 Dan's Game Tools
// http://DansGameTools.com
// -------------------------------------------
//! \cond
using UnityEngine;
namespace ControlFreak2
{
public static class CFUtils
{
public const float
SqrtOf2 = 1.4142135623730950488016887242097f,
SqrtOf3 = 1.7320508075688772935274463415059f,
OneOverSqrtOf2 = 0.70710678118654752440084436210485f,
OneOverSqrtOf3 = 0.57735026918962576450914878050196f,
TanLenFor45Tri = 0.7653668647301795434569199680608f,
TanLenFor90Tri = SqrtOf2;
public const float
MAX_DELTA_TIME = 0.5f;
private const float
MAX_LEFT_FACTOR = 0.75f;
// -----------------------
static public float realDeltaTime
{ get { return Time.unscaledDeltaTime; } }
// -----------------
static public float realDeltaTimeClamped
{ get { return Mathf.Min(Time.unscaledDeltaTime, MAX_DELTA_TIME); } }
#if UNITY_EDITOR
// ------------------------
static public bool editorStopped { get { return !UnityEditor.EditorApplication.isPlaying; } }
#else
static public bool editorStopped { get { return false; } }
#endif
// ------------------
#if CF_FORCE_MOBILE_MODE
static public bool forcedMobileModeEnabled { get { return true; } }
#else
static public bool forcedMobileModeEnabled { get { return false; } }
#endif
// ------------------------
static public string LogPrefixFull()
{
#if UNITY_EDITOR
return ("[" + (editorStopped ? "STOP" : "PLAY") + "][" + Time.frameCount + "] ");
#else
return ("[" + Time.frameCount + "] ");
#endif
}
// ------------------------
static public string LogPrefix()
{
return ("[" + Time.frameCount + "] ");
}
// ------------------
static public float ApplyDeltaInput(float accum, float delta)
{
if ((accum >= 0) && (delta >= 0))
return Mathf.Max(accum, delta);
else if ((accum < 0) && (delta < 0))
return Mathf.Min(accum, delta);
else
return (accum + delta);
}
// -----------------
static public int ApplyDeltaInputInt(int accum, int delta)
{
if ((accum >= 0) && (delta >= 0))
return Mathf.Max(accum, delta);
else if ((accum < 0) && (delta < 0))
return Mathf.Min(accum, delta);
else
return (accum + delta);
}
// --------------------
static public void ApplySignedDeltaInput(float v, ref float plusAccum, ref float minusAccum)
{
if (v >= 0)
{
if (v > plusAccum)
plusAccum = v;
}
else if (v < minusAccum)
minusAccum = v;
}
// --------------------
static public void ApplySignedDeltaInputInt(int v, ref int plusAccum, ref int minusAccum)
{
if (v >= 0)
{
if (v > plusAccum)
plusAccum = v;
}
else if (v < minusAccum)
minusAccum = v;
}
// ---------------------
static public int GetScrollValue(float drag, int prevScroll, float thresh, float magnet)
{
bool flippedAxis = (drag < 0);
if (flippedAxis)
{
drag = -drag;
prevScroll = -prevScroll;
}
float scroll = drag / thresh;
int scrollInt = Mathf.FloorToInt(scroll);
return (flippedAxis ? -scrollInt : scrollInt);
}
// ----------------
static public float MoveTowards(float a, float b, float secondsPerUnit, float deltaTime, float epsilon)
{
if (Mathf.Abs(b - a) <= epsilon)
return b;
return ((secondsPerUnit < 0.001f) || (secondsPerUnit <= deltaTime)) ? b : Mathf.MoveTowards(a, b, (deltaTime / secondsPerUnit));
}
// ----------------
static private float GetLerpFactor(float smoothingTime, float deltaTime, float maxLerpFactor)
{
return Mathf.Min(maxLerpFactor, ((smoothingTime <= deltaTime) ? 1 : (deltaTime / smoothingTime)));
}
// ----------------
static public float SmoothTowards(float a, float b, float smoothingTime, float deltaTime, float epsilon, float maxLeftFactor = MAX_LEFT_FACTOR)
{
if (Mathf.Abs(b - a) <= epsilon)
return b;
return ((smoothingTime < 0.001f)) ? b : Mathf.Lerp(a, b, GetLerpFactor(smoothingTime, deltaTime, maxLeftFactor));
}
// ----------------
static public float SmoothTowardsAngle(float a, float b, float smoothingTime, float deltaTime, float epsilon, float maxLeftFactor = MAX_LEFT_FACTOR)
{
if (Mathf.Abs(Mathf.DeltaAngle(b, a)) <= epsilon)
return b;
return ((smoothingTime < 0.001f)) ? b :
Mathf.MoveTowardsAngle(a, b, Mathf.Abs(b - a) * GetLerpFactor(smoothingTime, deltaTime, maxLeftFactor));
}
static public Vector2 SmoothTowardsVec2(Vector2 a, Vector2 b, float smoothingTime, float deltaTime, float sqrEpsilon, float maxLeftFactor = MAX_LEFT_FACTOR)
{
if ((sqrEpsilon != 0) && ((b - a).sqrMagnitude <= sqrEpsilon))
return b;
return ((smoothingTime < 0.001f)) ? b : Vector2.Lerp(a, b, GetLerpFactor(smoothingTime, deltaTime, maxLeftFactor));
}
static public Vector3 SmoothTowardsVec3(Vector3 a, Vector3 b, float smoothingTime, float deltaTime, float sqrEpsilon, float maxLeftFactor = MAX_LEFT_FACTOR)
{
if ((sqrEpsilon != 0) && ((b - a).sqrMagnitude <= sqrEpsilon))
return b;
return ((smoothingTime < 0.001f)) ? b : Vector3.Lerp(a, b, GetLerpFactor(smoothingTime, deltaTime, maxLeftFactor));
}
static public Color SmoothTowardsColor(Color a, Color b, float smoothingTime, float deltaTime, float maxLeftFactor = MAX_LEFT_FACTOR)
{ return ((smoothingTime < 0.001f)) ? b : Color.Lerp(a, b, GetLerpFactor(smoothingTime, deltaTime, maxLeftFactor)); }
static public Quaternion SmoothTowardsQuat(Quaternion a, Quaternion b, float smoothingTime, float deltaTime, float maxLeftFactor = MAX_LEFT_FACTOR)
{ return ((smoothingTime < 0.001f)) ? b : Quaternion.Slerp(a, b, GetLerpFactor(smoothingTime, deltaTime, maxLeftFactor)); }
// --------------------
static public float SmoothDamp(float valFrom, float valTo, ref float vel, float smoothingTime, float deltaTime, float epsilon)
{
if ((smoothingTime < 0.001f) || (Mathf.Abs(valTo - valFrom) <= epsilon))
{
vel = 0;
return valTo;
}
return Mathf.SmoothDamp(valFrom, valTo, ref vel, smoothingTime, 10000000, deltaTime);
}
// ----------------------
static public Color ScaleColorAlpha(Color color, float alphaScale)
{
color.a *= alphaScale;
return color;
}
// -----------------
static public Component GetComponentHereOrInParent(Component comp, System.Type compType)
{
if (comp == null)
return null;
Component c = null;
return (((c = comp.GetComponent(compType)) != null) ? c : comp.GetComponentInParent(compType));
}
// -----------------------
static public bool IsStretchyRectTransform(Transform tr)
{
RectTransform rectTr = (tr as RectTransform);
return ((rectTr != null) && (rectTr.anchorMax != rectTr.anchorMin));
}
// ----------------------
static public Rect TransformRect(Rect r, Matrix4x4 tr, bool round)
{
Bounds bb = TransformRectAsBounds(r, tr, round);
Vector3 min = bb.min;
Vector3 size = bb.size;
return new Rect(min.x, min.y, size.x, size.y);
}
// ------------------------
static public Bounds TransformRectAsBounds(Rect r, Matrix4x4 tr, bool round)
{
Vector3 cen = tr.MultiplyPoint3x4(r.center);
Vector3 vx = tr.MultiplyVector(new Vector3(1, 0, 0));
Vector3 vy = tr.MultiplyVector(new Vector3(0, 1, 0));
float w = r.width * 0.5f;
float h = r.height * 0.5f;
vx *= w;
vy *= h;
Vector3 min, max;
Vector3 v;
if (round)
{
// 4 points of a 180 degree slice...
// Up and down.
v = vy;
min = Vector3.Min(v, -v);
max = Vector3.Max(v, -v);
// Up-right and down-left...
v = ((vx * 0.77f) + (vy * 0.77f));
min = Vector3.Min(min, Vector3.Min (v, -v));
max = Vector3.Max(max, Vector3.Max (v, -v));
// Left and right...
v = vx;
min = Vector3.Min(min, Vector3.Min (v, -v));
max = Vector3.Max(max, Vector3.Max(v, -v));
// Up-left and down-right...
v = ((vx * -0.77f) + (vy * 0.77f));
min = Vector3.Min(min, Vector3.Min (v, -v));
max = Vector3.Max(max, Vector3.Max(v, -v));
}
else
{
// 2 corners and their mirrors...
// Up-right and down-left...
v = vx + vy;
min = Vector3.Min(v, -v);
max = Vector3.Max(v, -v);
// Down-right and up-left...
v = vx - vy;
min = Vector3.Min(min, Vector3.Min (v, -v));
max = Vector3.Max(max, Vector3.Max(v, -v));
}
return new Bounds(cen + ((min + max) * 0.5f), (max - min)); //new Bounds.(cen, size);
}
// ------------------------
static public Matrix4x4 ChangeMatrixTranl(Matrix4x4 m, Vector3 newTransl)
{
m.SetColumn(3, new Vector4(newTransl.x, newTransl.y, newTransl.z, m.m33));
return m;
}
// -----------------
static public Bounds GetWorldAABB(Matrix4x4 tf, Vector3 center, Vector3 size)
{
Vector3 a = center - (size * 0.5f);
Vector3 b = center + (size * 0.5f);
Vector3 min, max, v;
v = tf.MultiplyPoint3x4(new Vector3(a.x, a.y, a.z)); min = max = v;
v = tf.MultiplyPoint3x4(new Vector3(a.x, a.y, b.z)); min = Vector3.Min(min, v); max = Vector3.Max(max, v);
v = tf.MultiplyPoint3x4(new Vector3(a.x, b.y, a.z)); min = Vector3.Min(min, v); max = Vector3.Max(max, v);
v = tf.MultiplyPoint3x4(new Vector3(a.x, b.y, b.z)); min = Vector3.Min(min, v); max = Vector3.Max(max, v);
v = tf.MultiplyPoint3x4(new Vector3(b.x, a.y, a.z)); min = Vector3.Min(min, v); max = Vector3.Max(max, v);
v = tf.MultiplyPoint3x4(new Vector3(b.x, b.y, a.z)); min = Vector3.Min(min, v); max = Vector3.Max(max, v);
v = tf.MultiplyPoint3x4(new Vector3(b.x, a.y, b.z)); min = Vector3.Min(min, v); max = Vector3.Max(max, v);
v = tf.MultiplyPoint3x4(new Vector3(b.x, b.y, b.z)); min = Vector3.Min(min, v); max = Vector3.Max(max, v);
return new Bounds((min + max) * 0.5f, (max - min));
}
// --------------
static public Bounds GetWorldAABB(Matrix4x4 tf, Bounds localBounds)
{
return GetWorldAABB(tf, localBounds.center, localBounds.size);
}
// ---------------------
static public Rect GetWorldRect(Matrix4x4 tf, Bounds localBounds)
{
Bounds worldBounds = GetWorldAABB(tf, localBounds);
Vector3 min = worldBounds.min;
Vector3 max = worldBounds.max;
return Rect.MinMaxRect(min.x, min.y, max.x, max.y);
}
// ----------------------
static public Vector2 ClampRectInside(Rect rect, bool rectIsRound, Rect limiterRect, bool limiterIsRound)
{
if (limiterIsRound)
{
if (rectIsRound)
return ClampEllipseInsideEllipse(rect, limiterRect);
else
return ClampRectInsideEllipse(rect, limiterRect);
}
else
{
return ClampRectInsideRect(rect, limiterRect);
}
}
// ------------------
static public Vector2 ClampRectInsideEllipse(Rect rect, Rect limiterRect)
{
return ClampEllipseInsideEllipse(rect, limiterRect); // TODO!!
}
// ------------------
static public Vector2 ClampEllipseInsideEllipse(Rect rect, Rect limiterRect)
{
Vector2 rectRad = rect.size * 0.5f;
Vector2 limiterRad = limiterRect.size * 0.5f;
Vector2 rectCen = rect.center;
Vector2 limiterCen = limiterRect.center;
if ((rectRad.x >= limiterRad.x) || (rectRad.y >= limiterRad.y))
{
Vector2 finalOfs;
// Clamped is bigger on X axis...
if (rectRad.x >= limiterRad.x)
{
finalOfs.x = (limiterCen.x - rectCen.x);
}
else
{
finalOfs.x = ((rectCen.x >= limiterCen.x) ?
Mathf.Min(0, ((limiterCen.x + limiterRad.x) - (rectCen.x + rectRad.x))) :
Mathf.Max(0, ((limiterCen.x - limiterRad.x) - (rectCen.x - rectRad.x))) );
}
// Clamped is bigger on the Y axis..
if (rectRad.y >= limiterRad.y)
{
finalOfs.y = (limiterCen.y - rectCen.y);
}
else
{
finalOfs.y = ((rectCen.y >= limiterCen.y) ?
Mathf.Min(0, ((limiterCen.y + limiterRad.y) - (rectCen.y + rectRad.y))) :
Mathf.Max(0, ((limiterCen.y - limiterRad.y) - (rectCen.y - rectRad.y))) );
}
return finalOfs;
}
Vector2 radDiff = (limiterRad - rectRad);
Vector2 originalOfs = (rectCen - limiterCen);
Vector2 ofs = originalOfs;
ofs.x /= radDiff.x;
ofs.y /= radDiff.y;
if (ofs.sqrMagnitude < 1)
return Vector2.zero;
ofs.Normalize();
ofs.x *= radDiff.x;
ofs.y *= radDiff.y;
return (ofs - originalOfs);
}
// -----------------------
static public Vector2 ClampRectInsideRect(Rect rect, Rect limiterRect)
{
Vector2 cen0 = rect.center;
Vector2 cen1 = limiterRect.center;
Vector2 rad0 = rect.size * 0.5f;
Vector2 rad1 = limiterRect.size * 0.5f;
Vector2
min0 = (cen0 - rad0),
max0 = (cen0 + rad0),
min1 = (cen1 - rad1),
max1 = (cen1 + rad1);
Vector2 finalOfs = Vector2.zero;
if (rad0.x >= rad1.x)
{
finalOfs.x = (cen1.x - cen0.x);
}
else
{
if (max0.x > max1.x)
finalOfs.x = (max1.x - max0.x);
else if (min0.x < min1.x)
finalOfs.x = (min1.x - min0.x);
}
if (rad0.y >= rad1.y)
{
finalOfs.y = (cen1.y - cen0.y);
}
else
{
if (max0.y > max1.y)
finalOfs.y = (max1.y - max0.y);
else if (min0.y < min1.y)
finalOfs.y = (min1.y - min0.y);
}
return finalOfs;
}
// ----------------------
// Unit Cicrle - rad = 1.0
// ----------------------
static public Vector2 ClampInsideUnitCircle(Vector2 np)
{
return ((np.sqrMagnitude < 1) ? np : np.normalized);
}
// --------------------
// Unit Square - min = -1, max = 1
// --------------------
static public Vector2 ClampInsideUnitSquare(Vector2 np)
{
float t = 1;
if ((np.x > 1) || (np.x < -1)) t = Mathf.Abs(1.0f / np.x);
if ((np.y > 1) || (np.y < -1)) t = Mathf.Min(t, Mathf.Abs(1.0f / np.y));
return ((t < 1) ? (np * t) : np);
}
// --------------------
// Unit Square - min = -1, max = 1
// --------------------
static public Vector2 ClampPerAxisInsideUnitSquare(Vector2 np)
{
np.x = Mathf.Clamp(np.x, -1, 1);
np.y = Mathf.Clamp(np.y, -1, 1);
return np;
}
// ------------------
static public Vector2 ClampInsideRect(Vector2 v, Rect r)
{
if (r.Contains(v))
return v;
Vector2 cen = r.center;
Vector2 rad = r.size * 0.5f;
v -= cen;
float t = 1;
if ((v.x > rad.x) || (v.x < -rad.x)) t = Mathf.Abs(rad.x / v.x);
if ((v.y > rad.y) || (v.y < -rad.y)) t = Mathf.Min(t, Mathf.Abs(rad.y / v.y));
return (cen + (v * t));
}
// ---------------------------
/// \name Utils
/// \{
// ---------------------------
// ---------------
/// Return true if given direction is one of diagonal directions.
// ---------------
static public bool IsDirDiagonal(
Dir dir ///< Direction code.
)
{
return ((((int)dir - (int)Dir.U) & 1) == 1);
}
// ---------------
/// Return positive angle for given normalized vector. Angles start from top position and go clockwise.
// ---------------
static public float VecToAngle(Vector2 vec)
{
return NormalizeAnglePositive(Mathf.Atan2(vec.x, vec.y) * Mathf.Rad2Deg);
}
// ---------------
/// Return positive angle for given unnormalized vector. Angles start from top position and go clockwise.
// ---------------
static public float VecToAngle(Vector2 vec, float defaultAngle, float deadZoneSq)
{
float m = vec.sqrMagnitude;
if (m < deadZoneSq)
return defaultAngle;
if (Mathf.Abs(m - 1.0f) > 0.0001f)
vec.Normalize();
return NormalizeAnglePositive(Mathf.Atan2(vec.x, vec.y) * Mathf.Rad2Deg);
}
// -----------------
/// Return angle in degrees for given direction code.
// -----------------
static public float DirToAngle(
Dir d ///< Direction code.
)
{
if ((d < Dir.U) || (d > Dir.UL))
return 0;
return ((float)((int)d - (int)Dir.U) * 45.0f);
}
// ----------------
//! Get nearest direction for given angle.
// ----------------
static public Dir DirFromAngle(
float ang, //!< Angle in degrees
bool as8way //!< If true nearest of 8-way directions will be returned, otherwise one of major 4-way directions.
)
{
ang += (as8way ? 22.5f : 45.0f);
ang = NormalizeAnglePositive(ang);
Dir dir = Dir.N;
if (as8way)
{
if (ang < 45) dir = Dir.U;
else if (ang < 90) dir = Dir.UR;
else if (ang < 135) dir = Dir.R;
else if (ang < 180) dir = Dir.DR;
else if (ang < 225) dir = Dir.D;
else if (ang < 270) dir = Dir.DL;
else if (ang < 315) dir = Dir.L;
else dir = Dir.UL;
}
else
{
if (ang < 90) dir = Dir.U;
else if (ang < 180) dir = Dir.R;
else if (ang < 270) dir = Dir.D;
else dir = Dir.L;
}
return dir;
}
// ----------------
//! Get nearest direction for given angle with respect to last direction.
// ----------------
static public Dir DirFromAngleEx(
float ang, //!< Angle in degrees
bool as8way, //!< If true nearest of 8-way directions will be returned, otherwise one of major 4-way directions.
Dir lastDir, //!< Last direction.
float magnetPow //!< Normalized angular magnet power.
)
{
if (lastDir != Dir.N && (magnetPow > 0.001f))
{
if (Mathf.Abs(Mathf.DeltaAngle(ang, CFUtils.DirToAngle(lastDir))) <
((1.0f + (Mathf.Clamp01(magnetPow) * 0.5f)) * (as8way ? 22.5f : 45.0f)))
return lastDir;
}
return DirFromAngle(ang, as8way);
}
// ---------------------
static public int DirDeltaAngle(Dir dirFrom, Dir dirTo)
{
if ((dirFrom == Dir.N) || (dirTo == Dir.N))
return 0;
return Mathf.RoundToInt(Mathf.DeltaAngle(DirToAngle(dirFrom), DirToAngle(dirTo)));
}
// -------------------------
static public Vector2 DirToNormal(Dir dir)
{
switch (dir)
{
case Dir.U : return new Vector2(0, 1);
case Dir.R : return new Vector2(1, 0);
case Dir.D : return new Vector2(0, -1);
case Dir.L : return new Vector2(-1, 0);
case Dir.UR : return new Vector2(OneOverSqrtOf2, OneOverSqrtOf2);
case Dir.DR : return new Vector2(OneOverSqrtOf2, -OneOverSqrtOf2);
case Dir.DL : return new Vector2(-OneOverSqrtOf2, -OneOverSqrtOf2);
case Dir.UL : return new Vector2(-OneOverSqrtOf2, OneOverSqrtOf2);
}
return Vector2.zero;
}
// -------------------------
static public Vector2 DirToTangent(Dir dir)
{
switch (dir)
{
case Dir.U : return new Vector2(1, 0);
case Dir.R : return new Vector2(0, -1);
case Dir.D : return new Vector2(-1, 0);
case Dir.L : return new Vector2(0, 1);
case Dir.UR : return new Vector2(OneOverSqrtOf2, -OneOverSqrtOf2);
case Dir.DR : return new Vector2(-OneOverSqrtOf2, -OneOverSqrtOf2);
case Dir.DL : return new Vector2(-OneOverSqrtOf2, OneOverSqrtOf2);
case Dir.UL : return new Vector2(OneOverSqrtOf2, OneOverSqrtOf2);
}
return Vector2.zero;
}
// -----------------------
static public Dir GetOppositeDir(Dir dir)
{
switch (dir)
{
case Dir.U : return Dir.D;
case Dir.UR : return Dir.DL;
case Dir.R : return Dir.L;
case Dir.DR : return Dir.UL;
case Dir.D : return Dir.U;
case Dir.DL : return Dir.UR;
case Dir.L : return Dir.R;
case Dir.UL : return Dir.DR;
}
return Dir.N;
}
// -----------------------
static public Vector2 DirToVector(Dir dir, bool circular)
{
switch (dir)
{
case Dir.U : return new Vector2(0, 1);
case Dir.R : return new Vector2(1, 0);
case Dir.D : return new Vector2(0, -1);
case Dir.L : return new Vector2(-1, 0);
case Dir.UR : return (circular ? (new Vector2(OneOverSqrtOf2, OneOverSqrtOf2)).normalized : (new Vector2(1, 1)));
case Dir.DR : return (circular ? (new Vector2(OneOverSqrtOf2, -OneOverSqrtOf2)).normalized : (new Vector2(1, -1)));
case Dir.DL : return (circular ? (new Vector2(-OneOverSqrtOf2, -OneOverSqrtOf2)).normalized : (new Vector2(-1, -1)));
case Dir.UL : return (circular ? (new Vector2(-OneOverSqrtOf2, OneOverSqrtOf2)).normalized : (new Vector2(-1, 1)));
}
return Vector2.zero;
}
// ----------------------
static public Dir VecToDir(Vector2 vec, bool as8way)
{
return DirFromAngle(VecToAngle(vec), as8way);
}
// ---------------------
static public Dir VecToDir(Vector2 vec, Dir defaultDir, float deadZoneSq, bool as8way)
{
float mSq = vec.sqrMagnitude;
if (mSq <= deadZoneSq)
return defaultDir;
if (Mathf.Abs(mSq - 1.0f) > 0.00001f)
vec.Normalize();
return DirFromAngle(VecToAngle(vec), as8way);
}
// -------------------------
// Returns angle between 0 and 360
// -----------------------
static public float NormalizeAnglePositive(float a)
{
if (a >= 360.0f)
return Mathf.Repeat(a, 360.0f);
if (a >= 0)
return a;
if (a <= -360.0f)
a = Mathf.Repeat(a, 360.0f);
return (360.0f + a);
}
// ---------------------
static public float SmartDeltaAngle(float startAngle, float curAngle, float lastDelta)
{
float frameDelta = Mathf.DeltaAngle(startAngle + lastDelta, curAngle);
return lastDelta + frameDelta;
}
// --------------------
static public Dir DigitalToDir(
bool digiU,
bool digiR,
bool digiD,
bool digiL)
{
if (digiU && digiD) digiU = digiD = false;
if (digiR && digiL) digiR = digiL = false;
if (digiU)
return (digiR ? Dir.UR : digiL ? Dir.UL : Dir.U);
else if (digiD)
return (digiR ? Dir.DR : digiL ? Dir.DL : Dir.D);
else
return (digiR ? Dir.R : digiL ? Dir.L : Dir.N);
}
// ---------------------
static public Vector2 CircularToSquareJoystickVec(Vector2 circularVec)
{
if (circularVec.sqrMagnitude < 0.00001f)
return Vector2.zero;
Vector2 v = circularVec;
Vector2 n = circularVec.normalized;
v *= (Mathf.Abs(n.x) + Mathf.Abs(n.y));
v.x = Mathf.Clamp(v.x, -1.0f, 1.0f);
v.y = Mathf.Clamp(v.y, -1.0f, 1.0f);
return v;
}
// ---------------------
static public Vector2 SquareToCircularJoystickVec(Vector2 squareVec)
{
if (squareVec.sqrMagnitude < 0.00001f)
return Vector2.zero;
Vector2 v = squareVec;
Vector2 n = squareVec.normalized;
v /= (Mathf.Abs(n.x) + Mathf.Abs(n.y));
v.x = Mathf.Clamp(v.x, -1.0f, 1.0f);
v.y = Mathf.Clamp(v.y, -1.0f, 1.0f);
return v;
}
/// \}
// --------------------
static public int GetLineNumber(string str, int index)
{
int curLine = 1;
int lastLineStart = 0;
int nextLineStart = -1;
while (((nextLineStart = str.IndexOf('\n', lastLineStart)) >= 0) && (nextLineStart < index))
{
curLine++;
lastLineStart = nextLineStart + 1;
}
return curLine;
}
// --------------------
static public int GetEnumMaxValue(System.Type enumType)
{
int maxVal = 0;
foreach (int v in System.Enum.GetValues(enumType))
maxVal = ((maxVal == 0) ? v : Mathf.Max(maxVal, v));
return maxVal;
}
// ----------------
static public int CycleInt(int curId, int dir, int maxId)
{
curId += dir;
if (curId < 0)
curId = maxId;
else if (curId > maxId)
curId = 0;
return curId;
}
// ------------------
static public void SetEventSystemSelectedObject(GameObject o)
{
UnityEngine.EventSystems.EventSystem s = UnityEngine.EventSystems.EventSystem.current;
if (s != null)
{
s.firstSelectedGameObject = o;
if (s.currentInputModule is ControlFreak2.GamepadInputModule)
{
s.SetSelectedGameObject(null, null);
s.SetSelectedGameObject(o, null);
}
}
}
}
}
//! \endcond
| 25.125272 | 157 | 0.593757 | [
"MIT"
] | ReiiYuki/Firebase-Unity-Realtime-Movement-Demo | Assets/Plugins/Control-Freak-2/Scripts/Utils/CFUtils.cs | 23,067 | C# |
using System.Windows;
namespace GUIConsole.Wpf
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public App()
{
}
}
}
| 14.0625 | 42 | 0.537778 | [
"MIT"
] | Acidburn0zzz/terminal-1 | samples/ConPTY/GUIConsole/GUIConsole.WPF/App.xaml.cs | 225 | C# |
using UnityEngine;
using System.Collections.Generic;
using Phenix.Unity.AI;
public class GOAPActionCombatMoveForward : GOAPActionBase
{
AnimFSMEventCombatMove _eventCombatMove;
Vector3 _finalPos;
public GOAPActionCombatMoveForward(GOAPActionType1 actionType, Agent1 agent,
List<WorldStateBitData> WSPrecondition, List<WorldStateBitDataAction> WSEffect)
: base((int)actionType, agent, WSPrecondition, WSEffect)
{
}
public override void Reset()
{
base.Reset();
_eventCombatMove = null;
_finalPos = Vector3.zero;
}
public override void OnEnter()
{
SendEvent();
}
public override void OnExit(Phenix.Unity.AI.WorldState ws)
{
if (_eventCombatMove != null)
{
_eventCombatMove.Release();
_eventCombatMove = null;
}
base.OnExit(ws);
}
public override bool IsFinished()
{
if (_eventCombatMove == null)
{
return true;
}
return _eventCombatMove.IsFinished || Agent.BlackBoard.DesiredTargetInCombatRange;
}
void SendEvent()
{
_eventCombatMove = AnimFSMEventCombatMove.pool.Get();
_eventCombatMove.moveType = MoveType.FORWARD;
_eventCombatMove.motionType = Agent.BlackBoard.DistanceToDesiredTarget - Agent.BlackBoard.combatRange <= 4 ? MotionType.WALK : MotionType.RUN;
_eventCombatMove.target = Agent.BlackBoard.desiredTarget;
_eventCombatMove.totalMoveDistance = Random.Range((Agent.BlackBoard.DistanceToDesiredTarget - Agent.BlackBoard.combatRange * 0.5f) * 0.5f,
Agent.BlackBoard.DistanceToDesiredTarget - Agent.BlackBoard.combatRange * 0.5f);
_eventCombatMove.minDistanceToTarget = 3;
Agent.FSMComponent.SendEvent(_eventCombatMove);
}
} | 31.220339 | 150 | 0.673724 | [
"MIT"
] | mengtest/samurai | samurai/Assets/Scripts/GOAP1/Actions/GOAPActionCombatMoveForward.cs | 1,844 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
namespace Microsoft.Psi.Visualization.Adapters
{
using System;
using System.Collections.Generic;
using System.Windows;
using MathNet.Spatial.Euclidean;
using Microsoft.Psi.Visualization.Data;
/// <summary>
/// Used to adapt streams of lists of nullable MathNet.Spatial.Euclidean.Point2Ds into lists named points.
/// </summary>
[StreamAdapter]
public class MathNetNullablePoint2DToScatterPlotAdapter : StreamAdapter<Point2D?, List<Tuple<Point, string>>>
{
/// <summary>
/// Initializes a new instance of the <see cref="MathNetNullablePoint2DToScatterPlotAdapter"/> class.
/// </summary>
public MathNetNullablePoint2DToScatterPlotAdapter()
: base(Adapter)
{
}
private static List<Tuple<Point, string>> Adapter(Point2D? value, Envelope env)
{
var list = new List<Tuple<Point, string>>();
if (value.HasValue)
{
list.Add(Tuple.Create(new Point(value.Value.X, value.Value.Y), default(string)));
}
return list;
}
}
} | 32.945946 | 113 | 0.635767 | [
"MIT"
] | Bhaskers-Blu-Org2/psi | Sources/Visualization/Microsoft.Psi.Visualization.Common.Windows/Adapters/MathNetNullablePoint2DToScatterPlotAdapter.cs | 1,221 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
namespace Windows.UI.Interactivity
{
/// <summary>
/// Static class that owns the Triggers and Behaviors attached properties. Handles propagation of AssociatedObject change notifications.
///
/// </summary>
public static class Interaction
{
/// <summary>
/// This property is used as the internal backing store for the public Triggers attached property.
///
/// </summary>
public static readonly DependencyProperty TriggersProperty = DependencyProperty.RegisterAttached("Triggers", typeof(TriggerCollection), typeof(Interaction), new PropertyMetadata(null,new PropertyChangedCallback(Interaction.OnTriggersChanged)));
/// <summary>
/// This property is used as the internal backing store for the public Behaviors attached property.
///
/// </summary>
public static readonly DependencyProperty BehaviorsProperty = DependencyProperty.RegisterAttached("Behaviors", typeof(BehaviorCollection), typeof(Interaction), new PropertyMetadata(null,new PropertyChangedCallback(Interaction.OnBehaviorsChanged)));
/// <summary>
/// Gets the TriggerCollection containing the triggers associated with the specified object.
///
/// </summary>
/// <param name="obj">The object from which to retrieve the triggers.</param>
/// <returns>
/// A TriggerCollection containing the triggers associated with the specified object.
/// </returns>
public static TriggerCollection GetTriggers(DependencyObject obj)
{
TriggerCollection triggerCollection = (TriggerCollection)obj.GetValue(Interaction.TriggersProperty);
if (triggerCollection == null)
{
triggerCollection = new TriggerCollection();
obj.SetValue(Interaction.TriggersProperty, triggerCollection);
}
return triggerCollection;
}
/// <summary>
/// Gets the <see cref="T:System.Windows.Interactivity.BehaviorCollection"/> associated with a specified object.
///
/// </summary>
/// <param name="obj">The object from which to retrieve the <see cref="T:System.Windows.Interactivity.BehaviorCollection"/>.</param>
/// <returns>
/// A <see cref="T:System.Windows.Interactivity.BehaviorCollection"/> containing the behaviors associated with the specified object.
/// </returns>
public static BehaviorCollection GetBehaviors(FrameworkElement obj)
{
BehaviorCollection behaviorCollection = (BehaviorCollection)obj.GetValue(Interaction.BehaviorsProperty);
if (behaviorCollection == null)
{
behaviorCollection = new BehaviorCollection();
obj.SetValue(Interaction.BehaviorsProperty, behaviorCollection);
}
return behaviorCollection;
}
/// <exception cref="T:System.InvalidOperationException">Cannot host the same BehaviorCollection on more than one object at a time.</exception>
private static void OnBehaviorsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
BehaviorCollection behaviorCollection1 = args.OldValue as BehaviorCollection;
BehaviorCollection behaviorCollection2 = args.NewValue as BehaviorCollection;
//no change
if (behaviorCollection1 == behaviorCollection2)
{
return;
}
//unload previous collection
if (behaviorCollection1 != null && behaviorCollection1.AssociatedObject != null)
{
behaviorCollection1.Detach();
}
//no new collection
if (behaviorCollection2 == null || obj == null)
{
return;
}
if (behaviorCollection2.AssociatedObject != null)
{
throw new InvalidOperationException("Cannot Host BehaviorCollection Multiple Times");
}
FrameworkElement fElement = obj as FrameworkElement;
if (fElement == null)
{
throw new InvalidOperationException("Can only host BehaviorCollection on FrameworkElement");
}
behaviorCollection2.Attach(fElement);
}
/// <exception cref="T:System.InvalidOperationException">Cannot host the same TriggerCollection on more than one object at a time.</exception>
private static void OnTriggersChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
TriggerCollection triggerCollection1 = args.OldValue as TriggerCollection;
TriggerCollection triggerCollection2 = args.NewValue as TriggerCollection;
if (triggerCollection1 == triggerCollection2)
{
return;
}
if (triggerCollection1 != null && triggerCollection1.AssociatedObject != null)
{
triggerCollection1.Detach();
}
if (triggerCollection2 == null || obj == null)
{
return;
}
if (triggerCollection2.AssociatedObject != null)
{
throw new InvalidOperationException("Cannot Host TriggerCollection Multiple Times");
}
FrameworkElement fElement = obj as FrameworkElement;
if (fElement == null)
{
throw new InvalidOperationException("Can only host BehaviorCollection on FrameworkElement");
}
triggerCollection2.Attach(fElement);
}
/// <summary>
/// A helper function to take the place of FrameworkElement.IsLoaded, as this property is not available in Silverlight.
///
/// </summary>
/// <param name="element">The element of interest.</param>
/// <returns>
/// True if the element has been loaded; otherwise, False.
/// </returns>
internal static bool IsElementLoaded(FrameworkElement element)
{
UIElement rootVisual = Window.Current.Content;
if ((element.Parent ?? VisualTreeHelper.GetParent(element)) != null)
{
return true;
}
if (rootVisual != null)
{
return element == rootVisual;
}
else
{
return false;
}
}
}
}
| 43.738562 | 256 | 0.6185 | [
"MIT"
] | jlaanstra/Windows.UI.Interactivity | Windows.UI.Interactivity/Interaction.cs | 6,694 | C# |
using Dapper;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using Common.Extend;
using Common;
using System.Collections.Generic;
using DbOpertion.Models;
namespace DbOpertion.DBoperation
{
public partial class noRestaurantOper : SingleTon<noRestaurantOper>
{
public string ConnString=ConfigurationManager.AppSettings["ConnString"].ToString();
/// <summary>
/// 插入
/// </summary>
/// <param name="norestaurant"></param>
/// <returns>是否成功</returns>
public bool Insert(noRestaurant norestaurant)
{
StringBuilder sql = new StringBuilder("insert into noRestaurant ");
StringBuilder part1 = new StringBuilder();
StringBuilder part2 = new StringBuilder();
var parm = new DynamicParameters();
bool flag = true;
if(!norestaurant.location.IsNullOrEmpty())
{
if (flag)
{
part1.Append("location");
part2.Append("@location");
flag = false;
}
else
{
part1.Append(",location");
part2.Append(",@location");
}
parm.Add("location", norestaurant.location);
}
if(!norestaurant.times.IsNullOrEmpty())
{
if (flag)
{
part1.Append("times");
part2.Append("@times");
flag = false;
}
else
{
part1.Append(",times");
part2.Append(",@times");
}
parm.Add("times", norestaurant.times);
}
sql.Append("(").Append(part1).Append(") values(").Append(part2).Append(")");
using (var conn = new SqlConnection(ConnString))
{
conn.Open();
var r = conn.Execute(sql.ToString(), parm);
conn.Close();
return r > 0;
}
}
/// <summary>
/// 删除
/// </summary>
/// <param name="Id"></param>
/// <returns>是否成功</returns>
public bool Delete(int id)
{
object parm = new { id = id };
using (var conn = new SqlConnection(ConnString))
{
conn.Open();
var r = conn.Execute(@"Delete From noRestaurant where id=@id",parm);
conn.Close();
return r > 0;
}
}
/// <summary>
/// 更新
/// </summary>
/// <param name="norestaurant"></param>
/// <returns>是否成功</returns>
public bool Update(noRestaurant norestaurant)
{
StringBuilder sql = new StringBuilder("update noRestaurant set ");
StringBuilder part1 = new StringBuilder();
StringBuilder part2 = new StringBuilder();
var parm = new DynamicParameters();
bool flag = true;
if(!norestaurant.id.IsNullOrEmpty())
{
part2.Append("id = @id");
parm.Add("id", norestaurant.id);
}
if(!norestaurant.location.IsNullOrEmpty())
{
if (flag)
{
part1.Append("location = @location");
flag = false;
}
else
{
part1.Append(", location = @location");
}
parm.Add("location", norestaurant.location);
}
if(!norestaurant.times.IsNullOrEmpty())
{
if (flag)
{
part1.Append("times = @times");
flag = false;
}
else
{
part1.Append(", times = @times");
}
parm.Add("times", norestaurant.times);
}
sql.Append(part1).Append(" where ").Append(part2);
using (var conn = new SqlConnection(ConnString))
{
conn.Open();
var r = conn.Execute(sql.ToString(), parm);
conn.Close();
return r > 0;
}
}
/// <summary>
/// 查询
/// </summary>
/// <param name="norestaurant"></param>
/// <returns>对象列表</returns>
public List<noRestaurant> Select(noRestaurant norestaurant)
{
StringBuilder sql = new StringBuilder("Select ");
if(!norestaurant.Field.IsNullOrEmpty())
{
sql.Append(norestaurant.Field);
}
else
{
sql.Append("*");
}
sql.Append(" from noRestaurant ");
StringBuilder part1 = new StringBuilder();
var parm = new DynamicParameters();
bool flag = true;
if(!norestaurant.id.IsNullOrEmpty())
{
if (flag)
{
part1.Append("id = @id");
flag = false;
}
else
{
part1.Append(" and id = @id");
}
parm.Add("id", norestaurant.id);
}
if(!norestaurant.location.IsNullOrEmpty())
{
if (flag)
{
part1.Append("location = @location");
flag = false;
}
else
{
part1.Append(" and location = @location");
}
parm.Add("location", norestaurant.location);
}
if(!norestaurant.times.IsNullOrEmpty())
{
if (flag)
{
part1.Append("times = @times");
flag = false;
}
else
{
part1.Append(" and times = @times");
}
parm.Add("times", norestaurant.times);
}
if(!norestaurant.GroupBy.IsNullOrEmpty())
{
part1.Append(" Group By ").Append(norestaurant.GroupBy).Append(" ");
flag = false;
}
if(!norestaurant.OrderBy.IsNullOrEmpty())
{
part1.Append(" Order By ").Append(norestaurant.OrderBy).Append(" ");
flag = false;
}
if (!flag)
{
sql.Append(" where ");
}
sql.Append(part1);
using (var conn = new SqlConnection(ConnString))
{
conn.Open();
var r = (List<noRestaurant>)conn.Query<noRestaurant>(sql.ToString(), parm);
conn.Close();
if(r == null)
{
r = new List<noRestaurant>();
}
return r;
}
}
/// <summary>
/// 分页查询
/// </summary>
/// <param name="norestaurant"></param>
/// <param name="pageSize">页面大小</param>
/// <param name="pageNo">页面编号</param>
/// <returns>对象列表</returns>
public List<noRestaurant> SelectByPage(noRestaurant norestaurant,int pageSize,int pageNo)
{
StringBuilder sql = new StringBuilder("Select Top ").Append(pageSize).Append(" ");
if(!norestaurant.Field.IsNullOrEmpty())
{
sql.Append(norestaurant.Field);
}
else
{
sql.Append("*");
}
sql.Append(" from noRestaurant ");
StringBuilder part1 = new StringBuilder();
StringBuilder part2 = new StringBuilder();
StringBuilder strBuliderPage = new StringBuilder();
var parm = new DynamicParameters();
bool flag = true;
if(!norestaurant.id.IsNullOrEmpty())
{
if (flag)
{
part1.Append("id = @id");
flag = false;
}
else
{
part1.Append(" and id = @id");
}
parm.Add("id", norestaurant.id);
}
if(!norestaurant.location.IsNullOrEmpty())
{
if (flag)
{
part1.Append("location = @location");
flag = false;
}
else
{
part1.Append(" and location = @location");
}
parm.Add("location", norestaurant.location);
}
if(!norestaurant.times.IsNullOrEmpty())
{
if (flag)
{
part1.Append("times = @times");
flag = false;
}
else
{
part1.Append(" and times = @times");
}
parm.Add("times", norestaurant.times);
}
if(!flag)
{
strBuliderPage.Append(" and");
}strBuliderPage.Append(" id not in (").Append("Select Top ").Append(pageSize * (pageNo - 1)).Append(" id from noRestaurant ");
if(!norestaurant.GroupBy.IsNullOrEmpty())
{
strBuliderPage.Append(" Group By ").Append(norestaurant.GroupBy).Append(" ");
flag = false;
}
if(!norestaurant.OrderBy.IsNullOrEmpty())
{
strBuliderPage.Append(" Order By ").Append(norestaurant.OrderBy).Append(" ");
flag = false;
}
strBuliderPage.Append(" )");
if (!flag)
{
sql.Append(" where ");
}
sql.Append(part1).Append(strBuliderPage).Append(part1);
if(!norestaurant.GroupBy.IsNullOrEmpty())
{
part2.Append(" Group By ").Append(norestaurant.GroupBy).Append(" ");
}
if(!norestaurant.OrderBy.IsNullOrEmpty())
{
part2.Append(" Order By ").Append(norestaurant.OrderBy).Append(" ");
}
sql.Append(part2);
using (var conn = new SqlConnection(ConnString))
{
conn.Open();
var r = (List<noRestaurant>)conn.Query<noRestaurant>(sql.ToString(), parm);
conn.Close();
if(r == null)
{
r = new List<noRestaurant>();
}
return r;
}
}
/// <summary>
/// 根据Id查询
/// </summary>
/// <param name="Id"></param>
/// <returns>是否成功</returns>
public List<noRestaurant> SelectByIds(List<string> List_Id)
{
object parm = new { id = List_Id.ToArray() };
using (var conn = new SqlConnection(ConnString))
{
conn.Open();
var r = (List<noRestaurant>)conn.Query<noRestaurant>("Select * From noRestaurant where id in @id", parm);
conn.Close();
if(r == null)
{
r = new List<noRestaurant>();
}
return r;
}
}
}
}
| 32.602857 | 134 | 0.429673 | [
"MIT"
] | wustrom/WebApi_Health | DbOpertion/Opertion/noRestaurantOper.cs | 11,507 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2015 Ingo Herbote
* http://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Controls
{
#region Using
using System;
using System.Data;
using System.Web.UI;
using YAF.Classes.Data;
using YAF.Core;
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.Extensions;
using YAF.Types.Interfaces;
using YAF.Utils;
#endregion
/// <summary>
/// Shows a Reporters for reported posts
/// </summary>
public class BaseReportedPosts : BaseUserControl
{
#region Properties
/// <summary>
/// Gets or sets MessageID.
/// </summary>
public virtual int MessageID
{
get
{
return this.ViewState["MessageID"] != null ? this.ViewState["MessageID"].ToType<int>() : 0;
}
set
{
this.ViewState["MessageID"] = value;
}
}
/// <summary>
/// Gets or sets Resolved.
/// </summary>
[NotNull]
public virtual string Resolved
{
get
{
return this.ViewState["Resolved"].ToString();
}
set
{
this.ViewState["Resolved"] = value;
}
}
/// <summary>
/// Gets or sets ResolvedBy. It returns UserID as string value
/// </summary>
[NotNull]
public virtual string ResolvedBy
{
get
{
return this.ViewState["ResolvedBy"].ToString();
}
set
{
this.ViewState["ResolvedBy"] = value;
}
}
/// <summary>
/// Gets or sets ResolvedDate.
/// </summary>
[NotNull]
public virtual string ResolvedDate
{
get
{
return this.ViewState["ResolvedDate"].ToString();
}
set
{
this.ViewState["ResolvedDate"] = value;
}
}
#endregion
#region Methods
/// <summary>
/// The render.
/// </summary>
/// <param name="writer">
/// The writer.
/// </param>
protected override void Render([NotNull] HtmlTextWriter writer)
{
// TODO: Needs better commentting.
writer.WriteLine(@"<div id=""{0}"" class=""yafReportedPosts"">".FormatWith(this.ClientID));
DataTable reportersList = LegacyDb.message_listreporters(this.MessageID);
if (reportersList.Rows.Count <= 0)
{
return;
}
int i = 0;
writer.BeginRender();
foreach (DataRow reporter in reportersList.Rows)
{
string howMany = null;
if (reporter["ReportedNumber"].ToType<int>() > 1)
{
howMany = "({0})".FormatWith(reporter["ReportedNumber"]);
}
writer.WriteLine(
@"<table cellspacing=""0"" cellpadding=""0"" class=""content"" id=""yafreportedtable{0}"" style=""width:100%"">", this.ClientID);
// If the message was previously resolved we have not null string
// and can add an info about last user who resolved the message
if (!string.IsNullOrEmpty(this.ResolvedDate))
{
string resolvedByName =
LegacyDb.user_list(this.PageContext.PageBoardID, this.ResolvedBy.ToType<int>(), true).Rows[0]["Name"].ToString();
var resolvedByDisplayName =
UserMembershipHelper.GetDisplayNameFromID(this.ResolvedBy.ToType<long>()).IsSet()
? this.Server.HtmlEncode(this.Get<IUserDisplayName>().GetName(this.ResolvedBy.ToType<int>()))
: this.Server.HtmlEncode(resolvedByName);
writer.Write(@"<tr class=""header2""><td>");
writer.Write(
@"<span class=""postheader"">{0}</span><a class=""YafReported_Link"" href=""{1}""> {2}</a><span class=""YafReported_ResolvedBy""> : {3}</span>",
this.GetText("RESOLVEDBY"),
YafBuildLink.GetLink(ForumPages.profile, "u={0}&name={1}", this.ResolvedBy.ToType<int>(), resolvedByDisplayName),
resolvedByDisplayName,
this.Get<IDateTime>().FormatDateTimeTopic(this.ResolvedDate));
writer.WriteLine(@"</td></tr>");
}
writer.Write(@"<tr class=""header2""><td>");
writer.Write(
@"<span class=""YafReported_Complainer"">{3}</span><a class=""YafReported_Link"" href=""{1}""> {0}{2} </a>",
!string.IsNullOrEmpty(UserMembershipHelper.GetDisplayNameFromID(reporter["UserID"].ToType<long>()))
? this.Server.HtmlEncode(this.Get<IUserDisplayName>().GetName(reporter["UserID"].ToType<int>()))
: this.Server.HtmlEncode(reporter["UserName"].ToString()),
YafBuildLink.GetLink(ForumPages.profile, "u={0}&name={1}", reporter["UserID"].ToType<int>(), reporter["UserName"].ToString()),
howMany,
this.GetText("REPORTEDBY"));
writer.WriteLine(@"</td></tr>");
string[] reportString = reporter["ReportText"].ToString().Trim().Split('|');
foreach (string t in reportString)
{
string[] textString = t.Split("??".ToCharArray());
writer.Write(@"<tr class=""post""><td>");
writer.Write(
@"<span class=""YafReported_DateTime"">{0}:</span>",
this.Get<IDateTime>().FormatDateTimeTopic(textString[0]));
// Apply style if a post was previously resolved
string resStyle = "post_res";
try
{
if (!(string.IsNullOrEmpty(textString[0]) && string.IsNullOrEmpty(this.ResolvedDate)))
{
if (Convert.ToDateTime(textString[0]) < Convert.ToDateTime(this.ResolvedDate))
{
resStyle = "post";
}
}
}
catch (Exception)
{
resStyle = "post_res";
}
if (textString.Length > 2)
{
writer.Write(@"<tr><td class=""{0}"">", resStyle);
writer.Write(textString[2]);
writer.WriteLine(@"</td></tr>");
}
else
{
writer.WriteLine(@"<tr class=""post""><td>");
writer.Write(t);
writer.WriteLine(@"</td></tr>");
}
}
writer.WriteLine(@"<tr class=""postfooter""><td>");
writer.Write(
@"<a class=""YafReported_Link"" href=""{1}"">{2} {0}</a>",
!string.IsNullOrEmpty(UserMembershipHelper.GetDisplayNameFromID(reporter["UserID"].ToType<long>()))
? this.Server.HtmlEncode(this.Get<IUserDisplayName>().GetName(reporter["UserID"].ToType<int>()))
: this.Server.HtmlEncode(reporter["UserName"].ToString()),
YafBuildLink.GetLink(
ForumPages.pmessage, "u={0}&r={1}", reporter["UserID"].ToType<int>(), this.MessageID),
this.GetText("REPLYTO"));
writer.WriteLine(@"</td></tr>");
// TODO: Remove hard-coded formatting.
if (i < reportersList.Rows.Count - 1)
{
writer.Write("</table></br>");
}
else
{
writer.WriteLine(@"</td></tr>");
}
i++;
}
// render controls...
writer.Write(@"</table>");
base.Render(writer);
writer.WriteLine("</div>");
writer.EndRender();
}
#endregion
}
} | 34.065134 | 166 | 0.520301 | [
"Apache-2.0"
] | TristanTong/bbsWirelessTag | yafsrc/YAF.Controls/BaseReportedPosts.cs | 8,632 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ------------------------------------------------------------------------------
// Changes to this file must follow the https://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Security.Cryptography
{
public sealed class DSAOpenSsl : System.Security.Cryptography.DSA
{
public DSAOpenSsl() { }
public DSAOpenSsl(int keySize) { }
public DSAOpenSsl(System.IntPtr handle) { }
public DSAOpenSsl(System.Security.Cryptography.DSAParameters parameters) { }
public DSAOpenSsl(System.Security.Cryptography.SafeEvpPKeyHandle pkeyHandle) { }
public override int KeySize { set { } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public override byte[] CreateSignature(byte[] rgbHash) { throw null; }
protected override void Dispose(bool disposing) { }
public System.Security.Cryptography.SafeEvpPKeyHandle DuplicateKeyHandle() { throw null; }
public override System.Security.Cryptography.DSAParameters ExportParameters(bool includePrivateParameters) { throw null; }
protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public override void ImportParameters(System.Security.Cryptography.DSAParameters parameters) { }
public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; }
}
public sealed class ECDiffieHellmanOpenSsl : System.Security.Cryptography.ECDiffieHellman
{
public ECDiffieHellmanOpenSsl() { }
public ECDiffieHellmanOpenSsl(int keySize) { }
public ECDiffieHellmanOpenSsl(System.IntPtr handle) { }
public ECDiffieHellmanOpenSsl(System.Security.Cryptography.ECCurve curve) { }
public ECDiffieHellmanOpenSsl(System.Security.Cryptography.SafeEvpPKeyHandle pkeyHandle) { }
public override System.Security.Cryptography.ECDiffieHellmanPublicKey PublicKey { get { throw null; } }
public override byte[] DeriveKeyFromHash(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[]? secretPrepend, byte[]? secretAppend) { throw null; }
public override byte[] DeriveKeyFromHmac(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[]? hmacKey, byte[]? secretPrepend, byte[]? secretAppend) { throw null; }
public override byte[] DeriveKeyMaterial(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey) { throw null; }
public override byte[] DeriveKeyTls(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed) { throw null; }
public System.Security.Cryptography.SafeEvpPKeyHandle DuplicateKeyHandle() { throw null; }
public override System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; }
public override System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; }
public override void GenerateKey(System.Security.Cryptography.ECCurve curve) { }
public override void ImportParameters(System.Security.Cryptography.ECParameters parameters) { }
}
public sealed class ECDsaOpenSsl : System.Security.Cryptography.ECDsa
{
public ECDsaOpenSsl() { }
public ECDsaOpenSsl(int keySize) { }
public ECDsaOpenSsl(System.IntPtr handle) { }
public ECDsaOpenSsl(System.Security.Cryptography.ECCurve curve) { }
public ECDsaOpenSsl(System.Security.Cryptography.SafeEvpPKeyHandle pkeyHandle) { }
public override int KeySize { get { throw null; } set { } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
protected override void Dispose(bool disposing) { }
public System.Security.Cryptography.SafeEvpPKeyHandle DuplicateKeyHandle() { throw null; }
public override System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; }
public override System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; }
public override void GenerateKey(System.Security.Cryptography.ECCurve curve) { }
protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public override void ImportParameters(System.Security.Cryptography.ECParameters parameters) { }
public override byte[] SignHash(byte[] hash) { throw null; }
public override bool VerifyHash(byte[] hash, byte[] signature) { throw null; }
}
public sealed class RSAOpenSsl : System.Security.Cryptography.RSA
{
public RSAOpenSsl() { }
public RSAOpenSsl(int keySize) { }
public RSAOpenSsl(System.IntPtr handle) { }
public RSAOpenSsl(System.Security.Cryptography.RSAParameters parameters) { }
public RSAOpenSsl(System.Security.Cryptography.SafeEvpPKeyHandle pkeyHandle) { }
public override int KeySize { set { } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public override byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; }
protected override void Dispose(bool disposing) { }
public System.Security.Cryptography.SafeEvpPKeyHandle DuplicateKeyHandle() { throw null; }
public override byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; }
public override System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters) { throw null; }
protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public override void ImportParameters(System.Security.Cryptography.RSAParameters parameters) { }
public override byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public override bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
}
public sealed class SafeEvpPKeyHandle : System.Runtime.InteropServices.SafeHandle
{
public SafeEvpPKeyHandle() : base (default(System.IntPtr), default(bool)) { }
public SafeEvpPKeyHandle(System.IntPtr handle, bool ownsHandle) : base (default(System.IntPtr), default(bool)) { }
public static long OpenSslVersion { get { throw null; } }
public override bool IsInvalid { get { throw null; } }
public System.Security.Cryptography.SafeEvpPKeyHandle DuplicateHandle() { throw null; }
protected override bool ReleaseHandle() { throw null; }
}
}
| 82.957895 | 263 | 0.732014 | [
"MIT"
] | 333fred/runtime | src/libraries/System.Security.Cryptography.OpenSsl/ref/System.Security.Cryptography.OpenSsl.cs | 7,881 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Fluid;
using Fluid.Values;
using Newtonsoft.Json;
using Squidex.Text;
namespace Squidex.Domain.Apps.Core.Templates.Extensions
{
public sealed class StringFluidExtension : IFluidExtension
{
private static readonly FilterDelegate Slugify = (input, arguments, context) =>
{
if (input is StringValue value)
{
var result = value.ToStringValue().Slugify();
return FluidValue.Create(result);
}
return input;
};
private static readonly FilterDelegate Escape = (input, arguments, context) =>
{
var result = input.ToStringValue();
result = JsonConvert.ToString(result);
result = result[1..^1];
return FluidValue.Create(result);
};
private static readonly FilterDelegate Markdown2Text = (input, arguments, context) =>
{
return FluidValue.Create(TextHelpers.Markdown2Text(input.ToStringValue()));
};
private static readonly FilterDelegate Html2Text = (input, arguments, context) =>
{
return FluidValue.Create(TextHelpers.Html2Text(input.ToStringValue()));
};
private static readonly FilterDelegate Trim = (input, arguments, context) =>
{
return FluidValue.Create(input.ToStringValue().Trim());
};
public void RegisterGlobalTypes(IMemberAccessStrategy memberAccessStrategy)
{
TemplateContext.GlobalFilters.AddFilter("html2text", Html2Text);
TemplateContext.GlobalFilters.AddFilter("markdown2text", Markdown2Text);
TemplateContext.GlobalFilters.AddFilter("escape", Escape);
TemplateContext.GlobalFilters.AddFilter("slugify", Slugify);
TemplateContext.GlobalFilters.AddFilter("trim", Trim);
}
}
}
| 35.109375 | 93 | 0.569203 | [
"MIT"
] | EdoardoTona/squidex | backend/src/Squidex.Domain.Apps.Core.Operations/Templates/Extensions/StringFluidExtension.cs | 2,249 | C# |
using System.Collections.Generic;
namespace Furion.Extras.Admin.NET.Service
{
/// <summary>
/// 员工信息参数2
/// </summary>
public class EmpOutput2
{
/// <summary>
/// 员工Id
/// </summary>
public string Id { get; set; }
/// <summary>
/// 工号
/// </summary>
public string JobNum { get; set; }
/// <summary>
/// 机构Id
/// </summary>
public string OrgId { get; set; }
/// <summary>
/// 机构名称
/// </summary>
public string OrgName { get; set; }
/// <summary>
/// 附属机构
/// </summary>
public List<EmpExtOrgPosOutput> ExtIds { get; set; } = new List<EmpExtOrgPosOutput>();
/// <summary>
/// 职位集合
/// </summary>
public List<long> PosIdList { get; set; } = new List<long>();
}
} | 22.05 | 94 | 0.464853 | [
"Apache-2.0"
] | 364988343/AKStreamUI | backend/Furion.Extras.Admin.NET/Service/Emp/Dto/EmpOutput2.cs | 932 | C# |
// <copyright file="DriverServiceCommandExecutor.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// Provides a mechanism to execute commands on the browser
/// </summary>
public class DriverServiceCommandExecutor : ICommandExecutor
{
private DriverService service;
private HttpCommandExecutor internalExecutor;
private bool isDisposed;
/// <summary>
/// Initializes a new instance of the <see cref="DriverServiceCommandExecutor"/> class.
/// </summary>
/// <param name="driverService">The <see cref="DriverService"/> that drives the browser.</param>
/// <param name="commandTimeout">The maximum amount of time to wait for each command.</param>
public DriverServiceCommandExecutor(DriverService driverService, TimeSpan commandTimeout)
: this(driverService, commandTimeout, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DriverServiceCommandExecutor"/> class.
/// </summary>
/// <param name="driverService">The <see cref="DriverService"/> that drives the browser.</param>
/// <param name="commandTimeout">The maximum amount of time to wait for each command.</param>
/// <param name="enableKeepAlive"><see langword="true"/> if the KeepAlive header should be sent
/// with HTTP requests; otherwise, <see langword="false"/>.</param>
public DriverServiceCommandExecutor(DriverService driverService, TimeSpan commandTimeout, bool enableKeepAlive)
{
this.service = driverService;
this.internalExecutor = new HttpCommandExecutor(driverService.ServiceUrl, commandTimeout, enableKeepAlive);
}
/// <summary>
/// Initializes a new instance of the <see cref="DriverServiceCommandExecutor"/> class.
/// </summary>
/// <param name="service">The <see cref="DriverService"/> that drives the browser.</param>
/// <param name="commandExecutor">The <see cref="HttpCommandExecutor"/> object used to execute commands,
/// communicating with the service via HTTP.</param>
public DriverServiceCommandExecutor(DriverService service, HttpCommandExecutor commandExecutor)
{
this.service = service;
this.internalExecutor = commandExecutor;
}
/// <summary>
/// Gets the <see cref="CommandInfoRepository"/> object associated with this executor.
/// </summary>
//public CommandInfoRepository CommandInfoRepository
//{
// get { return this.internalExecutor.CommandInfoRepository; }
//}
public bool TryAddCommand(string commandName, CommandInfo info)
{
return this.internalExecutor.TryAddCommand(commandName, info);
}
/// <summary>
/// Gets the <see cref="HttpCommandExecutor"/> that sends commands to the remote
/// end WebDriver implementation.
/// </summary>
public HttpCommandExecutor HttpExecutor
{
get { return this.internalExecutor; }
}
/// <summary>
/// Executes a command
/// </summary>
/// <param name="commandToExecute">The command you wish to execute</param>
/// <returns>A response from the browser</returns>
public Response Execute(Command commandToExecute)
{
if (commandToExecute == null)
{
throw new ArgumentNullException("commandToExecute", "Command to execute cannot be null");
}
Response toReturn = null;
if (commandToExecute.Name == DriverCommand.NewSession)
{
this.service.Start();
}
// Use a try-catch block to catch exceptions for the Quit
// command, so that we can get the finally block.
try
{
toReturn = this.internalExecutor.Execute(commandToExecute);
}
finally
{
if (commandToExecute.Name == DriverCommand.Quit)
{
this.Dispose();
}
}
return toReturn;
}
/// <summary>
/// Releases all resources used by the <see cref="DriverServiceCommandExecutor"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="HttpCommandExecutor"/> and
/// optionally releases the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release managed and resources;
/// <see langword="false"/> to only release unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (disposing)
{
this.service.Dispose();
}
this.isDisposed = true;
}
}
}
}
| 39.421053 | 119 | 0.614653 | [
"Apache-2.0"
] | Abdulwahed-alhallak/selenium | dotnet/src/webdriver/Remote/DriverServiceCommandExecutor.cs | 5,992 | C# |
using System.Collections;
using UtilityWpf.Events;
namespace UtilityWpf.Abstract
{
public interface ICheckedSelector
{
IEnumerable CheckedItems { get; }
IEnumerable UnCheckedItems { get; }
event CheckedChangedEventHandler CheckedChanged;
}
} | 21.538462 | 56 | 0.714286 | [
"MIT"
] | dtaylor-530/UtilityWpfCore | UtilityWpf/Abstract/ICheckedSelector.cs | 282 | C# |
using AOFL.KrakenIoc.Core.V1.Interfaces;
using UnityEngine;
namespace AOFL.KrakenIoc.Extensions.V1
{
public static class GameObjectExtensions
{
/// <summary>
/// Adds a component and injects via the container.
/// </summary>
/// <returns>The component.</returns>
/// <param name="gameObject">Game object.</param>
/// <param name="container">Container.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public static T AddComponent<T>(this GameObject gameObject, IContainer container)
{
return container.Resolve<T>(gameObject);
}
}
} | 32.75 | 89 | 0.625954 | [
"MIT"
] | 2kCarlos/kraken-ioc | KrakenIoc/KrakenIoc.Unity/Extensions/V1/GameObjectExtensions.cs | 655 | C# |
using System;
using System.Web;
namespace ServiceStack.MiniProfiler
{
public enum RenderPosition
{
Left = 0,
Right = 1
}
public interface IProfiler
{
IProfiler Start();
void Stop();
IDisposable Step(string name);
IHtmlString RenderIncludes(RenderPosition? position = null, bool? showTrivial = null,
bool? showTimeWithChildren = null, int? maxTracesToShow = null, bool xhtml = false,
bool? showControls = null);
}
public class NullProfiler : IProfiler
{
public static readonly NullProfiler Instance = new NullProfiler();
readonly MockDisposable disposable = new MockDisposable();
class MockDisposable : IDisposable
{
public void Dispose() { }
}
public IProfiler Start() => this;
public void Stop() { }
public IDisposable Step(string name) => disposable;
public IHtmlString RenderIncludes(RenderPosition? position = null, bool? showTrivial = null,
bool? showTimeWithChildren = null,
int? maxTracesToShow = null, bool xhtml = false, bool? showControls = null)
{
return HtmlString.Empty;
}
}
public static class Profiler
{
public static IProfiler Current { get; set; } = NullProfiler.Instance;
public static IDisposable Step(string name) => Current.Step(name);
public static IHtmlString RenderIncludes(RenderPosition? position = null, bool? showTrivial = null,
bool? showTimeWithChildren = null,
int? maxTracesToShow = null, bool xhtml = false, bool? showControls = null)
{
return Current.RenderIncludes(position, showTrivial, showTimeWithChildren, maxTracesToShow, xhtml,
showControls);
}
public static IProfiler Start() => Current.Start();
public static void Stop() => Current.Stop();
}
public class HtmlString : IHtmlString, System.Web.IHtmlString
{
public static HtmlString Empty = new HtmlString(string.Empty);
private readonly string value;
public HtmlString(string value)
{
this.value = value;
}
public override string ToString()
{
return value;
}
public string ToHtmlString()
{
return this.ToString();
}
}
}
namespace ServiceStack.Html
{
public static class HtmlStringExtensions
{
public static System.Web.IHtmlString AsRaw(this IHtmlString htmlString) => htmlString is System.Web.IHtmlString aspRawStr
? aspRawStr
: new HtmlString(htmlString?.ToHtmlString() ?? "");
}
} | 29.510417 | 130 | 0.594776 | [
"Apache-2.0"
] | sbosell/ServiceStack | src/ServiceStack/Profiler.cs | 2,740 | C# |
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using Microsoft.Xna.Framework.Graphics;
namespace Microsoft.Xna.Framework.Content.Pipeline.Graphics
{
public class PvrtcRgba4BitmapContent : PvrtcBitmapContent
{
/// <summary>
/// Creates an instance of PvrtcRgba4BitBitmapContent with the specified width and height.
/// </summary>
/// <param name="width">The width in pixels of the bitmap.</param>
/// <param name="height">The height in pixels of the bitmap.</param>
public PvrtcRgba4BitmapContent(int width, int height)
: base(width, height)
{
}
/// <summary>
/// Gets the corresponding GPU texture format for the specified bitmap type.
/// </summary>
/// <param name="format">Format being retrieved.</param>
/// <returns>The GPU texture format of the bitmap type.</returns>
public override bool TryGetFormat(out SurfaceFormat format)
{
format = SurfaceFormat.RgbaPvrtc4Bpp;
return true;
}
/// <summary>
/// Returns a string description of the bitmap.
/// </summary>
/// <returns>Description of the bitmap.</returns>
public override string ToString()
{
return "PVRTC RGBA 4bpp " + Width + "x" + Height;
}
}
}
| 35.333333 | 98 | 0.616577 | [
"MIT"
] | Gitspathe/MonoGame | MonoGame.Framework.Content.Pipeline/Graphics/PvrtcRgba4BitmapContent.cs | 1,484 | C# |
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Protocols;
using Newtonsoft.Json;
namespace THNETII.AzureAcs.Client.Metadata
{
public class AcsInstanceMetadataRetriever
: IConfigurationRetriever<AcsInstanceMetadata>
{
public static Task<AcsInstanceMetadata>
GetAsync(string address, CancellationToken cancelToken = default) =>
GetAsync(address,
new HttpDocumentRetriever(),
cancelToken);
public static Task<AcsInstanceMetadata>
GetAsync(string address, HttpClient httpClient,
CancellationToken cancelToken = default) =>
GetAsync(address,
new HttpDocumentRetriever(httpClient ??
throw LogHelper.LogArgumentNullException(nameof(httpClient))),
cancelToken);
public static async Task<AcsInstanceMetadata>
GetAsync(string address, IDocumentRetriever documentRetriever,
CancellationToken cancelToken = default)
{
if (string.IsNullOrEmpty(address))
throw LogHelper.LogArgumentNullException(nameof(address));
if (documentRetriever is null)
throw LogHelper.LogArgumentNullException(nameof(documentRetriever));
string metadataJson = await documentRetriever
.GetDocumentAsync(address, cancelToken)
.ConfigureAwait(continueOnCapturedContext: false);
LogHelper.LogVerbose(LogMessages.ACS2001, metadataJson);
return JsonConvert.DeserializeObject<AcsInstanceMetadata>(metadataJson);
}
Task<AcsInstanceMetadata> IConfigurationRetriever<AcsInstanceMetadata>
.GetConfigurationAsync(string address,
IDocumentRetriever retriever,
CancellationToken cancelToken) =>
GetAsync(address, retriever, cancelToken);
}
}
| 38.846154 | 84 | 0.670297 | [
"MIT"
] | thnetii/azure-extensions | src/THNETII.AzureAcs.Client/Metadata/AcsInstanceMetadataRetriever.cs | 2,020 | C# |
using System.Collections.Generic;
using TestCreator.Data.Models.DTO;
using TestCreator.WebApp.ViewModels;
namespace TestCreator.WebApp.Converters.ViewModel.Interfaces
{
public interface IResultViewModelConverter
{
ResultViewModel Convert(Result result);
IEnumerable<ResultViewModel> Convert(IEnumerable<Result> results);
}
}
| 27.307692 | 74 | 0.777465 | [
"MIT"
] | PDanowski/TestCreator_React | TestCreator/TestCreator.WebApp/Converters/ViewModel/Interfaces/IResultViewModelConverter.cs | 357 | C# |
// Copyright (c) 2020, UW Medicine Research IT, University of Washington
// Developed by Nic Dobbins and Cliff Spital, CRIO Sean Mooney
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.Collections.Generic;
namespace Model.Compiler.Common
{
static class Dialect
{
public static class Field
{
public const string MinDate = "MinDate";
public const string MaxDate = "MaxDate";
}
public static class Alias
{
public const string Person = "_S";
public const string Sequence = "_T";
}
public static class Time
{
public const string SECOND = "SECOND";
public const string MINUTE = "MINUTE";
public const string HOUR = "HOUR";
public const string DAY = "DAY";
public const string WEEK = "WEEK";
public const string MONTH = "MONTH";
public const string YEAR = "YEAR";
}
public static class Syntax
{
public const string SELECT = "SELECT";
public const string FROM = "FROM";
public const string WHERE = "WHERE";
public const string GROUP_BY = "GROUP BY";
public const string HAVING = "HAVING";
public const string ORDER_BY = "ORDER BY";
public const string COUNT = "COUNT";
public const string AND = "AND";
public const string NOT = "NOT";
public const string MIN = "MIN";
public const string MAX = "MAX";
public const string IN = "IN";
public const string AS = "AS";
public const string UNION_ALL = "UNION ALL";
public const string BETWEEN = "BETWEEN";
public const string SINGLE_QUOTE = "'";
public const string WILDCARD = "%";
public const string LIKE = "LIKE";
public const string OR = "OR";
public const string LEFT_JOIN = "LEFT JOIN";
public const string INNER_JOIN = "INNER JOIN ";
public const string ON = "ON";
public const string DATEADD = "DATEADD";
public const string IS_NULL = "IS NULL";
public const string EXISTS = "EXISTS";
public const string NOW = "GETDATE()";
public const string INTERSECT = "INTERSECT";
public const string EXCEPT = "EXCEPT";
public const string DISTINCT = "DISTINCT";
public const string DECLARE = "DECLARE";
}
public static class Types
{
public const string BIT = "BIT";
public const string NVARCHAR = "NVARCHAR";
}
public static readonly string[] IllegalCommands = { "UPDATE ", "TRUNCATE ", "EXEC ", "DROP ", "INSERT ", "CREATE ", "DELETE ", "MERGE ", "SET " };
public static readonly HashSet<string> DateFilterTypes = new HashSet<string> { "MINUTE", "HOUR", "DAY", "WEEK", "MONTH", "YEAR" };
}
}
| 39.222222 | 154 | 0.570979 | [
"MPL-2.0"
] | UChicagoCRI/leaf | src/server/Model/Compiler/Common/Dialect.cs | 3,179 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Gabarito
{
public partial class Resultado : Form
{
public Resultado()
{
InitializeComponent();
}
int acertos = 0;
int numero = Iniciar.qArray.Length;
double aproveitamento;
int[] nQuest = new int[Iniciar.qArray.Length];
string[] correta = new string[Iniciar.qArray.Length];
private void Resultado_Load(object sender, EventArgs e)
{
//string output = string.Join(", ", Iniciar.qArray);
//MessageBox.Show(output);
for (int i = 0; i < Iniciar.qArray.Length; i++)
{
//if (Iniciar.qArray[i] == Iniciar.gArray[i])
if (string.Equals(Iniciar.qArray[i],Iniciar.gArray[i], StringComparison.OrdinalIgnoreCase))
{
acertos = acertos + 1;
correta[i] = "CERTA";
}
else
{
correta[i] = "ERRADA";
}
}
for (int j = 0; j < Iniciar.qArray.Length; j++)
{
nQuest[j] = Iniciar.nQuestao + j;
}
string[] result = nQuest.Select(x => x.ToString()).ToArray();
for (var i = 0; i < Iniciar.qArray.Count(); i++)
{
listView1.Items.Add(new ListViewItem(new[] {result[i], Iniciar.qArray[i], Iniciar.gArray[i], correta[i] }));
}
nAcertos.Text = acertos.ToString();
nErros.Text = (numero - acertos).ToString();
aproveitamento = 100*acertos / numero;
nAproveitamento.Text = string.Concat(aproveitamento.ToString()," %");
nAcertos.ReadOnly = true;
nErros.ReadOnly = true;
nAproveitamento.ReadOnly = true;
comboBox1.Text = "Excel (*.xlsx)";
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
ToolTip toolTip1 = new ToolTip();
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 200;
toolTip1.ReshowDelay = 500;
toolTip1.SetToolTip(this.button1, "O arquivo será salvo na mesma pasta de onde este programa está sendo executado");
}
private void Resultado_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
xla.Visible = true;
Microsoft.Office.Interop.Excel.Workbook wb = xla.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xla.ActiveSheet;
int i = 1;
int j = 1;
foreach (ListViewItem comp in listView1.Items)
{
ws.Cells[i, j] = comp.Text.ToString();
foreach (ListViewItem.ListViewSubItem drv in comp.SubItems)
{
ws.Cells[i, j] = drv.Text.ToString();
j++;
}
j = 1;
i++;
}
xla.DisplayAlerts = false;
xla.ScreenUpdating = false;
if (string.IsNullOrWhiteSpace(txtNomeExport.Text))
{
txtNomeExport.Text = "Resultado";
}
try
{
if (comboBox1.Text == "Excel (*.xlsx)")
{
if (File.Exists(@Environment.CurrentDirectory + "\\" + txtNomeExport.Text + ".xlsx"))
{
txtNomeExport.Text = txtNomeExport.Text + "1";
}
wb.SaveAs(@Environment.CurrentDirectory + "\\" + txtNomeExport.Text, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault);
}
else if (comboBox1.Text == "CSV (*.csv)")
{
if (File.Exists(@Environment.CurrentDirectory + "\\" + txtNomeExport.Text + ".csv"))
{
txtNomeExport.Text = txtNomeExport.Text + "1";
}
wb.SaveAs(@Environment.CurrentDirectory + "\\" + txtNomeExport.Text, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV);
}
else
{
wb.SaveAs(@Environment.CurrentDirectory + "\\" + txtNomeExport.Text, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault);
MessageBox.Show("Como o formato selecionado não está disponível, o arquivo foi salvo no formato de Excel comum (*.xlsx)");
}
}
catch (Exception)
{
MessageBox.Show("O nome do arquivo é inválido. Não use caracteres especiais e tente novamente.");
}
wb.Close(false);
xla.DisplayAlerts = true;
xla.ScreenUpdating = true;
xla.Quit();
}
}
}
| 29.594595 | 152 | 0.516164 | [
"MIT"
] | andreszlima/Gabarito | Resultado.cs | 5,485 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Internal.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Globalization
{
internal partial class CultureData
{
/// <summary>
/// Check with the OS to see if this is a valid culture.
/// If so we populate a limited number of fields. If its not valid we return false.
///
/// The fields we populate:
///
/// sWindowsName -- The name that windows thinks this culture is, ie:
/// en-US if you pass in en-US
/// de-DE_phoneb if you pass in de-DE_phoneb
/// fj-FJ if you pass in fj (neutral, on a pre-Windows 7 machine)
/// fj if you pass in fj (neutral, post-Windows 7 machine)
///
/// sRealName -- The name you used to construct the culture, in pretty form
/// en-US if you pass in EN-us
/// en if you pass in en
/// de-DE_phoneb if you pass in de-DE_phoneb
///
/// sSpecificCulture -- The specific culture for this culture
/// en-US for en-US
/// en-US for en
/// de-DE_phoneb for alt sort
/// fj-FJ for fj (neutral)
///
/// sName -- The IETF name of this culture (ie: no sort info, could be neutral)
/// en-US if you pass in en-US
/// en if you pass in en
/// de-DE if you pass in de-DE_phoneb
///
/// bNeutral -- TRUE if it is a neutral locale
///
/// For a neutral we just populate the neutral name, but we leave the windows name pointing to the
/// windows locale that's going to provide data for us.
/// </summary>
private unsafe bool NlsInitCultureData()
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(GlobalizationMode.UseNls);
int result;
string realNameBuffer = _sRealName;
char* pBuffer = stackalloc char[Interop.Kernel32.LOCALE_NAME_MAX_LENGTH];
result = GetLocaleInfoEx(realNameBuffer, Interop.Kernel32.LOCALE_SNAME, pBuffer, Interop.Kernel32.LOCALE_NAME_MAX_LENGTH);
// Did it fail?
if (result == 0)
{
return false;
}
// It worked, note that the name is the locale name, so use that (even for neutrals)
// We need to clean up our "real" name, which should look like the windows name right now
// so overwrite the input with the cleaned up name
_sRealName = new string(pBuffer, 0, result - 1);
realNameBuffer = _sRealName;
// Check for neutrality, don't expect to fail
// (buffer has our name in it, so we don't have to do the gc. stuff)
result = GetLocaleInfoEx(realNameBuffer, Interop.Kernel32.LOCALE_INEUTRAL | Interop.Kernel32.LOCALE_RETURN_NUMBER, pBuffer, sizeof(int) / sizeof(char));
if (result == 0)
{
return false;
}
// Remember our neutrality
_bNeutral = *((uint*)pBuffer) != 0;
// Note: Parents will be set dynamically
// Start by assuming the windows name will be the same as the specific name since windows knows
// about specifics on all versions. Only for downlevel Neutral locales does this have to change.
_sWindowsName = realNameBuffer;
// Neutrals and non-neutrals are slightly different
if (_bNeutral)
{
// Neutral Locale
// IETF name looks like neutral name
_sName = realNameBuffer;
// Specific locale name is whatever ResolveLocaleName (win7+) returns.
// (Buffer has our name in it, and we can recycle that because windows resolves it before writing to the buffer)
result = Interop.Kernel32.ResolveLocaleName(realNameBuffer, pBuffer, Interop.Kernel32.LOCALE_NAME_MAX_LENGTH);
// 0 is failure, 1 is invariant (""), which we expect
if (result < 1)
{
return false;
}
// We found a locale name, so use it.
// In vista this should look like a sort name (de-DE_phoneb) or a specific culture (en-US) and be in the "pretty" form
_sSpecificCulture = new string(pBuffer, 0, result - 1);
}
else
{
// Specific Locale
// Specific culture's the same as the locale name since we know its not neutral
// On mac we'll use this as well, even for neutrals. There's no obvious specific
// culture to use and this isn't exposed, but behaviorally this is correct on mac.
// Note that specifics include the sort name (de-DE_phoneb)
_sSpecificCulture = realNameBuffer;
_sName = realNameBuffer;
// We need the IETF name (sname)
// If we aren't an alt sort locale then this is the same as the windows name.
// If we are an alt sort locale then this is the same as the part before the _ in the windows name
// This is for like de-DE_phoneb and es-ES_tradnl that hsouldn't have the _ part
result = GetLocaleInfoEx(realNameBuffer, Interop.Kernel32.LOCALE_ILANGUAGE | Interop.Kernel32.LOCALE_RETURN_NUMBER, pBuffer, sizeof(int) / sizeof(char));
if (result == 0)
{
return false;
}
_iLanguage = *((int*)pBuffer);
if (!IsCustomCultureId(_iLanguage))
{
// not custom locale
int index = realNameBuffer.IndexOf('_');
if (index > 0 && index < realNameBuffer.Length)
{
_sName = realNameBuffer.Substring(0, index);
}
}
}
// It succeeded.
return true;
}
// Wrappers around the GetLocaleInfoEx APIs which handle marshalling the returned
// data as either and Int or string.
internal static unsafe string? GetLocaleInfoEx(string localeName, uint field)
{
// REVIEW: Determine the maximum size for the buffer
const int BUFFER_SIZE = 530;
char* pBuffer = stackalloc char[BUFFER_SIZE];
int resultCode = GetLocaleInfoEx(localeName, field, pBuffer, BUFFER_SIZE);
if (resultCode > 0)
{
return new string(pBuffer);
}
return null;
}
internal static unsafe int GetLocaleInfoExInt(string localeName, uint field)
{
field |= Interop.Kernel32.LOCALE_RETURN_NUMBER;
int value = 0;
GetLocaleInfoEx(localeName, field, (char*)&value, sizeof(int));
return value;
}
internal static unsafe int GetLocaleInfoEx(string lpLocaleName, uint lcType, char* lpLCData, int cchData)
{
Debug.Assert(!GlobalizationMode.Invariant);
return Interop.Kernel32.GetLocaleInfoEx(lpLocaleName, lcType, lpLCData, cchData);
}
private string NlsGetLocaleInfo(LocaleStringData type)
{
Debug.Assert(GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already");
return NlsGetLocaleInfo(_sWindowsName, type);
}
// For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
// "windows" name, which can be specific for downlevel (< windows 7) os's.
private string NlsGetLocaleInfo(string localeName, LocaleStringData type)
{
Debug.Assert(GlobalizationMode.UseNls);
uint lctype = (uint)type;
return GetLocaleInfoFromLCType(localeName, lctype, UseUserOverride);
}
private int NlsGetLocaleInfo(LocaleNumberData type)
{
Debug.Assert(GlobalizationMode.UseNls);
uint lctype = (uint)type;
// Fix lctype if we don't want overrides
if (!UseUserOverride)
{
lctype |= Interop.Kernel32.LOCALE_NOUSEROVERRIDE;
}
// Ask OS for data, note that we presume it returns success, so we have to know that
// sWindowsName is valid before calling.
Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
return GetLocaleInfoExInt(_sWindowsName, lctype);
}
private int[] NlsGetLocaleInfo(LocaleGroupingData type)
{
Debug.Assert(GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
return ConvertWin32GroupString(GetLocaleInfoFromLCType(_sWindowsName, (uint)type, UseUserOverride));
}
private string? NlsGetTimeFormatString()
{
Debug.Assert(GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
return ReescapeWin32String(GetLocaleInfoFromLCType(_sWindowsName, Interop.Kernel32.LOCALE_STIMEFORMAT, UseUserOverride));
}
private int NlsGetFirstDayOfWeek()
{
Debug.Assert(GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
int result = GetLocaleInfoExInt(_sWindowsName, Interop.Kernel32.LOCALE_IFIRSTDAYOFWEEK | (!UseUserOverride ? Interop.Kernel32.LOCALE_NOUSEROVERRIDE : 0));
// Win32 and .NET disagree on the numbering for days of the week, so we have to convert.
return ConvertFirstDayOfWeekMonToSun(result);
}
private string[]? NlsGetTimeFormats()
{
// Note that this gets overrides for us all the time
Debug.Assert(GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already");
string[]? result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, 0, UseUserOverride));
return result;
}
private string[]? NlsGetShortTimeFormats()
{
// Note that this gets overrides for us all the time
Debug.Assert(GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already");
string[]? result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, Interop.Kernel32.TIME_NOSECONDS, UseUserOverride));
return result;
}
// Enumerate all system cultures and then try to find out which culture has
// region name match the requested region name
private static CultureData? NlsGetCultureDataFromRegionName(string regionName)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(GlobalizationMode.UseNls);
Debug.Assert(regionName != null);
EnumLocaleData context;
context.cultureName = null;
context.regionName = regionName;
unsafe
{
Interop.Kernel32.EnumSystemLocalesEx(EnumSystemLocalesProc, Interop.Kernel32.LOCALE_SPECIFICDATA | Interop.Kernel32.LOCALE_SUPPLEMENTAL, Unsafe.AsPointer(ref context), IntPtr.Zero);
}
if (context.cultureName != null)
{
// we got a matched culture
return GetCultureData(context.cultureName, true);
}
return null;
}
private string NlsGetLanguageDisplayName(string cultureName)
{
Debug.Assert(GlobalizationMode.UseNls);
// Usually the UI culture shouldn't be different than what we got from WinRT except
// if DefaultThreadCurrentUICulture was set
CultureInfo? ci;
if (CultureInfo.DefaultThreadCurrentUICulture != null &&
((ci = CultureInfo.NlsGetUserDefaultCulture()) != null) &&
!CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name))
{
return NativeName;
}
else
{
return NlsGetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName);
}
}
private string NlsGetRegionDisplayName()
{
Debug.Assert(GlobalizationMode.UseNls);
// If the current UI culture matching the OS UI language, we'll get the display name from the OS.
// otherwise, we use the native name as we don't carry resources for the region display names anyway.
if (CultureInfo.CurrentUICulture.Name.Equals(CultureInfo.UserDefaultUICulture.Name))
{
return NlsGetLocaleInfo(LocaleStringData.LocalizedCountryName);
}
return NativeCountryName;
}
// PAL methods end here.
private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOveride)
{
Debug.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null");
// Fix lctype if we don't want overrides
if (!useUserOveride)
{
lctype |= Interop.Kernel32.LOCALE_NOUSEROVERRIDE;
}
// Ask OS for data
// Failed? Just use empty string
return GetLocaleInfoEx(localeName, lctype) ?? string.Empty;
}
/// <summary>
/// Reescape a Win32 style quote string as a NLS+ style quoted string
///
/// This is also the escaping style used by custom culture data files
///
/// NLS+ uses \ to escape the next character, whether in a quoted string or
/// not, so we always have to change \ to \\.
///
/// NLS+ uses \' to escape a quote inside a quoted string so we have to change
/// '' to \' (if inside a quoted string)
///
/// We don't build the stringbuilder unless we find something to change
/// </summary>
[return: NotNullIfNotNull("str")]
internal static string? ReescapeWin32String(string? str)
{
// If we don't have data, then don't try anything
if (str == null)
{
return null;
}
StringBuilder? result = null;
bool inQuote = false;
for (int i = 0; i < str.Length; i++)
{
// Look for quote
if (str[i] == '\'')
{
// Already in quote?
if (inQuote)
{
// See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote?
if (i + 1 < str.Length && str[i + 1] == '\'')
{
// Found another ', so we have ''. Need to add \' instead.
// 1st make sure we have our stringbuilder
result ??= new StringBuilder(str, 0, i, str.Length * 2);
// Append a \' and keep going (so we don't turn off quote mode)
result.Append("\\'");
i++;
continue;
}
// Turning off quote mode, fall through to add it
inQuote = false;
}
else
{
// Found beginning quote, fall through to add it
inQuote = true;
}
}
// Is there a single \ character?
else if (str[i] == '\\')
{
// Found a \, need to change it to \\
// 1st make sure we have our stringbuilder
result ??= new StringBuilder(str, 0, i, str.Length * 2);
// Append our \\ to the string & continue
result.Append("\\\\");
continue;
}
// If we have a builder we need to add our character
result?.Append(str[i]);
}
// Unchanged string? , just return input string
if (result == null)
return str;
// String changed, need to use the builder
return result.ToString();
}
[return: NotNullIfNotNull("array")]
internal static string[]? ReescapeWin32Strings(string[]? array)
{
if (array != null)
{
for (int i = 0; i < array.Length; i++)
{
array[i] = ReescapeWin32String(array[i]);
}
}
return array;
}
// If we get a group from windows, then its in 3;0 format with the 0 backwards
// of how NLS+ uses it (ie: if the string has a 0, then the int[] shouldn't and vice versa)
// EXCEPT in the case where the list only contains 0 in which NLS and NLS+ have the same meaning.
private static int[] ConvertWin32GroupString(string win32Str)
{
// None of these cases make any sense
if (string.IsNullOrEmpty(win32Str))
{
return new int[] { 3 };
}
if (win32Str[0] == '0')
{
return new int[] { 0 };
}
// Since its in n;n;n;n;n format, we can always get the length quickly
int[] values;
if (win32Str[^1] == '0')
{
// Trailing 0 gets dropped. 1;0 -> 1
values = new int[win32Str.Length / 2];
}
else
{
// Need extra space for trailing zero 1 -> 1;0
values = new int[(win32Str.Length / 2) + 2];
values[^1] = 0;
}
int i;
int j;
for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++)
{
// Note that this # shouldn't ever be zero, 'cause 0 is only at end
// But we'll test because its registry that could be anything
if (win32Str[i] < '1' || win32Str[i] > '9')
return new int[] { 3 };
values[j] = (int)(win32Str[i] - '0');
}
return values;
}
private static int ConvertFirstDayOfWeekMonToSun(int iTemp)
{
// Convert Mon-Sun to Sun-Sat format
iTemp++;
if (iTemp > 6)
{
// Wrap Sunday and convert invalid data to Sunday
iTemp = 0;
}
return iTemp;
}
// Context for EnumCalendarInfoExEx callback.
private struct EnumLocaleData
{
public string regionName;
public string? cultureName;
}
// EnumSystemLocaleEx callback.
// [NativeCallable(CallingConvention = CallingConvention.StdCall)]
private static unsafe Interop.BOOL EnumSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle)
{
ref EnumLocaleData context = ref Unsafe.As<byte, EnumLocaleData>(ref *(byte*)contextHandle);
try
{
string cultureName = new string(lpLocaleString);
string? regionName = GetLocaleInfoEx(cultureName, Interop.Kernel32.LOCALE_SISO3166CTRYNAME);
if (regionName != null && regionName.Equals(context.regionName, StringComparison.OrdinalIgnoreCase))
{
context.cultureName = cultureName;
return Interop.BOOL.FALSE; // we found a match, then stop the enumeration
}
return Interop.BOOL.TRUE;
}
catch (Exception)
{
return Interop.BOOL.FALSE;
}
}
// EnumSystemLocaleEx callback.
// [NativeCallable(CallingConvention = CallingConvention.StdCall)]
private static unsafe Interop.BOOL EnumAllSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle)
{
ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)contextHandle);
try
{
context.strings.Add(new string(lpLocaleString));
return Interop.BOOL.TRUE;
}
catch (Exception)
{
return Interop.BOOL.FALSE;
}
}
// Context for EnumTimeFormatsEx callback.
private struct EnumData
{
public List<string> strings;
}
// EnumTimeFormatsEx callback itself.
// [NativeCallable(CallingConvention = CallingConvention.StdCall)]
private static unsafe Interop.BOOL EnumTimeCallback(char* lpTimeFormatString, void* lParam)
{
ref EnumData context = ref Unsafe.As<byte, EnumData>(ref *(byte*)lParam);
try
{
context.strings.Add(new string(lpTimeFormatString));
return Interop.BOOL.TRUE;
}
catch (Exception)
{
return Interop.BOOL.FALSE;
}
}
private static unsafe string[]? nativeEnumTimeFormats(string localeName, uint dwFlags, bool useUserOverride)
{
EnumData data = default;
data.strings = new List<string>();
// Now call the enumeration API. Work is done by our callback function
Interop.Kernel32.EnumTimeFormatsEx(EnumTimeCallback, localeName, (uint)dwFlags, Unsafe.AsPointer(ref data));
if (data.strings.Count > 0)
{
// Now we need to allocate our stringarray and populate it
string[] results = data.strings.ToArray();
if (!useUserOverride && data.strings.Count > 1)
{
// Since there is no "NoUserOverride" aware EnumTimeFormatsEx, we always get an override
// The override is the first entry if it is overriden.
// We can check if we have overrides by checking the GetLocaleInfo with no override
// If we do have an override, we don't know if it is a user defined override or if the
// user has just selected one of the predefined formats so we can't just remove it
// but we can move it down.
uint lcType = (dwFlags == Interop.Kernel32.TIME_NOSECONDS) ? Interop.Kernel32.LOCALE_SSHORTTIME : Interop.Kernel32.LOCALE_STIMEFORMAT;
string timeFormatNoUserOverride = GetLocaleInfoFromLCType(localeName, lcType, useUserOverride);
if (timeFormatNoUserOverride != "")
{
string firstTimeFormat = results[0];
if (timeFormatNoUserOverride != firstTimeFormat)
{
results[0] = results[1];
results[1] = firstTimeFormat;
}
}
}
return results;
}
return null;
}
private static int NlsLocaleNameToLCID(string cultureName)
{
Debug.Assert(!GlobalizationMode.Invariant);
return Interop.Kernel32.LocaleNameToLCID(cultureName, Interop.Kernel32.LOCALE_ALLOW_NEUTRAL_NAMES);
}
private static unsafe string? NlsLCIDToLocaleName(int culture)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(GlobalizationMode.UseNls);
char* pBuffer = stackalloc char[Interop.Kernel32.LOCALE_NAME_MAX_LENGTH + 1]; // +1 for the null termination
int length = Interop.Kernel32.LCIDToLocaleName(culture, pBuffer, Interop.Kernel32.LOCALE_NAME_MAX_LENGTH + 1, Interop.Kernel32.LOCALE_ALLOW_NEUTRAL_NAMES);
if (length > 0)
{
return new string(pBuffer);
}
return null;
}
private int NlsGetAnsiCodePage(string cultureName)
{
Debug.Assert(GlobalizationMode.UseNls);
return NlsGetLocaleInfo(LocaleNumberData.AnsiCodePage);
}
private int NlsGetOemCodePage(string cultureName)
{
Debug.Assert(GlobalizationMode.UseNls);
return NlsGetLocaleInfo(LocaleNumberData.OemCodePage);
}
private int NlsGetMacCodePage(string cultureName)
{
Debug.Assert(GlobalizationMode.UseNls);
return NlsGetLocaleInfo(LocaleNumberData.MacCodePage);
}
private int NlsGetEbcdicCodePage(string cultureName)
{
Debug.Assert(GlobalizationMode.UseNls);
return NlsGetLocaleInfo(LocaleNumberData.EbcdicCodePage);
}
private int NlsGetGeoId(string cultureName)
{
Debug.Assert(GlobalizationMode.UseNls);
return NlsGetLocaleInfo(LocaleNumberData.GeoId);
}
private int NlsGetDigitSubstitution(string cultureName)
{
Debug.Assert(GlobalizationMode.UseNls);
return NlsGetLocaleInfo(LocaleNumberData.DigitSubstitution);
}
private string NlsGetThreeLetterWindowsLanguageName(string cultureName)
{
Debug.Assert(GlobalizationMode.UseNls);
return NlsGetLocaleInfo(cultureName, LocaleStringData.AbbreviatedWindowsLanguageName);
}
private static CultureInfo[] NlsEnumCultures(CultureTypes types)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(GlobalizationMode.UseNls);
uint flags = 0;
#pragma warning disable 618
if ((types & (CultureTypes.FrameworkCultures | CultureTypes.InstalledWin32Cultures | CultureTypes.ReplacementCultures)) != 0)
{
flags |= Interop.Kernel32.LOCALE_NEUTRALDATA | Interop.Kernel32.LOCALE_SPECIFICDATA;
}
#pragma warning restore 618
if ((types & CultureTypes.NeutralCultures) != 0)
{
flags |= Interop.Kernel32.LOCALE_NEUTRALDATA;
}
if ((types & CultureTypes.SpecificCultures) != 0)
{
flags |= Interop.Kernel32.LOCALE_SPECIFICDATA;
}
if ((types & CultureTypes.UserCustomCulture) != 0)
{
flags |= Interop.Kernel32.LOCALE_SUPPLEMENTAL;
}
if ((types & CultureTypes.ReplacementCultures) != 0)
{
flags |= Interop.Kernel32.LOCALE_SUPPLEMENTAL;
}
EnumData context = default;
context.strings = new List<string>();
unsafe
{
Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, flags, Unsafe.AsPointer(ref context), IntPtr.Zero);
}
CultureInfo[] cultures = new CultureInfo[context.strings.Count];
for (int i = 0; i < cultures.Length; i++)
{
cultures[i] = new CultureInfo(context.strings[i]);
}
return cultures;
}
private string NlsGetConsoleFallbackName(string cultureName)
{
Debug.Assert(GlobalizationMode.UseNls);
return NlsGetLocaleInfo(cultureName, LocaleStringData.ConsoleFallbackName);
}
internal bool NlsIsReplacementCulture
{
get
{
Debug.Assert(GlobalizationMode.UseNls);
EnumData context = default;
context.strings = new List<string>();
unsafe
{
Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, Interop.Kernel32.LOCALE_REPLACEMENT, Unsafe.AsPointer(ref context), IntPtr.Zero);
}
for (int i = 0; i < context.strings.Count; i++)
{
if (string.Equals(context.strings[i], _sWindowsName, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
}
internal static unsafe CultureData NlsGetCurrentRegionData()
{
Debug.Assert(GlobalizationMode.UseNls);
Span<char> geoIso2Letters = stackalloc char[10];
int geoId = Interop.Kernel32.GetUserGeoID(Interop.Kernel32.GEOCLASS_NATION);
if (geoId != Interop.Kernel32.GEOID_NOT_AVAILABLE)
{
int geoIsoIdLength;
fixed (char* pGeoIsoId = geoIso2Letters)
{
geoIsoIdLength = Interop.Kernel32.GetGeoInfo(geoId, Interop.Kernel32.GEO_ISO2, pGeoIsoId, geoIso2Letters.Length, 0);
}
if (geoIsoIdLength != 0)
{
geoIsoIdLength -= geoIso2Letters[geoIsoIdLength - 1] == 0 ? 1 : 0; // handle null termination and exclude it.
CultureData? cd = GetCultureDataForRegion(geoIso2Letters.Slice(0, geoIsoIdLength).ToString(), true);
if (cd != null)
{
return cd;
}
}
}
// Fallback to current locale data.
return CultureInfo.CurrentCulture._cultureData;
}
}
}
| 39.931347 | 197 | 0.556298 | [
"MIT"
] | AlenaSviridenko/runtime | src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Nls.cs | 30,827 | C# |
namespace MercadoPago.Client
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MercadoPago.Config;
using MercadoPago.Error;
using MercadoPago.Http;
using MercadoPago.Resource;
using MercadoPago.Serialization;
using HttpMethod = Http.HttpMethod;
/// <summary>
/// Base class for APIs clients.
/// </summary>
/// <typeparam name="TResource">Type of the resource.</typeparam>
public abstract class MercadoPagoClient<TResource>
where TResource : IResource, new()
{
private const string ACCEPT_VALUE = "application/json";
/// <summary>
/// Constructor of the <see cref="MercadoPagoClient{TResource}"/> class.
/// </summary>
/// <param name="httpClient">The http client that will be used in HTTP requests.</param>
/// <param name="serializer">
/// The serializer that will be used to serialize the HTTP requests content
/// and to deserialize the HTTP response content.
/// </param>
protected MercadoPagoClient(
IHttpClient httpClient,
ISerializer serializer)
{
HttpClient = httpClient ?? MercadoPagoConfig.HttpClient;
Serializer = serializer ?? MercadoPagoConfig.Serializer;
}
/// <summary>
/// The <see cref="IHttpClient"/> used to make HTTP requests.
/// </summary>
public IHttpClient HttpClient { get; }
/// <summary>
/// The <see cref="ISerializer"/> used to serialize request objects
/// to JSON and deserialize API response to <see cref="IResource"/>.
/// </summary>
public ISerializer Serializer { get; }
/// <summary>
/// The defaults headers that will be sended in every request.
/// </summary>
protected IDictionary<string, string> DefaultHeaders =>
new Dictionary<string, string>
{
[Headers.ACCEPT] = ACCEPT_VALUE,
[Headers.PRODUCT_ID] = MercadoPagoConfig.ProductId,
[Headers.USER_AGENT] = $"MercadoPago DotNet SDK/{MercadoPagoConfig.Version}",
};
/// <summary>
/// Send a async request to api <paramref name="path"/> with HTTP method <paramref name="httpMethod"/>.
/// The content body is in <paramref name="request"/>.
/// </summary>
/// <param name="path">Path of the endpoint.</param>
/// <param name="httpMethod">HTTP method.</param>
/// <param name="request">Object with request data.</param>
/// <param name="requestOptions"><see cref="RequestOptions"/></param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>
/// A task whose result is a resource that represents the API response.
/// </returns>
protected Task<TResource> SendAsync(
string path,
HttpMethod httpMethod,
object request,
RequestOptions requestOptions = null,
CancellationToken cancellationToken = default)
{
return SendAsync<TResource>(
path,
httpMethod,
request,
requestOptions,
cancellationToken);
}
/// <summary>
/// Send a request to api <paramref name="path"/> with HTTP method <paramref name="httpMethod"/>.
/// The content body is in <paramref name="request"/>.
/// </summary>
/// <param name="path">Path of the endpoint.</param>
/// <param name="httpMethod">HTTP method.</param>
/// <param name="request">Object with request data.</param>
/// <param name="requestOptions"><see cref="RequestOptions"/></param>
/// <returns>A resource that represents the API response.</returns>
protected TResource Send(
string path,
HttpMethod httpMethod,
object request,
RequestOptions requestOptions = null)
{
return SendAsync(path, httpMethod, request, requestOptions, default)
.ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// List async the resources from <paramref name="path"/>.
/// </summary>
/// <param name="path">Path of API.</param>
/// <param name="httpMethod">HTTP method.</param>
/// <param name="request">Object with request data.</param>
/// <param name="requestOptions"><see cref="RequestOptions"/></param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>
/// A task whose result is a list of resources.
/// </returns>
protected Task<ResourcesList<TResource>> ListAsync(
string path,
HttpMethod httpMethod,
object request,
RequestOptions requestOptions = null,
CancellationToken cancellationToken = default)
{
return SendAsync<ResourcesList<TResource>>(
path,
httpMethod,
request,
requestOptions,
cancellationToken);
}
/// <summary>
/// List the resources from <paramref name="path"/>.
/// </summary>
/// <param name="path">Path of API.</param>
/// <param name="httpMethod">HTTP method.</param>
/// <param name="request">Object with request data.</param>
/// <param name="requestOptions"><see cref="RequestOptions"/></param>
/// <returns>
/// A task whose result is a list of resources.
/// </returns>
protected ResourcesList<TResource> List(
string path,
HttpMethod httpMethod,
object request,
RequestOptions requestOptions = null)
{
return SendAsync<ResourcesList<TResource>>(
path,
httpMethod,
request,
requestOptions,
default)
.ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Searches async and returns a result page with resources.
/// </summary>
/// <typeparam name="TPageResult">The type of page.</typeparam>
/// <param name="path">Path of search API.</param>
/// <param name="request">Object with search parameters.</param>
/// <param name="requestOptions"><see cref="RequestOptions"/>.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>
/// A task whose result is a search response page.
/// </returns>
protected Task<TPageResult> SearchAsync<TPageResult>(
string path,
SearchRequest request,
RequestOptions requestOptions = null,
CancellationToken cancellationToken = default)
where TPageResult : IResourcesPage<TResource>, new()
{
return SendAsync<TPageResult>(
path,
HttpMethod.GET,
request?.GetParameters(),
requestOptions,
cancellationToken);
}
/// <summary>
/// Searches and returns a result page with resources.
/// </summary>
/// <typeparam name="TPageResult">The type of page.</typeparam>
/// <param name="path">Path of search API.</param>
/// <param name="request">Object with search parameters.</param>
/// <param name="requestOptions"><see cref="RequestOptions"/>.</param>
/// <returns>A search response page.</returns>
protected TPageResult Search<TPageResult>(
string path,
SearchRequest request,
RequestOptions requestOptions = null)
where TPageResult : IResourcesPage<TResource>, new()
{
return SearchAsync<TPageResult>(
path,
request,
requestOptions)
.ConfigureAwait(false).GetAwaiter().GetResult();
}
private async Task<TResponse> SendAsync<TResponse>(
string path,
HttpMethod httpMethod,
object request,
RequestOptions requestOptions,
CancellationToken cancellationToken)
where TResponse : IResource, new()
{
MercadoPagoResponse response;
requestOptions = BuildRequestOptions(requestOptions);
try
{
MercadoPagoRequest mercadoPagoRequest = await BuildRequestAsync(
path,
httpMethod,
request,
requestOptions);
response = await HttpClient.SendAsync(
mercadoPagoRequest,
requestOptions.RetryStrategy,
cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
throw new MercadoPagoException(ex);
}
return ParseResponse<TResponse>(response);
}
private RequestOptions BuildRequestOptions(RequestOptions requestOptions)
{
if (requestOptions == null)
{
requestOptions = new RequestOptions();
}
requestOptions.AccessToken = string.IsNullOrWhiteSpace(requestOptions.AccessToken) ?
MercadoPagoConfig.AccessToken : requestOptions.AccessToken;
requestOptions.RetryStrategy = requestOptions.RetryStrategy ?? MercadoPagoConfig.RetryStrategy;
return requestOptions;
}
private MercadoPagoRequest BuildRequest(
string path,
HttpMethod httpMethod,
RequestOptions requestOptions)
{
var mercadoPagoRequest = new MercadoPagoRequest
{
Url = $"{MercadoPagoConfig.BaseUrl}{path}",
Method = httpMethod,
};
AddRequestHeaders(path, mercadoPagoRequest, requestOptions);
return mercadoPagoRequest;
}
private async Task<MercadoPagoRequest> BuildRequestAsync(
string path,
HttpMethod httpMethod,
object request,
RequestOptions requestOptions)
{
var mercadoPagoRequest = BuildRequest(path, httpMethod, requestOptions);
var queryString = string.Empty;
if (request != null)
{
AddIdempotencyKey(mercadoPagoRequest, request);
if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.PUT)
{
mercadoPagoRequest.Content = Serializer.SerializeToJson(request);
}
else if (httpMethod == HttpMethod.GET)
{
string parameters = await Serializer.SerializeToQueryStringAsync(request);
if (!string.IsNullOrEmpty(parameters))
{
queryString = $"?{parameters}";
}
}
}
mercadoPagoRequest.Url = $"{mercadoPagoRequest.Url}{queryString}";
return mercadoPagoRequest;
}
private void AddRequestHeaders(
string path,
MercadoPagoRequest mercadoPagoRequest,
RequestOptions requestOptions)
{
foreach (var header in DefaultHeaders)
{
mercadoPagoRequest.Headers.Add(header);
}
path = path ?? string.Empty;
if (!path.Equals("/oauth/token", StringComparison.InvariantCultureIgnoreCase))
{
mercadoPagoRequest.Headers.Add(Headers.AUTHORIZATION, $"Bearer {requestOptions.AccessToken}");
}
if (!string.IsNullOrWhiteSpace(MercadoPagoConfig.CorporationId))
{
mercadoPagoRequest.Headers.Add(Headers.CORPORATION_ID, MercadoPagoConfig.CorporationId);
}
if (!string.IsNullOrWhiteSpace(MercadoPagoConfig.IntegratorId))
{
mercadoPagoRequest.Headers.Add(Headers.INTEGRATOR_ID, MercadoPagoConfig.IntegratorId);
}
if (!string.IsNullOrWhiteSpace(MercadoPagoConfig.PlatformId))
{
mercadoPagoRequest.Headers.Add(Headers.PLATFORM_ID, MercadoPagoConfig.PlatformId);
}
foreach (var header in requestOptions.CustomHeaders)
{
if (!mercadoPagoRequest.Headers.ContainsKey(header.Key)
&& !Headers.CONTENT_TYPE.Equals(header.Key, StringComparison.InvariantCultureIgnoreCase))
{
mercadoPagoRequest.Headers.Add(header);
}
}
}
private void AddIdempotencyKey(MercadoPagoRequest mercadoPagoRequest, object request)
{
if (mercadoPagoRequest.Method == HttpMethod.POST)
{
bool headerHasIdempotencyKey = mercadoPagoRequest.ContainsHeader(Headers.IDEMPOTENCY_KEY);
if (request is IdempotentRequest idempotentRequest && !headerHasIdempotencyKey)
{
mercadoPagoRequest.Headers.Add(Headers.IDEMPOTENCY_KEY, idempotentRequest.CreateIdempotencyKey());
}
}
}
private TResponse ParseResponse<TResponse>(MercadoPagoResponse response)
where TResponse : IResource, new()
{
if (response.StatusCode != 200 && response.StatusCode != 201)
{
throw BuildApiErrorException(response);
}
TResponse resource;
try
{
resource = Serializer.DeserializeFromJson<TResponse>(response.Content);
}
catch (Exception)
{
throw BuildInvalidResponseException(response);
}
resource.ApiResponse = response;
return resource;
}
private MercadoPagoApiException BuildApiErrorException(MercadoPagoResponse response)
{
ApiError apiError;
try
{
apiError = Serializer.DeserializeFromJson<ApiError>(response.Content);
}
catch (Exception)
{
apiError = null;
}
return new MercadoPagoApiException("Error response from API.", response)
{
ApiError = apiError,
};
}
private MercadoPagoApiException BuildInvalidResponseException(MercadoPagoResponse response)
{
return new MercadoPagoApiException("Invalid response from API.", response);
}
}
}
| 37.3025 | 118 | 0.565311 | [
"MIT"
] | mercadopago/sdk-dotnet | src/MercadoPago/Client/MercadoPagoClient.cs | 14,923 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework.Threading.Tasks;
namespace UCSample.CustomComponentCategory {
/// <summary>
/// Simulates your "core" implementation that can be extended via your
/// <b>UCSampleExampleCategory</b> category. Vendors that extend your category MUST implement the
/// <see cref="IComponentCategoryInterface"/> interface.
/// </summary>
/// <remarks>We simulate some kind of tracing algorithm that can be extended by
/// 3rd parties</remarks>
internal class CoreImplementationTrace : ICoreImplementationTraceInterface, INetworkResult, IDisposable {
private StringBuilder _sb = null;
private TraceResult _tr = null;
/// <summary>
/// For Beta4, NetworkLayer type is not supported so we have
/// a stand-in here
/// </summary>
public NetworkLayer traceLayer {
get { return new NetworkLayer() { Name = "MyCustomLayerName" }; }
}
/// <summary>
/// Execute the trace with a custom component that can extend it
/// </summary>
/// <param name="extender"></param>
/// <returns></returns>
public Task Trace(IComponentCategoryInterface extender) {
_sb = null;
_sb = new StringBuilder();
return QueuingTaskFactory.StartNew(async () => {
//get the stops
foreach (var stop in extender.GetStops()) {
_sb.AppendFormat("Stop: {0}\r\n", stop.Name);
}
//barriers
foreach (var barrier in extender.GetBarriers()) {
_sb.AppendFormat("Barrier: {0}\r\n", barrier.Name);
}
//do whatever
await System.Threading.Tasks.Task.Delay(1000);
//extenders turn
await extender.ModifyTrace(this);
//results
string sep = "";
_sb.AppendLine("\r\nResults");
_sb.Append("OIDS: ");
foreach (var oid in _tr.tracedSegmentOids) {
_sb.Append(sep + oid.ToString());
sep = ",";
}
});
}
public void UpdateResult(TraceResult results) {
if (_tr == null)
_tr = new TraceResult();
_tr.tracedSegmentOids = new List<long>();
foreach (var oid in results.tracedSegmentOids)
_tr.tracedSegmentOids.Add(oid);
}
public string Message() {
return _sb == null ? "No results" : _sb.ToString();
}
public void Dispose() {
_tr = null;
_sb = null;
}
}
}
| 36.101266 | 109 | 0.546283 | [
"Apache-2.0"
] | Esri/arcgis-pro-samples-beta | Beta4/CustomComponentCategory/CoreImplementationTrace.cs | 2,854 | C# |
using AutoMapper;
using MarsRover.Persistence.EFCore.Context;
using MarsRover.Rover.Persistence;
using MarsRover.Shared;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using DomainRover = MarsRover.Rover.Domain.RoverX;
using PersistenceRover = MarsRover.Persistence.EFCore.Entities.Rover;
namespace MarsRover.Persistence.EFCore.Repositories
{
public class RoverRepository : IRoverRepository
{
private readonly RoverContext _context;
public RoverRepository(RoverContext context)
{
_context = context;
}
public Rover.Domain.Rover GetRover(Guid roverId)
{
var persistenceRover = _context.Rovers.Include(t => t.Plateau).FirstOrDefault(t => t.Id == roverId);
return Mapper.Map<DomainRover>(persistenceRover);
}
public async Task<int> SaveRover(Rover.Domain.Rover rover)
{
var persistenceRover = Mapper.Map<PersistenceRover>(rover);
_context.Rovers.Add(persistenceRover);
return await _context.SaveChangesAsync();
}
public async Task<int> UpdateRover(Rover.Domain.Rover rover)
{
var persistenceRover = _context.Rovers.Include(t => t.Plateau).First(t => t.Id == rover.Id);
persistenceRover.Point = rover.Point;
persistenceRover.Direction = rover.Direction;
persistenceRover.PlateauId = rover.PlateauId;
persistenceRover.IsLocked = rover.IsLocked;
return await _context.SaveChangesAsync();
}
}
}
| 35.666667 | 112 | 0.676636 | [
"MIT"
] | kudretkurt/MarsRover-With-NserviceBus | MarsRover.Persistence.EFCore/Repositories/RoverRepository.cs | 1,607 | C# |
using System;
namespace FontAwesome
{
/// <summary>
/// The unicode values for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Unicode
{
/// <summary>
/// fa-church unicode value ("\uf51d").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/church
/// </summary>
public const string Church = "\uf51d";
}
/// <summary>
/// The Css values for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Css
{
/// <summary>
/// Church unicode value ("fa-church").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/church
/// </summary>
public const string Church = "fa-church";
}
/// <summary>
/// The Icon names for all FontAwesome icons.
/// <para/>
/// See https://fontawesome.com/cheatsheet
/// <para/>
/// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs).
/// </summary>
public static partial class Icon
{
/// <summary>
/// fa-church unicode value ("\uf51d").
/// <para/>
/// This icon supports the following styles: Light (Pro), Regular (Pro), Solid, Duotone (Pro)
/// <para/>
/// See https://fontawesome.com/icons/church
/// </summary>
public const string Church = "Church";
}
} | 35.508197 | 154 | 0.587258 | [
"MIT"
] | michaelswells/FontAwesomeAttribute | FontAwesome/FontAwesome.Church.cs | 2,166 | C# |
using System;
using Xamarin.Forms;
namespace Moments
{
public class RoundedRectangleImage : Image
{
}
}
| 9.166667 | 43 | 0.736364 | [
"MIT"
] | BrotherBrett/moments | Moments - CSharp/Moments.Shared/Controls/RoundedRectangleImage.cs | 110 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using hrmApp.Core.PagedList;
using hrmApp.Core.Constants;
using Microsoft.EntityFrameworkCore.Query;
namespace hrmApp.Core.Services
{
public interface IService<TEntity> where TEntity : class
{
Task<TEntity> GetByIdAysnc(int Id);
Task<TEntity> GetByIdAysnc(string Id);
Task<IEnumerable<TEntity>> GetAllAsync();
Task<IEnumerable<TEntity>> Where(Expression<Func<TEntity, bool>> predicate);
Task<TEntity> SingleOrDefaultAsync(Expression<Func<TEntity, bool>> predicate);
Task<bool> AnyAsync(Expression<Func<TEntity, bool>> predicate);
bool Any(Expression<Func<TEntity, bool>> predicate);
Task<TEntity> AddAsync(TEntity entity);
Task<IEnumerable<TEntity>> AddRangeAsync(IEnumerable<TEntity> entities);
void Remove(TEntity entity);
Task RemoveAsync(TEntity entity);
void RemoveRange(IEnumerable<TEntity> entities);
TEntity Update(TEntity entity);
Task<TEntity> UpdateAsync(TEntity entity);
// Nem használjuk...
Task<IPagedList<TEntity>> GetPagedListAsync(
Expression<Func<TEntity, bool>> predicate = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
Func<IQueryable<TEntity>, IIncludableQueryable<TEntity, object>> include = null,
int pageIndex = 0,
int pageSize = Paging.PageSize,
bool disableTracking = true,
CancellationToken cancellationToken = default(CancellationToken),
bool ignoreQueryFilters = false);
}
}
| 39.111111 | 96 | 0.680114 | [
"MIT"
] | gasparekferenc/hrmApp.N-Layer.MVC | scr/hrmApp/hrmApp.Core/Services/IService.cs | 1,763 | C# |
namespace Ignition.Core.Bases
{
public interface IDatabaseType
{
string GetDatabaseName();
}
} | 16.428571 | 34 | 0.652174 | [
"MIT"
] | Ali-Nasir-01/SitecoreIgnition | Ignition.Core/Bases/IDatabaseType.cs | 117 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Forge.Client.Models
{
public class ForgeClientArgs
{
public string BaseUrl { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string Scope { get; set; }
}
}
| 21.866667 | 48 | 0.643293 | [
"MIT"
] | Frederik91/ForgeBucketList | src/Forge.Client/Models/ForgeClientArgs.cs | 330 | C# |
using System;
using System.ComponentModel;
namespace InstagramApiSharp.Classes.Models
{
public class InstaCommentShort : INotifyPropertyChanged
{
public InstaContentType ContentType { get; set; }
public InstaUserShort User { get; set; }
public long Pk { get; set; }
public string Text { get; set; }
public int Type { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime CreatedAtUtc { get; set; }
public long MediaId { get; set; }
public string Status { get; set; }
public long ParentCommentId { get; set; }
private bool _haslikedcm;
public bool HasLikedComment { get => _haslikedcm; set { _haslikedcm = value; Update("HasLikedComment"); } }
public int CommentLikeCount { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected void Update(string memberName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(memberName));
}
}
}
| 26.35 | 115 | 0.639469 | [
"MIT"
] | AMP-VTV/InstagramApiSharp | src/InstagramApiSharp/Classes/Models/Comment/InstaCommentShort.cs | 1,056 | C# |
/******************************************************************************/
/*
Project - Unity Ray Marching
https://github.com/TheAllenChou/unity-ray-marching
Author - Ming-Lun "Allen" Chou
Web - http://AllenChou.net
Twitter - @TheAllenChou
*/
/******************************************************************************/
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[RequireComponent(typeof(Camera))]
[ExecuteInEditMode]
public class GameObjectRayMarcher : PostProcessingCompute
{
private static readonly int TileSize = 8;
public enum HeatMapModeEnum
{
None,
StepCountPerThread,
StepCountPerTile,
ShapeCountPerThread,
ShapeCountPerTile,
}
[Header("Ray Marching")]
public float BlendDistance = 0.5f;
public Color BackgroundColor = new Color(0.0f, 0.07f, 0.15f);
public Color MissColor = new Color(1.0f, 0.0f, 0.0f);
[Range(1, 256)]
public int MaxRaySteps = 128;
public float RayHitThreshold = 0.005f;
public float MaxRayDistance = 1000.0f;
[Header("Bounding Volume Hierarchy")]
[ConditionalField(Label = "Use BVH")]
public bool UseBoundingVolumes = true;
public bool DrawBoundingVolumes = false;
[ConditionalField(Label = " Isolate BVH Depth", Min = -1, Max = 16)]
public int IsolateBoundingVolumeDepth = -1;
[ConditionalField(Label = "Test BVH Bounds Query")]
public bool TestBvhBoundsQuery = false;
[ConditionalField(Label = "Test BVH Ray Cast")]
public bool TestBvhRayCast = false;
[Header("Heat Map")]
public HeatMapModeEnum HeatMapMode = HeatMapModeEnum.None;
[ConditionalField("HeatMapMode", HeatMapModeEnum.StepCountPerThread, HeatMapModeEnum.StepCountPerTile, Min = 1, Max = 256)]
public int MaxStepCountBudget = 64;
[ConditionalField("HeatMapMode", HeatMapModeEnum.ShapeCountPerThread, HeatMapModeEnum.ShapeCountPerTile, Min = 1, Max = 64)]
public int MaxShapeCountBudget = 16;
public Color HeatColorCool = new Color(0.0f, 1.0f, 0.0f);
public Color HeatColorMedium = new Color(1.0f, 1.0f, 0.0f);
public Color HeatColorHot = new Color(1.0f, 0.0f, 0.0f);
[Range(0.0f, 1.0f)]
public float HeatAlpha = 0.5f;
private struct ShaderConstants
{
public ICollection<int> Kernels;
public int MainKernel;
public int StepCountKernelPerThread;
public int StepCountKernelPerTile;
public int ShapeCountKernelPerThread;
public int ShapeCountKernelPerTile;
public int Src;
public int Dst;
public int CameraInverseProjection;
public int CameraToWorld;
public int CameraPosition;
public int ScreenSize;
public int SdfShapes;
public int NumSdfShapes;
public int TempBuffer;
public int BlendDistance;
public int RayMarchParams;
public int BackgroundColor;
public int MissColor;
public int UseAabbTree;
public int AabbTree;
public int AabbTreeRoot;
public int HeatMap;
public int HeatColorCool;
public int HeatColorMedium;
public int HeatColorHot;
public int HeatAlpha;
public int MaxCountBudget;
}
private ShaderConstants m_const;
private ComputeBuffer m_shapes;
private RenderTexture m_tempBuffer;
private ComputeBuffer m_aabbTree;
private RenderTexture m_heatMap;
protected override void OnValidate()
{
base.OnValidate();
BlendDistance = Mathf.Max(0.0f, BlendDistance);
RayHitThreshold = Mathf.Max(0.0f, RayHitThreshold);
MaxRayDistance = Mathf.Max(0.0f, MaxRayDistance);
IsolateBoundingVolumeDepth = Mathf.Max(-1, IsolateBoundingVolumeDepth);
}
protected override void Init(ComputeShader compute)
{
InitShaderConstants();
}
private void InitShaderConstants()
{
m_const.Kernels =
new int[]
{
m_const.MainKernel = Compute.FindKernel("Main"),
m_const.StepCountKernelPerThread = Compute.FindKernel("StepCountPerThread"),
m_const.StepCountKernelPerTile = Compute.FindKernel("StepCountPerTile"),
m_const.ShapeCountKernelPerThread = Compute.FindKernel("ShapeCountPerThread"),
m_const.ShapeCountKernelPerTile = Compute.FindKernel("ShapeCountPerTile"),
};
m_const.Src = Shader.PropertyToID("src");
m_const.Dst = Shader.PropertyToID("dst");
m_const.CameraInverseProjection = Shader.PropertyToID("cameraInvProj");
m_const.CameraToWorld = Shader.PropertyToID("cameraToWorld");
m_const.CameraPosition = Shader.PropertyToID("cameraPos");
m_const.ScreenSize = Shader.PropertyToID("screenSize");
m_const.SdfShapes = Shader.PropertyToID("aSdfShape");
m_const.NumSdfShapes = Shader.PropertyToID("numSdfShapes");
m_const.TempBuffer = Shader.PropertyToID("tempBuffer");
m_const.RayMarchParams = Shader.PropertyToID("rayMarchParams");
m_const.BlendDistance = Shader.PropertyToID("blendDist");
m_const.BackgroundColor = Shader.PropertyToID("backgroundColor");
m_const.MissColor = Shader.PropertyToID("missColor");
m_const.UseAabbTree = Shader.PropertyToID("useAabbTree");
m_const.AabbTree = Shader.PropertyToID("aabbTree");
m_const.AabbTreeRoot = Shader.PropertyToID("aabbTreeRoot");
m_const.HeatMap = Shader.PropertyToID("heatMap");
m_const.HeatColorCool = Shader.PropertyToID("heatColorCool");
m_const.HeatColorMedium = Shader.PropertyToID("heatColorMedium");
m_const.HeatColorHot = Shader.PropertyToID("heatColorHot");
m_const.HeatAlpha = Shader.PropertyToID("heatAlpha");
m_const.MaxCountBudget = Shader.PropertyToID("maxCountBudget");
}
protected override void Dispose(ComputeShader compute)
{
if (m_shapes != null)
{
m_shapes.Dispose();
m_shapes = null;
}
if (m_heatMap != null)
{
DestroyImmediate(m_heatMap);
m_heatMap = null;
}
}
protected override void OnPreRenderImage(ComputeShader compute, RenderTexture src, RenderTexture dst)
{
// validate SDF shapes buffer
var sdfShapes = RayMarchedShape.GetShapes();
int numShapes = sdfShapes.Count;
if (m_shapes == null
|| m_shapes.count != numShapes)
{
if (m_shapes != null)
{
m_shapes.Dispose();
m_shapes = null;
}
m_shapes = new ComputeBuffer(Mathf.Max(1, numShapes), SdfShape.Stride);
}
// validate SDF temp buffer
if (m_tempBuffer == null
|| m_tempBuffer.width != src.width
|| m_tempBuffer.height != src.height)
{
if (m_tempBuffer != null)
{
DestroyImmediate(m_tempBuffer);
m_tempBuffer = null;
}
m_tempBuffer = new RenderTexture(src.width, src.height, 0, RenderTextureFormat.ARGBFloat);
m_tempBuffer.enableRandomWrite = true;
m_tempBuffer.Create();
}
// validate AABB tree buffer
if (m_aabbTree == null
|| m_aabbTree.count != RayMarchedShape.AabbTreeCapacity)
{
if (m_aabbTree != null)
{
m_aabbTree.Dispose();
m_aabbTree = null;
}
m_aabbTree = new ComputeBuffer(RayMarchedShape.AabbTreeCapacity, AabbTree<RayMarchedShape>.NodePod.Stride);
}
// validate heat map buffer
if (m_heatMap == null
|| m_heatMap.width != src.width
|| m_heatMap.height != src.height)
{
if (m_heatMap != null)
{
DestroyImmediate(m_heatMap);
m_heatMap = null;
}
m_heatMap = new RenderTexture(src.width, src.height, 0, RenderTextureFormat.RFloat);
m_heatMap.enableRandomWrite = true;
m_heatMap.Create();
}
// fill buffers
m_shapes.SetData(sdfShapes);
RayMarchedShape.FillAabbTree(m_aabbTree, AabbTree<RayMarchedShape>.FatBoundsRadius - BlendDistance);
if (m_const.Kernels == null)
{
InitShaderConstants();
}
foreach (int kernel in m_const.Kernels)
{
compute.SetTexture(kernel, m_const.Src, src);
compute.SetTexture(kernel, m_const.Dst, dst);
compute.SetBuffer(kernel, m_const.SdfShapes, m_shapes);
compute.SetTexture(kernel, m_const.TempBuffer, m_tempBuffer);
compute.SetBuffer(kernel, m_const.AabbTree, m_aabbTree);
compute.SetTexture(kernel, m_const.HeatMap, m_heatMap);
}
var camera = GetComponent<Camera>();
compute.SetMatrix(m_const.CameraInverseProjection, camera.projectionMatrix.inverse);
compute.SetMatrix(m_const.CameraToWorld, camera.cameraToWorldMatrix);
compute.SetVector(m_const.CameraPosition, camera.transform.position);
compute.SetInts(m_const.ScreenSize, new int[] { camera.pixelWidth, camera.pixelHeight });
compute.SetInt(m_const.NumSdfShapes, numShapes);
compute.SetVector(m_const.RayMarchParams, new Vector4(MaxRaySteps, RayHitThreshold, MaxRayDistance, Time.time));
compute.SetFloat(m_const.BlendDistance, BlendDistance);
compute.SetVector(m_const.BackgroundColor, new Vector4(BackgroundColor.r, BackgroundColor.g, BackgroundColor.b, BackgroundColor.a));
compute.SetVector(m_const.MissColor, new Vector4(MissColor.r, MissColor.g, MissColor.b, MissColor.a));
compute.SetBool(m_const.UseAabbTree, UseBoundingVolumes);
compute.SetInt(m_const.AabbTreeRoot, RayMarchedShape.AabbTreeRoot);
compute.SetVector(m_const.HeatColorCool, new Vector4(HeatColorCool.r, HeatColorCool.g, HeatColorCool.b, HeatColorCool.a));
compute.SetVector(m_const.HeatColorMedium, new Vector4(HeatColorMedium.r, HeatColorMedium.g, HeatColorMedium.b, HeatColorMedium.a));
compute.SetVector(m_const.HeatColorHot, new Vector4(HeatColorHot.r, HeatColorHot.g, HeatColorHot.b, HeatColorHot.a));
compute.SetFloat(m_const.HeatAlpha, HeatAlpha);
}
protected override void Dispatch(ComputeShader compute, RenderTexture src, RenderTexture dst)
{
var camera = GetComponent<Camera>();
int threadGroupSizeX = (camera.pixelWidth + TileSize - 1) / TileSize;
int threadGroupSizeY = (camera.pixelHeight + TileSize - 1) / TileSize;
compute.Dispatch(m_const.MainKernel, threadGroupSizeX, threadGroupSizeY, 1);
switch (HeatMapMode)
{
case HeatMapModeEnum.StepCountPerThread:
compute.SetInt(m_const.MaxCountBudget, MaxStepCountBudget);
compute.Dispatch(m_const.StepCountKernelPerThread, threadGroupSizeX, threadGroupSizeY, 1);
break;
case HeatMapModeEnum.StepCountPerTile:
compute.SetInt(m_const.MaxCountBudget, MaxStepCountBudget);
compute.Dispatch(m_const.StepCountKernelPerTile, threadGroupSizeX, threadGroupSizeY, 1);
break;
case HeatMapModeEnum.ShapeCountPerThread:
compute.SetInt(m_const.MaxCountBudget, MaxShapeCountBudget);
compute.Dispatch(m_const.ShapeCountKernelPerThread, threadGroupSizeX, threadGroupSizeY, 1);
break;
case HeatMapModeEnum.ShapeCountPerTile:
compute.SetInt(m_const.MaxCountBudget, MaxShapeCountBudget);
compute.Dispatch(m_const.ShapeCountKernelPerTile, threadGroupSizeX, threadGroupSizeY, 1);
break;
}
}
private void OnDrawGizmos()
{
#if UNITY_EDITOR
var camera = GetComponent<Camera>();
if (DrawBoundingVolumes)
{
RayMarchedShape.DrawBoundingVolumeHierarchyGizmos(IsolateBoundingVolumeDepth);
}
if (TestBvhBoundsQuery)
{
Color prevColor = Handles.color;
Aabb queryBounds =
new Aabb
(
camera.transform.position - 0.5f * Vector3.one,
camera.transform.position + 0.5f * Vector3.one
);
Handles.color = Color.yellow;
Handles.DrawWireCube(queryBounds.Center, queryBounds.Extents);
Handles.color = new Color(1.0f, 1.0f, 0.0f, 0.5f);
RayMarchedShape.Query
(
queryBounds,
(RayMarchedShape shape) =>
{
Handles.DrawWireCube(shape.Bounds.Center, shape.Bounds.Extents);
return true;
}
);
Handles.color = prevColor;
}
if (TestBvhRayCast)
{
Color prevColor = Handles.color;
Vector3 cameraFrom = camera.transform.position;
Vector3 cameraTo = cameraFrom + 10.0f * camera.transform.forward;
Handles.color = Color.yellow;
Handles.DrawLine(cameraFrom, cameraTo);
Handles.color = new Color(1.0f, 1.0f, 0.0f, 0.5f);
RayMarchedShape.RayCast
(
cameraFrom,
cameraTo,
(Vector3 from, Vector3 to, RayMarchedShape shape) =>
{
Handles.DrawWireCube(shape.Bounds.Center, shape.Bounds.Extents);
return 1.0f;
}
);
Handles.color = prevColor;
}
#endif
}
}
| 31.720812 | 136 | 0.691791 | [
"MIT"
] | TheAllenChou/unity-ray-marching | unity-ray-marching/Assets/Script/Ray Marching/GameObjectRayMarcher.cs | 12,500 | C# |
//
// Copyright 2012-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 Android.App;
using Android.Webkit;
using Android.OS;
using System.Threading.Tasks;
using Xamarin.Utilities.Android;
using System.Timers;
namespace Xamarin.Auth
{
[Activity (Label = "Web Authenticator")]
#if XAMARIN_AUTH_INTERNAL
internal class WebAuthenticatorActivity : Activity
#else
public class WebAuthenticatorActivity : Activity
#endif
{
WebView webView;
internal class State : Java.Lang.Object
{
public WebAuthenticator Authenticator;
}
internal static readonly ActivityStateRepository<State> StateRepo = new ActivityStateRepository<State> ();
State state;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
//
// Load the state either from a configuration change or from the intent.
//
state = LastNonConfigurationInstance as State;
if (state == null && Intent.HasExtra ("StateKey")) {
var stateKey = Intent.GetStringExtra ("StateKey");
state = StateRepo.Remove (stateKey);
}
if (state == null) {
Finish ();
return;
}
Title = state.Authenticator.Title;
//
// Watch for completion
//
state.Authenticator.Completed += (s, e) => {
SetResult (e.IsAuthenticated ? Result.Ok : Result.Canceled);
Finish ();
};
state.Authenticator.Error += (s, e) => {
if (e.Exception != null) {
this.ShowError ("Authentication Error", e.Exception);
}
else {
this.ShowError ("Authentication Error", e.Message);
}
BeginLoadingInitialUrl ();
};
//
// Build the UI
//
webView = new WebView (this) {
Id = 42,
};
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient (new Client (this));
SetContentView (webView);
//
// Restore the UI state or start over
//
if (savedInstanceState != null) {
webView.RestoreState (savedInstanceState);
}
else {
if (Intent.GetBooleanExtra ("ClearCookies", true))
WebAuthenticator.ClearCookies();
BeginLoadingInitialUrl ();
}
}
void BeginLoadingInitialUrl ()
{
state.Authenticator.GetInitialUrlAsync ().ContinueWith (t => {
if (t.IsFaulted) {
this.ShowError ("Authentication Error", t.Exception);
}
else {
webView.LoadUrl (t.Result.AbsoluteUri);
}
}, TaskScheduler.FromCurrentSynchronizationContext ());
}
public override void OnBackPressed ()
{
state.Authenticator.OnCancelled ();
}
public override Java.Lang.Object OnRetainNonConfigurationInstance ()
{
return state;
}
protected override void OnSaveInstanceState (Bundle outState)
{
base.OnSaveInstanceState (outState);
webView.SaveState (outState);
}
void BeginProgress (string message)
{
webView.Enabled = false;
}
void EndProgress ()
{
webView.Enabled = true;
}
class Client : WebViewClient
{
WebAuthenticatorActivity activity;
public Client (WebAuthenticatorActivity activity)
{
this.activity = activity;
}
public override bool ShouldOverrideUrlLoading (WebView view, string url)
{
return false;
}
public override void OnPageStarted (WebView view, string url, Android.Graphics.Bitmap favicon)
{
var uri = new Uri (url);
activity.state.Authenticator.OnPageLoading (uri);
activity.BeginProgress (uri.Authority);
}
public override void OnPageFinished (WebView view, string url)
{
var uri = new Uri (url);
activity.state.Authenticator.OnPageLoaded (uri);
activity.EndProgress ();
}
}
}
}
| 24.081395 | 108 | 0.683969 | [
"MIT"
] | RepoForks/SalesforceSDK | external/Xamarin.Auth-old-copied-code/src/Xamarin.Auth.Android/WebAuthenticatorActivity.cs | 4,142 | 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("Reign.Input")]
[assembly: AssemblyProduct("Reign.Input")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[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. Only Windows
// assemblies support COM.
[assembly: ComVisible(false)]
// On Windows, the following GUID is for the ID of the typelib if this
// project is exposed to COM. On other platforms, it unique identifies the
// title storage container when deploying this assembly to the device.
[assembly: Guid("a82732fc-51b3-4886-8684-e3ee405a4fe4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
| 38.371429 | 77 | 0.756515 | [
"BSD-2-Clause"
] | reignstudios/ReignSDK | Platforms/Xbox360/Reign.Input/Properties/AssemblyInfo.cs | 1,346 | C# |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir & xuri 2021
//
// 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.
// This file was automatically generated and should not be edited directly.
using System.Runtime.InteropServices;
namespace SharpVk.Multivendor
{
/// <summary>
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct PhysicalDeviceImageRobustnessFeatures
{
/// <summary>
/// </summary>
public bool RobustImageAccess
{
get;
set;
}
/// <summary>
/// </summary>
/// <param name="pointer">
/// </param>
internal unsafe void MarshalTo(SharpVk.Interop.Multivendor.PhysicalDeviceImageRobustnessFeatures* pointer)
{
pointer->SType = StructureType.PhysicalDeviceImageRobustnessFeatures;
pointer->Next = null;
pointer->RobustImageAccess = RobustImageAccess;
}
/// <summary>
/// </summary>
/// <param name="pointer">
/// </param>
internal static unsafe PhysicalDeviceImageRobustnessFeatures MarshalFrom(SharpVk.Interop.Multivendor.PhysicalDeviceImageRobustnessFeatures* pointer)
{
PhysicalDeviceImageRobustnessFeatures result = default;
result.RobustImageAccess = pointer->RobustImageAccess;
return result;
}
}
}
| 38.015385 | 156 | 0.679887 | [
"MIT"
] | xuri02/SharpVk | src/SharpVk/Multivendor/PhysicalDeviceImageRobustnessFeatures.gen.cs | 2,471 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.Utilities.CloudService
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;
using Commands.Common.Properties;
internal static class JavaScriptPackageHelpers
{
/// <summary>
/// Ensure that a package.json file is available in the given directory, if not create it.
/// </summary>
/// <param name="directoryPath">fully qualified path to the directory to search</param>
/// <returns>True if package.json exists and is readable, false otherwise</returns>
internal static bool EnsurePackageJsonExists(string directoryPath, string applicationName = "")
{
string fileName = Path.Combine(directoryPath, Resources.PackageJsonFileName);
if (!File.Exists(fileName))
{
File.WriteAllText(fileName, string.Format(Resources.PackageJsonDefaultFile, applicationName));
}
return File.Exists(fileName);
}
/// <summary>
/// Get the version specifiction for the given engine, if any
/// </summary>
/// <param name="directoryPath">fully qualified path to the directory to search</param>
/// <param name="engineName">The name of the engine to specify</param>
/// <param name="version">The version specified in package.json, if any, or null otherwise</param>
/// <returns>True if we retrieved a valid engine version, false otherwise</returns>
internal static bool TryGetEngineVersion(string directoryPath, string engineName, out string version)
{
version = null;
Dictionary<string, object> contents;
if (TryGetContents(directoryPath, out contents))
{
return TryGetEngineVersionFromJson(contents, engineName, out version);
}
return false;
}
/// <summary>
/// Get the version specifiction for the given engine, if any
/// </summary>
/// <param name="directoryPath">fully qualified path to the directory to search</param>
/// <param name="engineName">The name of the engine to specify</param>
/// <param name="version">The version to set in package.json.</param>
/// <returns>True if we successfully set the engine version, false otherwise</returns>
internal static bool TrySetEngineVersion(string directoryPath, string engineName, string version)
{
Dictionary<string, object> contents;
if (TryGetContents(directoryPath, out contents))
{
SetEngineVersionInJson(contents, engineName, version);
SetContents(directoryPath, contents);
return true;
}
return false;
}
/// <summary>
/// Deserialize the contents of package.json in the given directory
/// </summary>
/// <param name="directoryPath">fully qualified path to the directory to search</param>
/// <param name="contents">The contents of the file, represented as a dictionary</param>
/// <returns>True if we successfully read the file, false otherwise</returns>
private static bool TryGetContents(string directoryPath, out Dictionary<string, object> contents)
{
contents = null;
string fileName = Path.Combine(directoryPath, Resources.PackageJsonFileName);
try
{
using (StreamReader reader = new StreamReader(fileName))
{
string jsonString = reader.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
contents = js.Deserialize<Dictionary<string, object>>(jsonString);
}
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Write the given JavaScript object in dictionaroy representation out to package.json
/// </summary>
/// <param name="contents">The JavaScript object in dictionary representation</param>
static void SetContents(string directoryPath, Dictionary<string, object> contents)
{
string fileName = Path.Combine(directoryPath, Resources.PackageJsonFileName);
using (StreamWriter writer = new StreamWriter(fileName, false))
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
writer.Write(serializer.Serialize(contents));
writer.Flush();
}
}
/// <summary>
/// Try to get the value of a property from a JavaScript object represented as a dictionary
/// use case-insensitive matching and coerce the return type as appropriate
/// </summary>
/// <param name="store">The JavaScript object in dictionary representation</param>
/// <param name="searchKey">The property name to find</param>
/// <param name="value">The out variable to return the value stored in the object</param>
/// <returns>True if the property is successfully found, false otherwise</returns>
static bool TryGetValue<T>(Dictionary<string, object> store, string searchKey, out T value) where T : class
{
value = null;
foreach (string key in store.Keys)
{
if (string.Equals(key, searchKey, StringComparison.OrdinalIgnoreCase))
{
value = store[key] as T;
return value != null;
}
}
return false;
}
/// <summary>
/// Try to set the value of a property in a JavaScript object represented as a dictionary
/// use case-insensitive matching
/// </summary>
/// <param name="store">The JavaScript object in dictionary representation</param>
/// <param name="searchKey">The property name to find</param>
/// <param name="value">The out variable to return the value stored in the object</param>
/// <returns>True if the property is successfully found, false otherwise</returns>
static void SetValue<T>(Dictionary<string, object> store, string searchKey, T value) where T : class
{
foreach (string key in store.Keys)
{
if (string.Equals(key, searchKey, StringComparison.OrdinalIgnoreCase))
{
store[key] = value;
return;
}
}
store[searchKey] = value;
}
/// <summary>
/// Try to get the engines section from a package.json object
/// use case-insensitive matching and coerce the return type as appropriate
/// </summary>
/// <param name="store">The JavaScript object in dictionary representation</param>
/// <param name="engines">The out variable to return the engines section as a dictionary</param>
/// <returns>True if the property is successfully found, false otherwise</returns>
private static bool TryGetEnginesSection(Dictionary<string, object> store, out Dictionary<string, object> engines)
{
return TryGetValue<Dictionary<string, object>>(store, Resources.JsonEnginesSectionName, out engines);
}
/// <summary>
/// Try to get the engine version specification from the given package.json object (represented
/// as a dictionary)
/// </summary>
/// <param name="store">The JavaScript object in dictionary representation</param>
/// <param name="searchKey">The property name of the engine version to find</param>
/// <param name="value">The out variable to return the value stored in the object</param>
/// <returns>True if the property is successfully found, false otherwise</returns>
static bool TryGetEngineVersionFromJson(Dictionary<string, object> store, string engineKey, out string engineVersion)
{
engineVersion = null;
Dictionary<string, object> engines;
if (TryGetEnginesSection(store, out engines))
{
return TryGetValue<string>(engines, engineKey, out engineVersion) && ISValidVersion(engineVersion);
}
return false;
}
/// <summary>
/// Determine if the version contained in a package.json is a real version value
/// </summary>
/// <param name="version">The version to check</param>
/// <returns>true if a valid 3-part version, otherwise false</returns>
static bool ISValidVersion(string version)
{
if (!string.IsNullOrEmpty(version))
{
string[] versions = version.Split('.');
return versions != null && versions.Length == 3;
}
return false;
}
/// <summary>
/// Try to get the engine version specification from the given package.json object (represented
/// as a dictionary)
/// </summary>
/// <param name="store">The JavaScript object in dictionary representation</param>
/// <param name="searchKey">The property name of the engine version to find</param>
/// <param name="value">The version value to store in the object for the engine given</param>
/// <returns>True if the property is successfully set, false otherwise</returns>
static void SetEngineVersionInJson(Dictionary<string, object> store, string engineKey, string engineVersion)
{
Dictionary<string, object> engines;
if (!TryGetEnginesSection(store, out engines))
{
engines = new Dictionary<string, object>();
store[Resources.JsonEnginesSectionName] = engines;
}
SetValue<string>(engines, engineKey, engineVersion);
}
}
}
| 46.755274 | 126 | 0.592817 | [
"MIT"
] | Milstein/azure-sdk-tools | WindowsAzurePowershell/src/Common/CloudService/JavaScriptPackageHelpers.cs | 10,847 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Compute
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Compute Client
/// </summary>
public partial class ComputeManagementClient : ServiceClient<ComputeManagementClient>, IComputeManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// The preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// The retry timeout in seconds for Long Running Operations. Default value is
/// 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// Whether a unique x-ms-client-request-id should be generated. When set to
/// true a unique x-ms-client-request-id value is generated and included in
/// each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IOperations.
/// </summary>
public virtual IOperations Operations { get; private set; }
/// <summary>
/// Gets the IAvailabilitySetsOperations.
/// </summary>
public virtual IAvailabilitySetsOperations AvailabilitySets { get; private set; }
/// <summary>
/// Gets the IProximityPlacementGroupsOperations.
/// </summary>
public virtual IProximityPlacementGroupsOperations ProximityPlacementGroups { get; private set; }
/// <summary>
/// Gets the IDedicatedHostGroupsOperations.
/// </summary>
public virtual IDedicatedHostGroupsOperations DedicatedHostGroups { get; private set; }
/// <summary>
/// Gets the IDedicatedHostsOperations.
/// </summary>
public virtual IDedicatedHostsOperations DedicatedHosts { get; private set; }
/// <summary>
/// Gets the IVirtualMachineExtensionImagesOperations.
/// </summary>
public virtual IVirtualMachineExtensionImagesOperations VirtualMachineExtensionImages { get; private set; }
/// <summary>
/// Gets the IVirtualMachineExtensionsOperations.
/// </summary>
public virtual IVirtualMachineExtensionsOperations VirtualMachineExtensions { get; private set; }
/// <summary>
/// Gets the IVirtualMachineImagesOperations.
/// </summary>
public virtual IVirtualMachineImagesOperations VirtualMachineImages { get; private set; }
/// <summary>
/// Gets the IUsageOperations.
/// </summary>
public virtual IUsageOperations Usage { get; private set; }
/// <summary>
/// Gets the IVirtualMachinesOperations.
/// </summary>
public virtual IVirtualMachinesOperations VirtualMachines { get; private set; }
/// <summary>
/// Gets the IVirtualMachineSizesOperations.
/// </summary>
public virtual IVirtualMachineSizesOperations VirtualMachineSizes { get; private set; }
/// <summary>
/// Gets the IImagesOperations.
/// </summary>
public virtual IImagesOperations Images { get; private set; }
/// <summary>
/// Gets the IVirtualMachineScaleSetsOperations.
/// </summary>
public virtual IVirtualMachineScaleSetsOperations VirtualMachineScaleSets { get; private set; }
/// <summary>
/// Gets the IVirtualMachineScaleSetExtensionsOperations.
/// </summary>
public virtual IVirtualMachineScaleSetExtensionsOperations VirtualMachineScaleSetExtensions { get; private set; }
/// <summary>
/// Gets the IVirtualMachineScaleSetRollingUpgradesOperations.
/// </summary>
public virtual IVirtualMachineScaleSetRollingUpgradesOperations VirtualMachineScaleSetRollingUpgrades { get; private set; }
/// <summary>
/// Gets the IVirtualMachineScaleSetVMExtensionsOperations.
/// </summary>
public virtual IVirtualMachineScaleSetVMExtensionsOperations VirtualMachineScaleSetVMExtensions { get; private set; }
/// <summary>
/// Gets the IVirtualMachineScaleSetVMsOperations.
/// </summary>
public virtual IVirtualMachineScaleSetVMsOperations VirtualMachineScaleSetVMs { get; private set; }
/// <summary>
/// Gets the ILogAnalyticsOperations.
/// </summary>
public virtual ILogAnalyticsOperations LogAnalytics { get; private set; }
/// <summary>
/// Gets the IVirtualMachineRunCommandsOperations.
/// </summary>
public virtual IVirtualMachineRunCommandsOperations VirtualMachineRunCommands { get; private set; }
/// <summary>
/// Gets the IResourceSkusOperations.
/// </summary>
public virtual IResourceSkusOperations ResourceSkus { get; private set; }
/// <summary>
/// Gets the IDisksOperations.
/// </summary>
public virtual IDisksOperations Disks { get; private set; }
/// <summary>
/// Gets the ISnapshotsOperations.
/// </summary>
public virtual ISnapshotsOperations Snapshots { get; private set; }
/// <summary>
/// Gets the IDiskEncryptionSetsOperations.
/// </summary>
public virtual IDiskEncryptionSetsOperations DiskEncryptionSets { get; private set; }
/// <summary>
/// Gets the IGalleriesOperations.
/// </summary>
public virtual IGalleriesOperations Galleries { get; private set; }
/// <summary>
/// Gets the IGalleryImagesOperations.
/// </summary>
public virtual IGalleryImagesOperations GalleryImages { get; private set; }
/// <summary>
/// Gets the IGalleryImageVersionsOperations.
/// </summary>
public virtual IGalleryImageVersionsOperations GalleryImageVersions { get; private set; }
/// <summary>
/// Gets the IGalleryApplicationsOperations.
/// </summary>
public virtual IGalleryApplicationsOperations GalleryApplications { get; private set; }
/// <summary>
/// Gets the IGalleryApplicationVersionsOperations.
/// </summary>
public virtual IGalleryApplicationVersionsOperations GalleryApplicationVersions { get; private set; }
/// <summary>
/// Gets the IContainerServicesOperations.
/// </summary>
public virtual IContainerServicesOperations ContainerServices { get; private set; }
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling ComputeManagementClient.Dispose(). False: will not dispose provided httpClient</param>
protected ComputeManagementClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ComputeManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ComputeManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected ComputeManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected ComputeManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ComputeManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling ComputeManagementClient.Dispose(). False: will not dispose provided httpClient</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ComputeManagementClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ComputeManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ComputeManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ComputeManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ComputeManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Operations = new Operations(this);
AvailabilitySets = new AvailabilitySetsOperations(this);
ProximityPlacementGroups = new ProximityPlacementGroupsOperations(this);
DedicatedHostGroups = new DedicatedHostGroupsOperations(this);
DedicatedHosts = new DedicatedHostsOperations(this);
VirtualMachineExtensionImages = new VirtualMachineExtensionImagesOperations(this);
VirtualMachineExtensions = new VirtualMachineExtensionsOperations(this);
VirtualMachineImages = new VirtualMachineImagesOperations(this);
Usage = new UsageOperations(this);
VirtualMachines = new VirtualMachinesOperations(this);
VirtualMachineSizes = new VirtualMachineSizesOperations(this);
Images = new ImagesOperations(this);
VirtualMachineScaleSets = new VirtualMachineScaleSetsOperations(this);
VirtualMachineScaleSetExtensions = new VirtualMachineScaleSetExtensionsOperations(this);
VirtualMachineScaleSetRollingUpgrades = new VirtualMachineScaleSetRollingUpgradesOperations(this);
VirtualMachineScaleSetVMExtensions = new VirtualMachineScaleSetVMExtensionsOperations(this);
VirtualMachineScaleSetVMs = new VirtualMachineScaleSetVMsOperations(this);
LogAnalytics = new LogAnalyticsOperations(this);
VirtualMachineRunCommands = new VirtualMachineRunCommandsOperations(this);
ResourceSkus = new ResourceSkusOperations(this);
Disks = new DisksOperations(this);
Snapshots = new SnapshotsOperations(this);
DiskEncryptionSets = new DiskEncryptionSetsOperations(this);
Galleries = new GalleriesOperations(this);
GalleryImages = new GalleryImagesOperations(this);
GalleryImageVersions = new GalleryImageVersionsOperations(this);
GalleryApplications = new GalleryApplicationsOperations(this);
GalleryApplicationVersions = new GalleryApplicationVersionsOperations(this);
ContainerServices = new ContainerServicesOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| 41.601905 | 194 | 0.615814 | [
"MIT"
] | Azkel/azure-sdk-for-net | sdk/compute/Microsoft.Azure.Management.Compute/src/Generated/ComputeManagementClient.cs | 21,841 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Generation date: 10/4/2020 2:24:13 PM
namespace Microsoft.Dynamics.DataEntities
{
/// <summary>
/// There are no comments for RetailReplenishmentRuleLineSingle in the schema.
/// </summary>
public partial class RetailReplenishmentRuleLineSingle : global::Microsoft.OData.Client.DataServiceQuerySingle<RetailReplenishmentRuleLine>
{
/// <summary>
/// Initialize a new RetailReplenishmentRuleLineSingle object.
/// </summary>
public RetailReplenishmentRuleLineSingle(global::Microsoft.OData.Client.DataServiceContext context, string path)
: base(context, path) {}
/// <summary>
/// Initialize a new RetailReplenishmentRuleLineSingle object.
/// </summary>
public RetailReplenishmentRuleLineSingle(global::Microsoft.OData.Client.DataServiceContext context, string path, bool isComposable)
: base(context, path, isComposable) {}
/// <summary>
/// Initialize a new RetailReplenishmentRuleLineSingle object.
/// </summary>
public RetailReplenishmentRuleLineSingle(global::Microsoft.OData.Client.DataServiceQuerySingle<RetailReplenishmentRuleLine> query)
: base(query) {}
/// <summary>
/// There are no comments for RetailChannel in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.Dynamics.DataEntities.RetailChannelSingle RetailChannel
{
get
{
if (!this.IsComposable)
{
throw new global::System.NotSupportedException("The previous function is not composable.");
}
if ((this._RetailChannel == null))
{
this._RetailChannel = new global::Microsoft.Dynamics.DataEntities.RetailChannelSingle(this.Context, GetPath("RetailChannel"));
}
return this._RetailChannel;
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.RetailChannelSingle _RetailChannel;
/// <summary>
/// There are no comments for OrganizationHierarchyType in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.Dynamics.DataEntities.OrganizationHierarchyTypeSingle OrganizationHierarchyType
{
get
{
if (!this.IsComposable)
{
throw new global::System.NotSupportedException("The previous function is not composable.");
}
if ((this._OrganizationHierarchyType == null))
{
this._OrganizationHierarchyType = new global::Microsoft.Dynamics.DataEntities.OrganizationHierarchyTypeSingle(this.Context, GetPath("OrganizationHierarchyType"));
}
return this._OrganizationHierarchyType;
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.OrganizationHierarchyTypeSingle _OrganizationHierarchyType;
}
/// <summary>
/// There are no comments for RetailReplenishmentRuleLine in the schema.
/// </summary>
/// <KeyProperties>
/// dataAreaId
/// ReplenishmentRule
/// Type
/// ReplenishmentHierarchyTypeName
/// ReplenishmentOrganizationPartyNumber
/// ReplenishmentHierarchyValidFrom
/// ReplenishmentHierarchyValidTo
/// RetailChannelId
/// </KeyProperties>
[global::Microsoft.OData.Client.Key("dataAreaId", "ReplenishmentRule", "Type", "ReplenishmentHierarchyTypeName", "ReplenishmentOrganizationPartyNumber", "ReplenishmentHierarchyValidFrom", "ReplenishmentHierarchyValidTo", "RetailChannelId")]
[global::Microsoft.OData.Client.EntitySet("RetailReplenishmentRuleLines")]
public partial class RetailReplenishmentRuleLine : global::Microsoft.OData.Client.BaseEntityType, global::System.ComponentModel.INotifyPropertyChanged
{
/// <summary>
/// Create a new RetailReplenishmentRuleLine object.
/// </summary>
/// <param name="dataAreaId">Initial value of dataAreaId.</param>
/// <param name="replenishmentRule">Initial value of ReplenishmentRule.</param>
/// <param name="replenishmentHierarchyTypeName">Initial value of ReplenishmentHierarchyTypeName.</param>
/// <param name="replenishmentOrganizationPartyNumber">Initial value of ReplenishmentOrganizationPartyNumber.</param>
/// <param name="replenishmentHierarchyValidFrom">Initial value of ReplenishmentHierarchyValidFrom.</param>
/// <param name="replenishmentHierarchyValidTo">Initial value of ReplenishmentHierarchyValidTo.</param>
/// <param name="retailChannelId">Initial value of RetailChannelId.</param>
/// <param name="defaultWeight">Initial value of DefaultWeight.</param>
/// <param name="percent">Initial value of Percent.</param>
/// <param name="weight">Initial value of Weight.</param>
/// <param name="defaultPercent">Initial value of DefaultPercent.</param>
/// <param name="organizationHierarchyType">Initial value of OrganizationHierarchyType.</param>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public static RetailReplenishmentRuleLine CreateRetailReplenishmentRuleLine(string dataAreaId,
string replenishmentRule,
string replenishmentHierarchyTypeName,
string replenishmentOrganizationPartyNumber,
global::System.DateTimeOffset replenishmentHierarchyValidFrom,
global::System.DateTimeOffset replenishmentHierarchyValidTo,
string retailChannelId,
decimal defaultWeight,
decimal percent,
decimal weight,
decimal defaultPercent,
global::Microsoft.Dynamics.DataEntities.OrganizationHierarchyType organizationHierarchyType)
{
RetailReplenishmentRuleLine retailReplenishmentRuleLine = new RetailReplenishmentRuleLine();
retailReplenishmentRuleLine.dataAreaId = dataAreaId;
retailReplenishmentRuleLine.ReplenishmentRule = replenishmentRule;
retailReplenishmentRuleLine.ReplenishmentHierarchyTypeName = replenishmentHierarchyTypeName;
retailReplenishmentRuleLine.ReplenishmentOrganizationPartyNumber = replenishmentOrganizationPartyNumber;
retailReplenishmentRuleLine.ReplenishmentHierarchyValidFrom = replenishmentHierarchyValidFrom;
retailReplenishmentRuleLine.ReplenishmentHierarchyValidTo = replenishmentHierarchyValidTo;
retailReplenishmentRuleLine.RetailChannelId = retailChannelId;
retailReplenishmentRuleLine.DefaultWeight = defaultWeight;
retailReplenishmentRuleLine.Percent = percent;
retailReplenishmentRuleLine.Weight = weight;
retailReplenishmentRuleLine.DefaultPercent = defaultPercent;
if ((organizationHierarchyType == null))
{
throw new global::System.ArgumentNullException("organizationHierarchyType");
}
retailReplenishmentRuleLine.OrganizationHierarchyType = organizationHierarchyType;
return retailReplenishmentRuleLine;
}
/// <summary>
/// There are no comments for Property dataAreaId in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string dataAreaId
{
get
{
return this._dataAreaId;
}
set
{
this.OndataAreaIdChanging(value);
this._dataAreaId = value;
this.OndataAreaIdChanged();
this.OnPropertyChanged("dataAreaId");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _dataAreaId;
partial void OndataAreaIdChanging(string value);
partial void OndataAreaIdChanged();
/// <summary>
/// There are no comments for Property ReplenishmentRule in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string ReplenishmentRule
{
get
{
return this._ReplenishmentRule;
}
set
{
this.OnReplenishmentRuleChanging(value);
this._ReplenishmentRule = value;
this.OnReplenishmentRuleChanged();
this.OnPropertyChanged("ReplenishmentRule");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _ReplenishmentRule;
partial void OnReplenishmentRuleChanging(string value);
partial void OnReplenishmentRuleChanged();
/// <summary>
/// There are no comments for Property Type in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.Nullable<global::Microsoft.Dynamics.DataEntities.RetailReplenishmentRuleType> Type
{
get
{
return this._Type;
}
set
{
this.OnTypeChanging(value);
this._Type = value;
this.OnTypeChanged();
this.OnPropertyChanged("Type");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.Nullable<global::Microsoft.Dynamics.DataEntities.RetailReplenishmentRuleType> _Type;
partial void OnTypeChanging(global::System.Nullable<global::Microsoft.Dynamics.DataEntities.RetailReplenishmentRuleType> value);
partial void OnTypeChanged();
/// <summary>
/// There are no comments for Property ReplenishmentHierarchyTypeName in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string ReplenishmentHierarchyTypeName
{
get
{
return this._ReplenishmentHierarchyTypeName;
}
set
{
this.OnReplenishmentHierarchyTypeNameChanging(value);
this._ReplenishmentHierarchyTypeName = value;
this.OnReplenishmentHierarchyTypeNameChanged();
this.OnPropertyChanged("ReplenishmentHierarchyTypeName");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _ReplenishmentHierarchyTypeName;
partial void OnReplenishmentHierarchyTypeNameChanging(string value);
partial void OnReplenishmentHierarchyTypeNameChanged();
/// <summary>
/// There are no comments for Property ReplenishmentOrganizationPartyNumber in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string ReplenishmentOrganizationPartyNumber
{
get
{
return this._ReplenishmentOrganizationPartyNumber;
}
set
{
this.OnReplenishmentOrganizationPartyNumberChanging(value);
this._ReplenishmentOrganizationPartyNumber = value;
this.OnReplenishmentOrganizationPartyNumberChanged();
this.OnPropertyChanged("ReplenishmentOrganizationPartyNumber");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _ReplenishmentOrganizationPartyNumber;
partial void OnReplenishmentOrganizationPartyNumberChanging(string value);
partial void OnReplenishmentOrganizationPartyNumberChanged();
/// <summary>
/// There are no comments for Property ReplenishmentHierarchyValidFrom in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.DateTimeOffset ReplenishmentHierarchyValidFrom
{
get
{
return this._ReplenishmentHierarchyValidFrom;
}
set
{
this.OnReplenishmentHierarchyValidFromChanging(value);
this._ReplenishmentHierarchyValidFrom = value;
this.OnReplenishmentHierarchyValidFromChanged();
this.OnPropertyChanged("ReplenishmentHierarchyValidFrom");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.DateTimeOffset _ReplenishmentHierarchyValidFrom;
partial void OnReplenishmentHierarchyValidFromChanging(global::System.DateTimeOffset value);
partial void OnReplenishmentHierarchyValidFromChanged();
/// <summary>
/// There are no comments for Property ReplenishmentHierarchyValidTo in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.DateTimeOffset ReplenishmentHierarchyValidTo
{
get
{
return this._ReplenishmentHierarchyValidTo;
}
set
{
this.OnReplenishmentHierarchyValidToChanging(value);
this._ReplenishmentHierarchyValidTo = value;
this.OnReplenishmentHierarchyValidToChanged();
this.OnPropertyChanged("ReplenishmentHierarchyValidTo");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.DateTimeOffset _ReplenishmentHierarchyValidTo;
partial void OnReplenishmentHierarchyValidToChanging(global::System.DateTimeOffset value);
partial void OnReplenishmentHierarchyValidToChanged();
/// <summary>
/// There are no comments for Property RetailChannelId in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string RetailChannelId
{
get
{
return this._RetailChannelId;
}
set
{
this.OnRetailChannelIdChanging(value);
this._RetailChannelId = value;
this.OnRetailChannelIdChanged();
this.OnPropertyChanged("RetailChannelId");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _RetailChannelId;
partial void OnRetailChannelIdChanging(string value);
partial void OnRetailChannelIdChanged();
/// <summary>
/// There are no comments for Property DefaultWeight in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual decimal DefaultWeight
{
get
{
return this._DefaultWeight;
}
set
{
this.OnDefaultWeightChanging(value);
this._DefaultWeight = value;
this.OnDefaultWeightChanged();
this.OnPropertyChanged("DefaultWeight");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private decimal _DefaultWeight;
partial void OnDefaultWeightChanging(decimal value);
partial void OnDefaultWeightChanged();
/// <summary>
/// There are no comments for Property Percent in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual decimal Percent
{
get
{
return this._Percent;
}
set
{
this.OnPercentChanging(value);
this._Percent = value;
this.OnPercentChanged();
this.OnPropertyChanged("Percent");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private decimal _Percent;
partial void OnPercentChanging(decimal value);
partial void OnPercentChanged();
/// <summary>
/// There are no comments for Property Weight in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual decimal Weight
{
get
{
return this._Weight;
}
set
{
this.OnWeightChanging(value);
this._Weight = value;
this.OnWeightChanged();
this.OnPropertyChanged("Weight");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private decimal _Weight;
partial void OnWeightChanging(decimal value);
partial void OnWeightChanged();
/// <summary>
/// There are no comments for Property Description in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string Description
{
get
{
return this._Description;
}
set
{
this.OnDescriptionChanging(value);
this._Description = value;
this.OnDescriptionChanged();
this.OnPropertyChanged("Description");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _Description;
partial void OnDescriptionChanging(string value);
partial void OnDescriptionChanged();
/// <summary>
/// There are no comments for Property DefaultPercent in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual decimal DefaultPercent
{
get
{
return this._DefaultPercent;
}
set
{
this.OnDefaultPercentChanging(value);
this._DefaultPercent = value;
this.OnDefaultPercentChanged();
this.OnPropertyChanged("DefaultPercent");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private decimal _DefaultPercent;
partial void OnDefaultPercentChanging(decimal value);
partial void OnDefaultPercentChanged();
/// <summary>
/// There are no comments for Property RetailChannel in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.Dynamics.DataEntities.RetailChannel RetailChannel
{
get
{
return this._RetailChannel;
}
set
{
this.OnRetailChannelChanging(value);
this._RetailChannel = value;
this.OnRetailChannelChanged();
this.OnPropertyChanged("RetailChannel");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.RetailChannel _RetailChannel;
partial void OnRetailChannelChanging(global::Microsoft.Dynamics.DataEntities.RetailChannel value);
partial void OnRetailChannelChanged();
/// <summary>
/// There are no comments for Property OrganizationHierarchyType in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.Dynamics.DataEntities.OrganizationHierarchyType OrganizationHierarchyType
{
get
{
return this._OrganizationHierarchyType;
}
set
{
this.OnOrganizationHierarchyTypeChanging(value);
this._OrganizationHierarchyType = value;
this.OnOrganizationHierarchyTypeChanged();
this.OnPropertyChanged("OrganizationHierarchyType");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.OrganizationHierarchyType _OrganizationHierarchyType;
partial void OnOrganizationHierarchyTypeChanging(global::Microsoft.Dynamics.DataEntities.OrganizationHierarchyType value);
partial void OnOrganizationHierarchyTypeChanged();
/// <summary>
/// This event is raised when the value of the property is changed
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// The value of the property is changed
/// </summary>
/// <param name="property">property name</param>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
protected virtual void OnPropertyChanged(string property)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new global::System.ComponentModel.PropertyChangedEventArgs(property));
}
}
}
}
| 48.767206 | 244 | 0.636047 | [
"MIT"
] | NathanClouseAX/AAXDataEntityPerfTest | Projects/AAXDataEntityPerfTest/ConsoleApp1/Connected Services/D365/RetailReplenishmentRuleLine.cs | 24,093 | C# |
// Copyright 2016-2019, Pulumi Corporation
namespace Pulumi
{
/// <summary>
/// Options to help control the behavior of <see cref="IDeployment.InvokeAsync{T}(string,
/// ResourceArgs, InvokeOptions)"/>.
/// </summary>
public class InvokeOptions
{
/// <summary>
/// An optional parent to use for default options for this invoke (e.g. the default provider
/// to use).
/// </summary>
public Resource? Parent { get; set; }
/// <summary>
/// An optional provider to use for this invocation. If no provider is supplied, the default
/// provider for the invoked function's package will be used.
/// </summary>
public ProviderResource? Provider { get; set; }
/// <summary>
/// An optional version, corresponding to the version of the provider plugin that should be
/// used when performing this invoke.
/// </summary>
public string? Version { get; set; }
}
}
| 33.466667 | 100 | 0.603586 | [
"Apache-2.0"
] | geekflyer/pulumi | sdk/dotnet/Pulumi/Deployment/InvokeOptions.cs | 1,006 | C# |
// ReSharper disable InconsistentNaming
using System.Collections.Generic;
using System;
using System.Threading.Tasks;
using EasyNetQ.AutoSubscribe;
using EasyNetQ.Tests.Mocking;
using NUnit.Framework;
using RabbitMQ.Client;
using Rhino.Mocks;
namespace EasyNetQ.Tests.AutoSubscriberTests
{
[TestFixture]
public class When_autosubscribing
{
private MockBuilder mockBuilder;
private const string expectedQueueName1 =
"EasyNetQ.Tests.AutoSubscriberTests.When_autosubscribing+MessageA:EasyNetQ.Tests_my_app:d7617d39b90b6b695b90c630539a12e2";
private const string expectedQueueName2 =
"EasyNetQ.Tests.AutoSubscriberTests.When_autosubscribing+MessageB:EasyNetQ.Tests_MyExplicitId";
private const string expectedQueueName3 =
"EasyNetQ.Tests.AutoSubscriberTests.When_autosubscribing+MessageC:EasyNetQ.Tests_my_app:8b7980aa5e42959b4202e32ee442fc52";
[SetUp]
public void SetUp()
{
mockBuilder = new MockBuilder();
// mockBuilder = new MockBuilder(x => x.Register<IEasyNetQLogger, ConsoleLogger>());
var autoSubscriber = new AutoSubscriber(mockBuilder.Bus, "my_app");
autoSubscriber.Subscribe(typeof(MyAsyncConsumer), typeof(MyConsumer), typeof(MyGenericAbstractConsumer<>));
}
[Test]
public void Should_have_declared_the_queues()
{
Action<string> assertQueueDeclared = queueName =>
mockBuilder.Channels[0].AssertWasCalled(x => x.QueueDeclare(
Arg<string>.Is.Equal(queueName),
Arg<bool>.Is.Equal(true),
Arg<bool>.Is.Equal(false),
Arg<bool>.Is.Equal(false),
Arg<IDictionary<string, object>>.Is.Anything
));
assertQueueDeclared(expectedQueueName1);
assertQueueDeclared(expectedQueueName2);
assertQueueDeclared(expectedQueueName3);
}
[Test]
public void Should_have_bound_to_queues()
{
Action<int, string, string> assertConsumerStarted = (channelIndex, queueName, topicName) =>
mockBuilder.Channels[0].AssertWasCalled(x =>
x.QueueBind(
Arg<string>.Is.Equal(queueName),
Arg<string>.Is.Anything,
Arg<string>.Is.Equal(topicName))
);
assertConsumerStarted(1, expectedQueueName1, "#");
assertConsumerStarted(2, expectedQueueName2, "#");
assertConsumerStarted(3, expectedQueueName3, "Important");
}
[Test]
public void Should_have_started_consuming_from_the_correct_queues()
{
mockBuilder.ConsumerQueueNames.Contains(expectedQueueName1).ShouldBeTrue();
mockBuilder.ConsumerQueueNames.Contains(expectedQueueName2).ShouldBeTrue();
mockBuilder.ConsumerQueueNames.Contains(expectedQueueName3).ShouldBeTrue();
}
// Discovered by reflection over test assembly, do not remove.
private class MyConsumer : IConsume<MessageA>, IConsume<MessageB>, IConsume<MessageC>
{
public void Consume(MessageA message)
{
}
[AutoSubscriberConsumer(SubscriptionId = "MyExplicitId")]
public void Consume(MessageB message)
{
}
[ForTopicAttribute("Important")]
public void Consume(MessageC message)
{
}
}
//Discovered by reflection over test assembly, do not remove.
private class MyAsyncConsumer : IConsumeAsync<MessageA>, IConsumeAsync<MessageB>, IConsumeAsync<MessageC>
{
public Task Consume(MessageA message)
{
throw new NotImplementedException();
}
[AutoSubscriberConsumer(SubscriptionId = "MyExplicitId")]
public Task Consume(MessageB message)
{
throw new NotImplementedException();
}
public Task Consume(MessageC message)
{
throw new NotImplementedException();
}
}
//Discovered by reflection over test assembly, do not remove.
private abstract class MyGenericAbstractConsumer<TMessage> : IConsume<TMessage>
where TMessage : class
{
public virtual void Consume(TMessage message)
{
throw new NotImplementedException();
}
}
private class MessageA
{
public string Text { get; set; }
}
private class MessageB
{
public string Text { get; set; }
}
private class MessageC
{
public string Text { get; set; }
}
}
}
// ReSharper restore InconsistentNaming | 34.945578 | 134 | 0.584777 | [
"MIT"
] | CrimpyMcDoogles/EasyNetQ | Source/EasyNetQ.Tests/AutoSubscriberTests/When_autosubscribing.cs | 5,139 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.Editor
{
internal class NavigationBarSelectedTypeAndMember : IEquatable<NavigationBarSelectedTypeAndMember>
{
public static readonly NavigationBarSelectedTypeAndMember Empty = new(typeItem: null, memberItem: null);
public NavigationBarItem? TypeItem { get; }
public bool ShowTypeItemGrayed { get; }
public NavigationBarItem? MemberItem { get; }
public bool ShowMemberItemGrayed { get; }
public NavigationBarSelectedTypeAndMember(NavigationBarItem? typeItem, NavigationBarItem? memberItem)
: this(typeItem, showTypeItemGrayed: false, memberItem, showMemberItemGrayed: false)
{
}
public NavigationBarSelectedTypeAndMember(
NavigationBarItem? typeItem,
bool showTypeItemGrayed,
NavigationBarItem? memberItem,
bool showMemberItemGrayed)
{
TypeItem = typeItem;
MemberItem = memberItem;
ShowTypeItemGrayed = showTypeItemGrayed;
ShowMemberItemGrayed = showMemberItemGrayed;
}
public override bool Equals(object? obj)
=> Equals(obj as NavigationBarSelectedTypeAndMember);
public bool Equals(NavigationBarSelectedTypeAndMember? other)
=> other != null &&
this.ShowTypeItemGrayed == other.ShowTypeItemGrayed &&
this.ShowMemberItemGrayed == other.ShowMemberItemGrayed &&
Equals(this.TypeItem, other.TypeItem) &&
Equals(this.MemberItem, other.MemberItem);
public override int GetHashCode()
=> throw new NotImplementedException();
}
}
| 38.959184 | 112 | 0.675223 | [
"MIT"
] | AlexanderSemenyak/roslyn | src/EditorFeatures/Core/Extensibility/NavigationBar/NavigationBarSelectedItems.cs | 1,911 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Extensions.Logging;
using Tehk.Sourcers.Meetup.Svc.Models;
namespace Tehk.Sourcers.Meetup.Svc.Services
{
public class MeetupApiClient : IMeetupApiClient
{
public MeetupApiClient(HttpClient httpClient, ILogger<MeetupApiClient> logger)
{
HttpClient = httpClient;
Logger = logger;
}
private HttpClient HttpClient { get; }
private ILogger<MeetupApiClient> Logger;
public async Task<IEnumerable<MeetupEventModel>> GetEvents(
string urlName, EventsScroll scroll = EventsScroll.Undefined)
{
IEnumerable<MeetupEventModel> Default() => new List<MeetupEventModel>(0);
if (string.IsNullOrWhiteSpace(urlName))
{
Logger.LogError($"Null or whitespace urlname, aborting API call.");
return Default();
}
NameValueCollection BuildQueryString(NameValueCollection query)
{
var collection = HttpUtility.ParseQueryString(string.Empty);
foreach (var key in query.Cast<string>().Where(key => !string.IsNullOrEmpty(query[key])))
{
collection[key] = query[key];
}
return collection;
}
var queryString = BuildQueryString(new NameValueCollection {
{"photo-host", "secure"},
{"scroll", scroll.ToDescriptionString()},
{"desc", "true"} // Hack; this param results in more returned events and in correct order.
});
var response = await HttpClient.GetAsync($"/{HttpUtility.UrlEncode(urlName)}/events?{queryString}");
if (!response.IsSuccessStatusCode)
{
Logger.LogError($"Unexpected meetup API response; status code {response.StatusCode}.");
return Default();
}
try
{
return await response.Content.ReadAsAsync<List<MeetupEventModel>>();
}
catch (Exception e)
{
Logger.LogError("Unable to deserialize API response.", e);
return Default();
}
}
}
} | 35.985075 | 112 | 0.58482 | [
"MIT"
] | bgever/techeventshk | src/sourcers/meetup/svc/Services/MeetupApiClient.cs | 2,411 | C# |
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace Masuit.MyBlogs.Core.Extensions.UEditor
{
/// <summary>
/// NotSupportedHandler 的摘要说明
/// </summary>
public class NotSupportedHandler : Handler
{
public NotSupportedHandler(HttpContext context) : base(context)
{
}
public override Task<string> Process()
{
return Task.FromResult(WriteJson(new
{
state = "action 参数为空或者 action 不被支持。"
}));
}
}
} | 23.478261 | 71 | 0.583333 | [
"MIT"
] | 5653325/Masuit.MyBlogs | src/Masuit.MyBlogs.Core/Extensions/UEditor/NotSupportedHandler.cs | 574 | C# |
using FluentValidation;
using HomeCinema.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HomeCinema.Web.Infrastructure.Validators
{
public class StockViewModelValidator : AbstractValidator<StockViewModel>
{
public StockViewModelValidator()
{
RuleFor(s => s.ID).GreaterThan(0)
.WithMessage("Invalid stock item");
RuleFor(s => s.UniqueKey).NotEqual(Guid.Empty)
.WithMessage("Invalid stock item");
}
}
} | 26.380952 | 76 | 0.66065 | [
"MIT"
] | Gitesss/RentCar | HomeCinema.Web/Infrastructure/Validators/StockViewModelValidator.cs | 556 | C# |
namespace Kasp.Panel.EntityManager.Tests.Controllers {
// [Route("api/entity-manager/test-entity")]
// public class TestEntityManagerController : EntityManagerControllerBase<TestModel, IModelService, TestModel, TestModel, TestModel, FilterBase> {
// public TestEntityManagerController(IModelService repository, IObjectMapper objectMapper, IFormBuilder builder) : base(repository, objectMapper, builder) {
// }
// }
//
//
// [Route("api/entity-manager/[controller]")]
// public abstract class MyEntityManagerController : EntityManagerControllerBase<TestModel, IModelService, TestModel, TestModel, TestModel, FilterBase> {
// protected MyEntityManagerController(IModelService repository, IObjectMapper objectMapper, IFormBuilder builder) : base(repository, objectMapper, builder) {
// }
// }
//
// public class PageController : MyEntityManagerController {
// public PageController(IModelService repository, IObjectMapper objectMapper, IFormBuilder builder) : base(repository, objectMapper, builder) {
// }
// }
//
//
// [Route("api/entity-manager/[controller]"), EntityManagerInfo("data", Name = "my data")]
// public class DataController : EntityManagerControllerBase<TestModel, IModelService, TestModel, TestModel, TestModel, FilterBase> {
// public DataController(IModelService repository, IObjectMapper objectMapper, IFormBuilder builder) : base(repository, objectMapper, builder) {
// }
// }
//
// [AppApiRoute("news"), DisplayName("news 1")]
// public class NewsController : EntityManagerControllerBase<TestModel, IModelService, TestModel, TestModel, TestModel, FilterBase> {
// public NewsController(IModelService repository, IObjectMapper objectMapper, IFormBuilder builder) : base(repository, objectMapper, builder) {
// }
// }
//
// public class TestModel : IModel {
// public int Id { get; set; }
// }
//
// public interface IModelService : IFilteredRepositoryBase<TestModel, FilterBase> {
// }
//
//
// public class AppApiRoute : RouteAttribute {
// public AppApiRoute(string template) : base($"api/app/{template}") {
// }
// }
}
| 45.586957 | 160 | 0.740582 | [
"MIT"
] | Kican/Kasp | tests/Kasp.Panel.EntityManager.Tests/Controllers/TestEntityManagerController.cs | 2,099 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Xml; IKeyInfoEncryptedKey
namespace Org.BouncyCastle.Crypto.Xml
{
public interface IKeyInfoEncryptedKey
{
EncryptedKey EncryptedKey { get; set; }; IKeyInfoEncryptedKey
XmlElement GetXml(); IKeyInfoEncryptedKey
void LoadXml(XmlElement value); IKeyInfoEncryptedKey
}
} | 32.625 | 71 | 0.747126 | [
"MIT"
] | EdoardoLenzi9/bc-xml-security | relatedness/IKeyInfoEncryptedKey.cs | 524 | C# |
using System;
using System.Windows.Forms;
using EWSEditor.Logging;
using Microsoft.Exchange.WebServices.Data;
namespace EWSEditor.Forms
{
/// <summary>
/// This base form makes it really easy to implement new, specialized content
/// forms for different types of content. The steps to implement a new form
/// are:
/// 1. Override SetupForm, LoadContents, and LoadSelectionDetails
/// (see method comments for implementation notes)
/// 2. Set RowIdColumnName to a column that uniquely identifies a row in the
/// ContentsGrid
/// </summary>
public partial class BaseContentForm : EWSEditor.Forms.BrowserForm
{
private Form callingForm = null;
private string contentIdColumnName = string.Empty;
private string detailIdColumnName = string.Empty;
private PropertySet overrideDetailPropertySet = null;
public BaseContentForm()
{
InitializeComponent();
this.CenterToParent();
}
/// <summary>
/// Gets or sets the form which created this form.
/// </summary>
protected Form CallingForm
{
get
{
return this.callingForm;
}
set
{
this.callingForm = value;
}
}
/// <summary>
/// Gets or sets the form which created this form.
/// </summary>
protected PropertySet OverrideDetailPropertySet
{
get
{
return this.overrideDetailPropertySet;
}
set
{
this.overrideDetailPropertySet = value;
}
}
/// <summary>
/// Gets or sets the column name is used in RefreshContentAndDetails()
/// to identify the column which represents a unique identifier for
/// the selected row in the ContentsGrid and maintain the selection
/// after refreshing the data.
/// </summary>
protected string ContentIdColumnName
{
get
{
return this.contentIdColumnName;
}
set
{
this.contentIdColumnName = value;
}
}
/// <summary>
/// Gets or sets the column name is used in RefreshContentAndDetails()
/// to identify the column which represents a unique identifier for
/// the selected row in the DetailsGrid and maintain the selection
/// after refreshing the data.
/// </summary>
protected string DetialIdColumnName
{
get
{
return this.detailIdColumnName;
}
set
{
this.detailIdColumnName = value;
}
}
/// <summary>
/// Refresh the data displayed in the content and details grids.
/// </summary>
protected void RefreshContentAndDetails()
{
try
{
this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
// Remember which content row was selected if there is a column
// identified to uniquely identify rows
string selectedId = this.GetSelectedContentId();
// Reload the contents grid
this.ContentsGrid.Rows.Clear();
this.LoadContents();
// Find and select the previously selected row if we saved the Id
if (selectedId.Length > 0)
{
foreach (DataGridViewRow row in this.ContentsGrid.Rows)
{
if (row.Cells[this.contentIdColumnName].Value != null &&
row.Cells[this.contentIdColumnName].Value.ToString().Equals(selectedId))
{
row.Selected = true;
break;
}
}
}
// Reload the details grid
this.PropertyDetailsGrid.Clear();
this.LoadSelectionDetails();
}
finally
{
this.Cursor = System.Windows.Forms.Cursors.Default;
}
}
/// <summary>
/// Get the value of the designated Id column of the currently
/// selected row. If no row is selected, return NULL.
/// </summary>
/// <returns>
/// Returns the value of the Id column in the selected row of the
/// ContentsGrid if found. Otherwise it returns string.Empty.
/// </returns>
protected string GetSelectedContentId()
{
if (this.contentIdColumnName.Length == 0 ||
!this.ContentsGrid.Columns.Contains(this.ContentIdColumnName))
{
DebugLog.WriteVerbose(String.Concat("Invalid value for RowIdColumnName, ", this.ContentIdColumnName));
throw new InvalidOperationException("RowIdColumnName must be set to a valid column name.");
}
if (this.ContentsGrid.SelectedRows.Count > 0 &&
this.ContentsGrid.SelectedRows[0] != null &&
this.ContentsGrid.SelectedRows[0].Cells[this.ContentIdColumnName].Value != null)
{
return this.ContentsGrid.SelectedRows[0].Cells[this.ContentIdColumnName].Value.ToString();
}
return string.Empty;
}
protected virtual void LoadContents()
{
// Do Nothing...
}
protected virtual void LoadSelectionDetails()
{
// Do Nothing...
}
protected virtual void SetupForm()
{
// Do Nothing...
}
#region Events
private void BaseContentForm_Load(object sender, EventArgs e)
{
// CurrentService should only be NULL here if we are in design mode
// or there is an bug in form so bail out and do nothing.
if (this.CurrentService == null)
{
return;
}
try
{
this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
this.ContentsGrid.Columns.Clear();
this.SetupForm();
// Set the form height and width to that
// of the parent, just like MFCMAPI does
if (this.callingForm != null)
{
if (this.callingForm.WindowState == FormWindowState.Maximized)
{
this.WindowState = FormWindowState.Maximized;
}
else if (this.callingForm.WindowState == FormWindowState.Normal)
{
this.Size = this.callingForm.Size;
this.Location = this.callingForm.Location;
}
}
this.LoadContents();
this.LoadSelectionDetails();
this.mnuRefresh.Click += new EventHandler(this.MnuRefresh_Click);
}
finally
{
this.Cursor = System.Windows.Forms.Cursors.Default;
}
}
/// <summary>
/// Right click should select the row that was clicked and
/// display the context menu.
/// </summary>
/// <param name="sender">The parameter is not used.</param>
/// <param name="e">The parameter is not used.</param>
private void ContentsGrid_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
this.ContentsGrid.Rows[e.RowIndex].Selected = true;
}
}
/// <summary>
/// Call LoadSelectionDetails() if a row in the ContentsGrid is selected
/// </summary>
/// <param name="sender">The parameter is not used.</param>
/// <param name="e">The parameter is not used.</param>
private void ContentsGrid_SelectionChanged(object sender, EventArgs e)
{
try
{
this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
if (this.ContentsGrid.SelectedRows.Count != 1)
{
return;
}
else
{
this.LoadSelectionDetails();
}
}
finally
{
this.Cursor = System.Windows.Forms.Cursors.Default;
}
}
/// <summary>
/// Refresh the contents and details grids, remember which content item was previously selected
/// and select it again.
/// </summary>
/// <param name="sender">The parameter is not used.</param>
/// <param name="e">The parameter is not used.</param>
private void MnuRefresh_Click(object sender, EventArgs e)
{
this.RefreshContentAndDetails();
}
#endregion
private void ContentsGrid_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
if (e.Column.ValueType == typeof(DateTime))
{
DateTime date1 = Convert.ToDateTime(e.CellValue1);
DateTime date2 = Convert.ToDateTime(e.CellValue2);
e.SortResult = System.DateTime.Compare(date1, date2);
e.Handled = true;
}
}
private void ContentsGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
| 32.475083 | 118 | 0.521432 | [
"MIT"
] | manoj75/o365-EWS-Editor | EWSEditor/Forms/BaseContentForm.cs | 9,777 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Files.DataLake.Models;
using Metadata = System.Collections.Generic.IDictionary<string, string>;
namespace Azure.Storage.Files.DataLake
{
/// <summary>
/// The <see cref="DataLakeFileClient"/> allows you to manipulate Azure Data Lake files.
/// </summary>
public class DataLakeFileClient : DataLakePathClient
{
/// <summary>
/// Gets the maximum number of bytes that can be sent in a call
/// to <see cref="UploadAsync(Stream, PathHttpHeaders, DataLakeRequestConditions, IProgress{long}, StorageTransferOptions, CancellationToken)"/>.
/// Supported value is now larger than <see cref="int.MaxValue"/>; please use
/// <see cref="MaxUploadLongBytes"/>.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual int MaxUploadBytes => Version < DataLakeClientOptions.ServiceVersion.V2019_12_12
? Constants.DataLake.Pre_2019_12_12_MaxAppendBytes
: int.MaxValue; // value is larger than can be represented by an int
/// <summary>
/// Gets the maximum number of bytes that can be sent in a call
/// to <see cref="UploadAsync(Stream, PathHttpHeaders, DataLakeRequestConditions, IProgress{long}, StorageTransferOptions, CancellationToken)"/>.
/// </summary>
public virtual long MaxUploadLongBytes => Version < DataLakeClientOptions.ServiceVersion.V2019_12_12
? Constants.DataLake.Pre_2019_12_12_MaxAppendBytes
: Constants.DataLake.MaxAppendBytes;
#region ctors
/// <summary>
/// Initializes a new instance of the <see cref="DataLakeFileClient"/>
/// class for mocking.
/// </summary>
protected DataLakeFileClient()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DataLakeFileClient"/> class.
/// </summary>
/// <param name="fileUri">
/// A <see cref="Uri"/> referencing the file that includes the
/// name of the account, the name of the file system, and the path of the
/// file.
/// </param>
public DataLakeFileClient(Uri fileUri)
: this(fileUri, (HttpPipelinePolicy)null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DataLakeFileClient"/> class.
/// </summary>
/// <param name="fileUri">
/// A <see cref="Uri"/> referencing the file that includes the
/// name of the account, the name of the file system, and the path of the
/// file.
/// </param>
/// <param name="options">
/// Optional <see cref="DataLakeClientOptions"/> that define the transport
/// pipeline policies for authentication, retries, etc., that are
/// applied to every request.
/// </param>
public DataLakeFileClient(Uri fileUri, DataLakeClientOptions options)
: this(fileUri, (HttpPipelinePolicy)null, options)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DataLakeFileClient"/> class.
/// </summary>
/// <param name="fileUri">
/// A <see cref="Uri"/> referencing the file that includes the
/// name of the account, the name of the file system, and the path of the
/// file.
/// </param>
/// <param name="credential">
/// The shared key credential used to sign requests.
/// </param>
public DataLakeFileClient(Uri fileUri, StorageSharedKeyCredential credential)
: this(fileUri, credential.AsPolicy(), null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DataLakeFileClient"/> class.
/// </summary>
/// <param name="fileUri">
/// A <see cref="Uri"/> referencing the file that includes the
/// name of the account, the name of the file system, and the path of the
/// file.
/// </param>
/// <param name="credential">
/// The shared key credential used to sign requests.
/// </param>
/// <param name="options">
/// Optional <see cref="DataLakeClientOptions"/> that define the transport
/// pipeline policies for authentication, retries, etc., that are
/// applied to every request.
/// </param>
public DataLakeFileClient(Uri fileUri, StorageSharedKeyCredential credential, DataLakeClientOptions options)
: this(fileUri, credential.AsPolicy(), options)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DataLakeFileClient"/> class.
/// </summary>
/// <param name="fileUri">
/// A <see cref="Uri"/> referencing the file that includes the
/// name of the account, the name of the file system, and the path of the
/// file.
/// </param>
/// <param name="credential">
/// The token credential used to sign requests.
/// </param>
public DataLakeFileClient(Uri fileUri, TokenCredential credential)
: this(fileUri, credential.AsPolicy(), null)
{
Errors.VerifyHttpsTokenAuth(fileUri);
}
/// <summary>
/// Initializes a new instance of the <see cref="DataLakeFileClient"/> class.
/// </summary>
/// <param name="fileUri">
/// A <see cref="Uri"/> referencing the file that includes the
/// name of the account, the name of the file system, and the path of the
/// file.
/// </param>
/// <param name="credential">
/// The token credential used to sign requests.
/// </param>
/// <param name="options">
/// Optional <see cref="DataLakeClientOptions"/> that define the transport
/// pipeline policies for authentication, retries, etc., that are
/// applied to every request.
/// </param>
public DataLakeFileClient(Uri fileUri, TokenCredential credential, DataLakeClientOptions options)
: this(fileUri, credential.AsPolicy(), options)
{
Errors.VerifyHttpsTokenAuth(fileUri);
}
/// <summary>
/// Initializes a new instance of the <see cref="DataLakeFileClient"/>
/// class.
/// </summary>
/// <param name="fileUri">
/// A <see cref="Uri"/> referencing the file that includes the
/// name of the account, the name of the file system, and the path of the
/// file.
/// </param>
/// <param name="authentication">
/// An optional authentication policy used to sign requests.
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline
/// policies for authentication, retries, etc., that are applied to
/// every request.
/// </param>
internal DataLakeFileClient(Uri fileUri, HttpPipelinePolicy authentication, DataLakeClientOptions options)
: base(fileUri, authentication, options)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DataLakeFileClient"/> class.
/// </summary>
/// <param name="fileUri">
/// A <see cref="Uri"/> referencing the file that includes the
/// name of the account, the name of the file system, and the path of the file.
/// </param>
/// <param name="pipeline">
/// The transport pipeline used to send every request.
/// </param>
/// <param name="version">
/// The version of the service to use when sending requests.
/// </param>
/// <param name="clientDiagnostics">
/// The <see cref="ClientDiagnostics"/> instance used to create
/// diagnostic scopes every request.
/// </param>
internal DataLakeFileClient(
Uri fileUri,
HttpPipeline pipeline,
DataLakeClientOptions.ServiceVersion version,
ClientDiagnostics clientDiagnostics)
: base(
fileUri,
pipeline,
version,
clientDiagnostics)
{
}
internal DataLakeFileClient(
Uri fileSystemUri,
string filePath,
HttpPipeline pipeline,
DataLakeClientOptions.ServiceVersion version,
ClientDiagnostics clientDiagnostics)
: base(
fileSystemUri,
filePath,
pipeline,
version,
clientDiagnostics)
{
}
#endregion ctors
#region Create
/// <summary>
/// The <see cref="Create"/> operation creates a file.
/// If the file already exists, it will be overwritten. If you don't intent to overwrite
/// an existing file, consider using the <see cref="CreateIfNotExists"/> API.
///
/// For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/create.
/// </summary>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// new file or directory..
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this file or directory.
/// </param>
/// <param name="permissions">
/// Optional and only valid if Hierarchical Namespace is enabled for the account. Sets POSIX access
/// permissions for the file owner, the file owning group, and others. Each class may be granted read,
/// write, or execute permission. The sticky bit is also supported. Both symbolic (rwxrw-rw-) and 4-digit
/// octal notation (e.g. 0766) are supported.
/// </param>
/// <param name="umask">
/// Optional and only valid if Hierarchical Namespace is enabled for the account.
/// When creating a file or directory and the parent folder does not have a default ACL,
/// the umask restricts the permissions of the file or directory to be created. The resulting
/// permission is given by p bitwise-and ^u, where p is the permission and u is the umask. For example,
/// if p is 0777 and u is 0057, then the resulting permission is 0720. The default permission is
/// 0777 for a directory and 0666 for a file. The default umask is 0027. The umask must be specified
/// in 4-digit octal notation (e.g. 0766).
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on the creation of this file or directory.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the
/// newly created file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<PathInfo> Create(
PathHttpHeaders httpHeaders = default,
Metadata metadata = default,
string permissions = default,
string umask = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Create)}");
try
{
scope.Start();
return base.Create(
PathResourceType.File,
httpHeaders,
metadata,
permissions,
umask,
conditions,
cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="Create"/> operation creates a file.
/// If the file already exists, it will be overwritten. If you don't intent to overwrite
/// an existing file, consider using the <see cref="CreateIfNotExistsAsync"/> API.
///
/// For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/create.
/// </summary>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// new file or directory..
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this file or directory.
/// </param>
/// <param name="permissions">
/// Optional and only valid if Hierarchical Namespace is enabled for the account. Sets POSIX access
/// permissions for the file owner, the file owning group, and others. Each class may be granted read,
/// write, or execute permission. The sticky bit is also supported. Both symbolic (rwxrw-rw-) and 4-digit
/// octal notation (e.g. 0766) are supported.
/// </param>
/// <param name="umask">
/// Optional and only valid if Hierarchical Namespace is enabled for the account.
/// When creating a file or directory and the parent folder does not have a default ACL,
/// the umask restricts the permissions of the file or directory to be created. The resulting
/// permission is given by p bitwise-and ^u, where p is the permission and u is the umask. For example,
/// if p is 0777 and u is 0057, then the resulting permission is 0720. The default permission is
/// 0777 for a directory and 0666 for a file. The default umask is 0027. The umask must be specified
/// in 4-digit octal notation (e.g. 0766).
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on the creation of this file or directory.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the
/// newly created file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<PathInfo>> CreateAsync(
PathHttpHeaders httpHeaders = default,
Metadata metadata = default,
string permissions = default,
string umask = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Create)}");
try
{
scope.Start();
return await base.CreateAsync(
PathResourceType.File,
httpHeaders,
metadata,
permissions,
umask,
conditions,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Create
#region Create If Not Exists
/// <summary>
/// The <see cref="CreateIfNotExists"/> operation creates a file.
/// If the file already exists, it is not changed.
///
/// For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/create.
/// </summary>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// new file or directory..
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this file or directory..
/// </param>
/// <param name="permissions">
/// Optional and only valid if Hierarchical Namespace is enabled for the account. Sets POSIX access
/// permissions for the file owner, the file owning group, and others. Each class may be granted read,
/// write, or execute permission. The sticky bit is also supported. Both symbolic (rwxrw-rw-) and 4-digit
/// octal notation (e.g. 0766) are supported.
/// </param>
/// <param name="umask">
/// Optional and only valid if Hierarchical Namespace is enabled for the account.
/// When creating a file or directory and the parent folder does not have a default ACL,
/// the umask restricts the permissions of the file or directory to be created. The resulting
/// permission is given by p bitwise-and ^u, where p is the permission and u is the umask. For example,
/// if p is 0777 and u is 0057, then the resulting permission is 0720. The default permission is
/// 0777 for a directory and 0666 for a file. The default umask is 0027. The umask must be specified
/// in 4-digit octal notation (e.g. 0766).
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the
/// newly created file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<PathInfo> CreateIfNotExists(
PathHttpHeaders httpHeaders = default,
Metadata metadata = default,
string permissions = default,
string umask = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(CreateIfNotExists)}");
try
{
scope.Start();
return base.CreateIfNotExists(
PathResourceType.File,
httpHeaders,
metadata,
permissions,
umask,
cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="CreateIfNotExistsAsync"/> operation creates a file.
/// If the file already exists, it is not changed.
///
/// For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/create.
/// </summary>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// new file or directory..
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this file or directory..
/// </param>
/// <param name="permissions">
/// Optional and only valid if Hierarchical Namespace is enabled for the account. Sets POSIX access
/// permissions for the file owner, the file owning group, and others. Each class may be granted read,
/// write, or execute permission. The sticky bit is also supported. Both symbolic (rwxrw-rw-) and 4-digit
/// octal notation (e.g. 0766) are supported.
/// </param>
/// <param name="umask">
/// Optional and only valid if Hierarchical Namespace is enabled for the account.
/// When creating a file or directory and the parent folder does not have a default ACL,
/// the umask restricts the permissions of the file or directory to be created. The resulting
/// permission is given by p bitwise-and ^u, where p is the permission and u is the umask. For example,
/// if p is 0777 and u is 0057, then the resulting permission is 0720. The default permission is
/// 0777 for a directory and 0666 for a file. The default umask is 0027. The umask must be specified
/// in 4-digit octal notation (e.g. 0766).
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the
/// newly created file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<PathInfo>> CreateIfNotExistsAsync(
PathHttpHeaders httpHeaders = default,
Metadata metadata = default,
string permissions = default,
string umask = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(CreateIfNotExists)}");
try
{
scope.Start();
return await base.CreateIfNotExistsAsync(
PathResourceType.File,
httpHeaders,
metadata,
permissions,
umask,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Create If Not Exists
#region Delete
/// <summary>
/// The <see cref="Delete"/> operation marks the specified path
/// deletion. The path is later deleted during
/// garbage collection.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/delete">
/// Delete Path</see>.
/// </summary>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// deleting this path.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> on successfully deleting.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response Delete(
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Delete)}");
try
{
scope.Start();
return base.Delete(
recursive: null,
conditions,
cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="DeleteAsync"/> operation marks the specified path
/// deletion. The path is later deleted during
/// garbage collection.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/delete">
/// Delete Path</see>.
/// </summary>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// deleting this path.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> on successfully deleting.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response> DeleteAsync(
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Delete)}");
try
{
scope.Start();
return await base.DeleteAsync(
recursive: null,
conditions,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Delete
#region Delete If Exists
/// <summary>
/// The <see cref="DeleteIfExists"/> operation marks the specified file
/// for deletion, if the file exists. The file is later deleted during
/// garbage collection.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/delete">
/// Delete Path</see>.
/// </summary>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// deleting this path.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> on successfully deleting.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<bool> DeleteIfExists(
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(DeleteIfExists)}");
try
{
scope.Start();
return base.DeleteIfExists(
recursive: null,
conditions,
cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="DeleteIfExistsAsync"/> operation marks the specified file
/// for deletion, if the file exists. The file is later deleted during
/// garbage collection.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/delete">
/// Delete Path</see>.
/// </summary>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// deleting this path.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> on successfully deleting.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<bool>> DeleteIfExistsAsync(
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(DeleteIfExists)}");
try
{
scope.Start();
return await base.DeleteIfExistsAsync(
recursive: null,
conditions,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Delete If Not Exists
#region Rename
/// <summary>
/// The <see cref="Rename"/> operation renames a Directory.
///
/// For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/create.
/// </summary>
/// <param name="destinationPath">
/// The destination path to rename the path to.
/// </param>
/// <param name="destinationFileSystem">
/// Optional destination file system. If null, path will be renamed within the
/// current file system.
/// </param>
/// <param name="sourceConditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on the source on the creation of this file or directory.
/// </param>
/// <param name="destinationConditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on the creation of this file or directory.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{DataLakeFileClient}"/> describing the
/// newly created file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public new virtual Response<DataLakeFileClient> Rename(
string destinationPath,
string destinationFileSystem = default,
DataLakeRequestConditions sourceConditions = default,
DataLakeRequestConditions destinationConditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Rename)}");
try
{
scope.Start();
Response<DataLakePathClient> response = base.Rename(
destinationFileSystem,
destinationPath,
sourceConditions,
destinationConditions,
cancellationToken);
return Response.FromValue(
new DataLakeFileClient(response.Value.DfsUri, response.Value.Pipeline, response.Value.Version, response.Value.ClientDiagnostics),
response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="RenameAsync"/> operation renames a file or directory.
///
/// For more information, see https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/create.
/// </summary>
/// <param name="destinationPath">
/// The destination path to rename the path to.
/// </param>
/// <param name="destinationFileSystem">
/// Optional destination file system. If null, path will be renamed within the
/// current file system.
/// </param>
/// <param name="destinationConditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on the creation of this file or directory.
/// </param>
/// <param name="sourceConditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on the source on the creation of this file or directory.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{DataLakeFileClient}"/> describing the
/// newly created file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public new virtual async Task<Response<DataLakeFileClient>> RenameAsync(
string destinationPath,
string destinationFileSystem = default,
DataLakeRequestConditions sourceConditions = default,
DataLakeRequestConditions destinationConditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Rename)}");
try
{
scope.Start();
Response<DataLakePathClient> response = await base.RenameAsync(
destinationFileSystem,
destinationPath,
sourceConditions,
destinationConditions,
cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(
new DataLakeFileClient(response.Value.DfsUri, response.Value.Pipeline, response.Value.Version, response.Value.ClientDiagnostics),
response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Rename
#region Get Access Control
/// <summary>
/// The <see cref="GetAccessControl"/> operation returns the
/// access control data for a path.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/getproperties">
/// Get Properties</see>.
/// </summary>
/// <param name="userPrincipalName">
/// Optional.Valid only when Hierarchical Namespace is enabled for the account.If "true",
/// the user identity values returned in the x-ms-owner, x-ms-group, and x-ms-acl response
/// headers will be transformed from Azure Active Directory Object IDs to User Principal Names.
/// If "false", the values will be returned as Azure Active Directory Object IDs.The default
/// value is false. Note that group and application Object IDs are not translated because they
/// do not have unique friendly names.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on getting the path's access control.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathAccessControl}"/> describing the
/// path's access control.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public override Response<PathAccessControl> GetAccessControl(
bool? userPrincipalName = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(GetAccessControl)}");
try
{
scope.Start();
return base.GetAccessControl(
userPrincipalName,
conditions,
cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="GetAccessControlAsync"/> operation returns the
/// access control data for a path.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/getproperties">
/// Get Properties</see>.
/// </summary>
/// <param name="userPrincipalName">
/// Optional.Valid only when Hierarchical Namespace is enabled for the account.If "true",
/// the user identity values returned in the x-ms-owner, x-ms-group, and x-ms-acl response
/// headers will be transformed from Azure Active Directory Object IDs to User Principal Names.
/// If "false", the values will be returned as Azure Active Directory Object IDs.The default
/// value is false. Note that group and application Object IDs are not translated because they
/// do not have unique friendly names.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on getting the path's access control.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathAccessControl}"/> describing the
/// path's access control.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public override async Task<Response<PathAccessControl>> GetAccessControlAsync(
bool? userPrincipalName = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(GetAccessControl)}");
try
{
scope.Start();
return await base.GetAccessControlAsync(
userPrincipalName,
conditions,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Get Access Control
#region Set Access Control
/// <summary>
/// The <see cref="SetAccessControlList"/> operation sets the
/// Access Control on a path
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update">
/// Update Path</see>.
/// </summary>
/// <param name="accessControlList">
/// The POSIX access control list for the file or directory.
/// </param>
/// <param name="owner">
/// The owner of the file or directory.
/// </param>
/// <param name="group">
/// The owning group of the file or directory.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// setting the the path's access control.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the updated
/// path.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public override Response<PathInfo> SetAccessControlList(
IList<PathAccessControlItem> accessControlList,
string owner = default,
string group = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(SetAccessControlList)}");
try
{
scope.Start();
return base.SetAccessControlList(
accessControlList,
owner,
group,
conditions,
cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="SetAccessControlListAsync"/> operation sets the
/// Access Control on a path
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update">
/// Update Path</see>.
/// </summary>
/// <param name="accessControlList">
/// The POSIX access control list for the file or directory.
/// </param>
/// <param name="owner">
/// The owner of the file or directory.
/// </param>
/// <param name="group">
/// The owning group of the file or directory.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// setting the the path's access control.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the updated
/// path.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public override async Task<Response<PathInfo>> SetAccessControlListAsync(
IList<PathAccessControlItem> accessControlList,
string owner = default,
string group = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(SetAccessControlList)}");
try
{
scope.Start();
return await base.SetAccessControlListAsync(
accessControlList,
owner,
group,
conditions,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Set Access Control
#region Set Permissions
/// <summary>
/// The <see cref="SetPermissions"/> operation sets the
/// file permissions on a path.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update">
/// Update Path</see>.
/// </summary>
/// <param name="permissions">
/// The POSIX access permissions for the file owner, the file owning group, and others.
/// </param>
/// <param name="owner">
/// The owner of the file or directory.
/// </param>
/// <param name="group">
/// The owning group of the file or directory.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// setting the the path's access control.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the updated
/// path.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public override Response<PathInfo> SetPermissions(
PathPermissions permissions,
string owner = default,
string group = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(SetPermissions)}");
try
{
scope.Start();
return base.SetPermissions(
permissions,
owner,
group,
conditions,
cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="SetPermissionsAsync"/> operation sets the
/// file permissions on a path.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update">
/// Update Path</see>.
/// </summary>
/// <param name="permissions">
/// The POSIX access permissions for the file owner, the file owning group, and others.
/// </param>
/// <param name="owner">
/// The owner of the file or directory.
/// </param>
/// <param name="group">
/// The owning group of the file or directory.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// setting the the path's access control.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the updated
/// path.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public override async Task<Response<PathInfo>> SetPermissionsAsync(
PathPermissions permissions,
string owner = default,
string group = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(SetPermissions)}");
try
{
scope.Start();
return await base.SetPermissionsAsync(
permissions,
owner,
group,
conditions,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Set Permissions
#region Get Properties
/// <summary>
/// The <see cref="GetProperties"/> operation returns all
/// user-defined metadata, standard HTTP properties, and system
/// properties for the path. It does not return the content of the
/// path.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/get-blob-properties">
/// Get Properties</see>.
/// </summary>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on getting the path's properties.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathProperties}"/> describing the
/// path's properties.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
#pragma warning disable CS0114 // Member hides inherited member; missing override keyword
public virtual Response<PathProperties> GetProperties(
#pragma warning restore CS0114 // Member hides inherited member; missing override keyword
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(GetProperties)}");
try
{
scope.Start();
return base.GetProperties(
conditions,
cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="GetPropertiesAsync"/> operation returns all
/// user-defined metadata, standard HTTP properties, and system
/// properties for the path. It does not return the content of the
/// path.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/get-blob-properties">
/// Get Properties</see>.
/// </summary>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on getting the path's properties.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathProperties}"/> describing the
/// paths's properties.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public override async Task<Response<PathProperties>> GetPropertiesAsync(
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(GetProperties)}");
try
{
scope.Start();
return await base.GetPropertiesAsync(
conditions,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Get Properties
#region Set Http Headers
/// <summary>
/// The <see cref="SetHttpHeaders"/> operation sets system
/// properties on the path.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/set-blob-properties">
/// Set Blob Properties</see>.
/// </summary>
/// <param name="httpHeaders">
/// Optional. The standard HTTP header system properties to set.
/// If not specified, existing values will be cleared.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// setting the paths's HTTP headers.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{httpHeaders}"/> describing the updated
/// path.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public override Response<PathInfo> SetHttpHeaders(
PathHttpHeaders httpHeaders = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(SetHttpHeaders)}");
try
{
scope.Start();
return base.SetHttpHeaders(
httpHeaders,
conditions,
cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="SetHttpHeadersAsync"/> operation sets system
/// properties on the PATH.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/set-blob-properties">
/// Set Blob Properties</see>.
/// </summary>
/// <param name="httpHeaders">
/// Optional. The standard HTTP header system properties to set.
/// If not specified, existing values will be cleared.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// setting the path's HTTP headers.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the updated
/// path.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public override async Task<Response<PathInfo>> SetHttpHeadersAsync(
PathHttpHeaders httpHeaders = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(SetHttpHeaders)}");
try
{
scope.Start();
return await base.SetHttpHeadersAsync(
httpHeaders,
conditions,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Set Http Headers
#region Set Metadata
/// <summary>
/// The <see cref="SetMetadata"/> operation sets user-defined
/// metadata for the specified path as one or more name-value pairs.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/set-blob-metadata">
/// Set Metadata</see>.
/// </summary>
/// <param name="metadata">
/// Custom metadata to set for this path.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// setting the path's metadata.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the updated
/// path.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public override Response<PathInfo> SetMetadata(
Metadata metadata,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(SetMetadata)}");
try
{
scope.Start();
return base.SetMetadata(
metadata,
conditions,
cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="SetMetadataAsync"/> operation sets user-defined
/// metadata for the specified path as one or more name-value pairs.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/set-blob-metadata">
/// Set Metadata</see>.
/// </summary>
/// <param name="metadata">
/// Custom metadata to set for this path.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// setting the path's metadata.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the updated
/// path.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public override async Task<Response<PathInfo>> SetMetadataAsync(
Metadata metadata,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(SetMetadata)}");
try
{
scope.Start();
return await base.SetMetadataAsync(
metadata,
conditions,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Set Metadata
#region Append Data
/// <summary>
/// The <see cref="Append"/> operation uploads data to be appended to a file.
/// Data can only be appended to a file.
/// To apply perviously uploaded data to a file, call Flush Data.
/// Append is currently limited to 4000 MB per request. To upload large files all at once, consider using <see cref="Upload(Stream)"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update">
/// Update Path</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="offset">
/// This parameter allows the caller to upload data in parallel and control the order in which it is appended to the file.
/// It is required when uploading data to be appended to the file and when flushing previously uploaded data to the file.
/// The value must be the position where the data is to be appended. Uploaded data is not immediately flushed, or written, to the file.
/// To flush, the previously uploaded data must be contiguous, the position parameter must be specified and equal to the length
/// of the file after all data has been written, and there must not be a request entity body included with the request.
/// </param>
/// <param name="contentHash">
/// This hash is used to verify the integrity of the request content during transport. When this header is specified,
/// the storage service compares the hash of the content that has arrived with this header value. If the two hashes do not match,
/// the operation will fail with error code 400 (Bad Request). Note that this MD5 hash is not stored with the file. This header is
/// associated with the request content, and not with the stored content of the file itself.
/// </param>
/// <param name="leaseId">
/// Optional lease id.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> describing the state
/// of the updated file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response Append(
Stream content,
long offset,
byte[] contentHash = default,
string leaseId = default,
IProgress<long> progressHandler = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Append)}");
try
{
scope.Start();
return AppendInternal(
content,
offset,
contentHash,
leaseId,
progressHandler,
async: false,
cancellationToken)
.EnsureCompleted();
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="AppendAsync"/> operation uploads data to be appended to a file. Data can only be appended to a file.
/// To apply perviously uploaded data to a file, call Flush Data.
/// Append is currently limited to 4000 MB per request. To upload large files all at once, consider using <see cref="UploadAsync(Stream)"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update">
/// Update Path</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="offset">
/// This parameter allows the caller to upload data in parallel and control the order in which it is appended to the file.
/// It is required when uploading data to be appended to the file and when flushing previously uploaded data to the file.
/// The value must be the position where the data is to be appended. Uploaded data is not immediately flushed, or written, to the file.
/// To flush, the previously uploaded data must be contiguous, the position parameter must be specified and equal to the length
/// of the file after all data has been written, and there must not be a request entity body included with the request.
/// </param>
/// <param name="contentHash">
/// This hash is used to verify the integrity of the request content during transport. When this header is specified,
/// the storage service compares the hash of the content that has arrived with this header value. If the two hashes do not match,
/// the operation will fail with error code 400 (Bad Request). Note that this MD5 hash is not stored with the file. This header is
/// associated with the request content, and not with the stored content of the file itself.
/// </param>
/// <param name="leaseId">
/// Optional lease id.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> describing the state
/// of the updated file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response> AppendAsync(
Stream content,
long offset,
byte[] contentHash = default,
string leaseId = default,
IProgress<long> progressHandler = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Append)}");
try
{
scope.Start();
return await AppendInternal(
content,
offset,
contentHash,
leaseId,
progressHandler,
async: true,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="AppendInternal"/> operation uploads data to be appended to a file. Data can only be appended to a file.
/// To apply perviously uploaded data to a file, call Flush Data.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update">
/// Update Path</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="offset">
/// This parameter allows the caller to upload data in parallel and control the order in which it is appended to the file.
/// It is required when uploading data to be appended to the file and when flushing previously uploaded data to the file.
/// The value must be the position where the data is to be appended. Uploaded data is not immediately flushed, or written, to the file.
/// To flush, the previously uploaded data must be contiguous, the position parameter must be specified and equal to the length
/// of the file after all data has been written, and there must not be a request entity body included with the request.
/// </param>
/// <param name="contentHash">
/// This hash is used to verify the integrity of the request content during transport. When this header is specified,
/// the storage service compares the hash of the content that has arrived with this header value. If the two hashes do not match,
/// the operation will fail with error code 400 (Bad Request). Note that this MD5 hash is not stored with the file. This header is
/// associated with the request content, and not with the stored content of the file itself.
/// </param>
/// <param name="leaseId">
/// Optional lease id.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> describing the state
/// of the updated file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
internal virtual async Task<Response> AppendInternal(
Stream content,
long? offset,
byte[] contentHash,
string leaseId,
IProgress<long> progressHandler,
bool async,
CancellationToken cancellationToken)
{
using (Pipeline.BeginLoggingScope(nameof(DataLakeFileClient)))
{
content = content?.WithNoDispose().WithProgress(progressHandler);
Pipeline.LogMethodEnter(
nameof(DataLakeFileClient),
message:
$"{nameof(Uri)}: {Uri}\n" +
$"{nameof(offset)}: {offset}\n" +
$"{nameof(leaseId)}: {leaseId}\n");
try
{
Response<PathAppendDataResult> response = await DataLakeRestClient.Path.AppendDataAsync(
clientDiagnostics: ClientDiagnostics,
pipeline: Pipeline,
resourceUri: DfsUri,
body: content,
version: Version.ToVersionString(),
position: offset,
contentLength: content?.Length ?? 0,
transactionalContentHash: contentHash,
leaseId: leaseId,
async: async,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
return response.GetRawResponse();
}
catch (Exception ex)
{
Pipeline.LogException(ex);
throw;
}
finally
{
Pipeline.LogMethodExit(nameof(DataLakeFileClient));
}
}
}
#endregion Append Data
#region Flush Data
/// <summary>
/// The <see cref="Flush"/> operation flushes (writes) previously
/// appended data to a file.
/// </summary>
/// <param name="position">
/// This parameter allows the caller to upload data in parallel and control the order in which it is appended to the file.
/// It is required when uploading data to be appended to the file and when flushing previously uploaded data to the file.
/// The value must be the position where the data is to be appended. Uploaded data is not immediately flushed, or written,
/// to the file. To flush, the previously uploaded data must be contiguous, the position parameter must be specified and
/// equal to the length of the file after all data has been written, and there must not be a request entity body included
/// with the request.
/// </param>
/// <param name="retainUncommittedData">
/// If "true", uncommitted data is retained after the flush operation completes; otherwise, the uncommitted data is deleted
/// after the flush operation. The default is false. Data at offsets less than the specified position are written to the
/// file when flush succeeds, but this optional parameter allows data after the flush position to be retained for a future
/// flush operation.
/// </param>
/// <param name="close">
/// Azure Storage Events allow applications to receive notifications when files change. When Azure Storage Events are enabled,
/// a file changed event is raised. This event has a property indicating whether this is the final change to distinguish the
/// difference between an intermediate flush to a file stream and the final close of a file stream. The close query parameter
/// is valid only when the action is "flush" and change notifications are enabled. If the value of close is "true" and the
/// flush operation completes successfully, the service raises a file change notification with a property indicating that
/// this is the final update (the file stream has been closed). If "false" a change notification is raised indicating the
/// file has changed. The default is false. This query parameter is set to true by the Hadoop ABFS driver to indicate that
/// the file stream has been closed."
/// </param>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the file.
///</param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on the flush of this file.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the
/// path.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<PathInfo> Flush(
long position,
bool? retainUncommittedData = default,
bool? close = default,
PathHttpHeaders httpHeaders = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Flush)}");
try
{
scope.Start();
return FlushInternal(
position,
retainUncommittedData,
close,
httpHeaders,
conditions,
async: false,
cancellationToken)
.EnsureCompleted();
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="FlushAsync"/> operation flushes (writes) previously
/// appended data to a file.
/// </summary>
/// <param name="position">
/// This parameter allows the caller to upload data in parallel and control the order in which it is appended to the file.
/// It is required when uploading data to be appended to the file and when flushing previously uploaded data to the file.
/// The value must be the position where the data is to be appended. Uploaded data is not immediately flushed, or written,
/// to the file. To flush, the previously uploaded data must be contiguous, the position parameter must be specified and
/// equal to the length of the file after all data has been written, and there must not be a request entity body included
/// with the request.
/// </param>
/// <param name="retainUncommittedData">
/// If "true", uncommitted data is retained after the flush operation completes; otherwise, the uncommitted data is deleted
/// after the flush operation. The default is false. Data at offsets less than the specified position are written to the
/// file when flush succeeds, but this optional parameter allows data after the flush position to be retained for a future
/// flush operation.
/// </param>
/// <param name="close">
/// Azure Storage Events allow applications to receive notifications when files change. When Azure Storage Events are enabled,
/// a file changed event is raised. This event has a property indicating whether this is the final change to distinguish the
/// difference between an intermediate flush to a file stream and the final close of a file stream. The close query parameter
/// is valid only when the action is "flush" and change notifications are enabled. If the value of close is "true" and the
/// flush operation completes successfully, the service raises a file change notification with a property indicating that
/// this is the final update (the file stream has been closed). If "false" a change notification is raised indicating the
/// file has changed. The default is false. This query parameter is set to true by the Hadoop ABFS driver to indicate that
/// the file stream has been closed."
/// </param>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the file.
///</param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on the flush of this file.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the
/// path.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<PathInfo>> FlushAsync(
long position,
bool? retainUncommittedData = default,
bool? close = default,
PathHttpHeaders httpHeaders = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Flush)}");
try
{
scope.Start();
return await FlushInternal(
position,
retainUncommittedData,
close,
httpHeaders,
conditions,
async: true,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="FlushInternal"/> operation flushes (writes) previously
/// appended data to a file.
/// </summary>
/// <param name="position">
/// This parameter allows the caller to upload data in parallel and control the order in which it is appended to the file.
/// It is required when uploading data to be appended to the file and when flushing previously uploaded data to the file.
/// The value must be the position where the data is to be appended. Uploaded data is not immediately flushed, or written,
/// to the file. To flush, the previously uploaded data must be contiguous, the position parameter must be specified and
/// equal to the length of the file after all data has been written, and there must not be a request entity body included
/// with the request.
/// </param>
/// <param name="retainUncommittedData">
/// If "true", uncommitted data is retained after the flush operation completes; otherwise, the uncommitted data is deleted
/// after the flush operation. The default is false. Data at offsets less than the specified position are written to the
/// file when flush succeeds, but this optional parameter allows data after the flush position to be retained for a future
/// flush operation.
/// </param>
/// <param name="close">
/// Azure Storage Events allow applications to receive notifications when files change. When Azure Storage Events are enabled,
/// a file changed event is raised. This event has a property indicating whether this is the final change to distinguish the
/// difference between an intermediate flush to a file stream and the final close of a file stream. The close query parameter
/// is valid only when the action is "flush" and change notifications are enabled. If the value of close is "true" and the
/// flush operation completes successfully, the service raises a file change notification with a property indicating that
/// this is the final update (the file stream has been closed). If "false" a change notification is raised indicating the
/// file has changed. The default is false. This query parameter is set to true by the Hadoop ABFS driver to indicate that
/// the file stream has been closed."
/// </param>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the file.
///</param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add
/// conditions on the flush of this file.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the
/// path.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
internal virtual async Task<Response<PathInfo>> FlushInternal(
long position,
bool? retainUncommittedData,
bool? close,
PathHttpHeaders httpHeaders,
DataLakeRequestConditions conditions,
bool async,
CancellationToken cancellationToken)
{
using (Pipeline.BeginLoggingScope(nameof(DataLakeFileClient)))
{
Pipeline.LogMethodEnter(
nameof(DataLakeFileClient),
message:
$"{nameof(Uri)}: {Uri}");
try
{
Response<PathFlushDataResult> response = await DataLakeRestClient.Path.FlushDataAsync(
clientDiagnostics: ClientDiagnostics,
pipeline: Pipeline,
resourceUri: DfsUri,
version: Version.ToVersionString(),
position: position,
retainUncommittedData: retainUncommittedData,
close: close,
contentLength: 0,
contentHash: httpHeaders?.ContentHash,
leaseId: conditions?.LeaseId,
cacheControl: httpHeaders?.CacheControl,
contentType: httpHeaders?.ContentType,
contentDisposition: httpHeaders?.ContentDisposition,
contentEncoding: httpHeaders?.ContentEncoding,
contentLanguage: httpHeaders?.ContentLanguage,
ifMatch: conditions?.IfMatch,
ifNoneMatch: conditions?.IfNoneMatch,
ifModifiedSince: conditions?.IfModifiedSince,
ifUnmodifiedSince: conditions?.IfUnmodifiedSince,
async: async,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(
new PathInfo()
{
ETag = response.Value.ETag,
LastModified = response.Value.LastModified
},
response.GetRawResponse());
}
catch (Exception ex)
{
Pipeline.LogException(ex);
throw;
}
finally
{
Pipeline.LogMethodExit(nameof(DataLakeFileClient));
}
}
}
#endregion
#region Read Data
/// <summary>
/// The <see cref="Read()"/> operation downloads a file from
/// the service, including its metadata and properties.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/get-blob">
/// Get Blob</see>.
/// </summary>
/// <returns>
/// A <see cref="Response{FileDownloadInfo}"/> describing the
/// downloaded file. <see cref="FileDownloadInfo.Content"/> contains
/// the blob's data.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<FileDownloadInfo> Read()
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Read)}");
try
{
scope.Start();
Response<Blobs.Models.BlobDownloadInfo> response = _blockBlobClient.Download();
return Response.FromValue(
response.Value.ToFileDownloadInfo(),
response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="ReadAsync()"/> operation downloads a file from
/// the service, including its metadata and properties.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/get-blob">
/// Get Blob</see>.
/// </summary>
/// <returns>
/// A <see cref="Response{FileDownloadInfo}"/> describing the
/// downloaded file. <see cref="FileDownloadInfo.Content"/> contains
/// the file's data.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<FileDownloadInfo>> ReadAsync()
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Read)}");
try
{
scope.Start();
Response<Blobs.Models.BlobDownloadInfo> response
= await _blockBlobClient.DownloadAsync(CancellationToken.None).ConfigureAwait(false);
return Response.FromValue(
response.Value.ToFileDownloadInfo(),
response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="Read(CancellationToken)"/> operation downloads a file from
/// the service, including its metadata and properties.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/get-blob">
/// Get Blob</see>.
/// </summary>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{FileDownloadInfo}"/> describing the
/// downloaded file. <see cref="FileDownloadInfo.Content"/> contains
/// the blob's data.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<FileDownloadInfo> Read(
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Read)}");
try
{
scope.Start();
Response<Blobs.Models.BlobDownloadInfo> response = _blockBlobClient.Download(cancellationToken);
return Response.FromValue(
response.Value.ToFileDownloadInfo(),
response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="ReadAsync(CancellationToken)"/> operation downloads a file from
/// the service, including its metadata and properties.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/get-blob">
/// Get Blob</see>.
/// </summary>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{FileDownloadInfo}"/> describing the
/// downloaded file. <see cref="FileDownloadInfo.Content"/> contains
/// the file's data.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<FileDownloadInfo>> ReadAsync(
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Read)}");
try
{
scope.Start();
Response<Blobs.Models.BlobDownloadInfo> response
= await _blockBlobClient.DownloadAsync(cancellationToken).ConfigureAwait(false);
return Response.FromValue(
response.Value.ToFileDownloadInfo(),
response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="Read(HttpRange, DataLakeRequestConditions?, Boolean, CancellationToken)"/>
/// operation downloads a file from the service, including its metadata
/// and properties.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/get-blob">
/// Get Blob</see>.
/// </summary>
/// <param name="range">
/// If provided, only donwload the bytes of the file in the specified
/// range. If not provided, download the entire file.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// donwloading this file.
/// </param>
/// <param name="rangeGetContentHash">
/// When set to true and specified together with the <paramref name="range"/>,
/// the service returns the MD5 hash for the range, as long as the
/// range is less than or equal to 4 MB in size. If this value is
/// specified without <paramref name="range"/> or set to true when the
/// range exceeds 4 MB in size, a <see cref="RequestFailedException"/>
/// is thrown.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{FileDownloadInfo}"/> describing the
/// downloaded file. <see cref="FileDownloadInfo.Content"/> contains
/// the file's data.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<FileDownloadInfo> Read(
HttpRange range = default,
DataLakeRequestConditions conditions = default,
bool rangeGetContentHash = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Read)}");
try
{
scope.Start();
Response<Blobs.Models.BlobDownloadInfo> response = _blockBlobClient.Download(
range: range,
conditions: conditions.ToBlobRequestConditions(),
rangeGetContentHash: rangeGetContentHash,
cancellationToken: cancellationToken);
return Response.FromValue(
response.Value.ToFileDownloadInfo(),
response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="ReadAsync(HttpRange, DataLakeRequestConditions?, Boolean, CancellationToken)"/>
/// operation downloads a file from the service, including its metadata
/// and properties.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/rest/api/storageservices/get-blob">
/// Get Blob</see>.
/// </summary>
/// <param name="range">
/// If provided, only donwload the bytes of the file in the specified
/// range. If not provided, download the entire file.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// donwloading this file.
/// </param>
/// <param name="rangeGetContentHash">
/// When set to true and specified together with the <paramref name="range"/>,
/// the service returns the MD5 hash for the range, as long as the
/// range is less than or equal to 4 MB in size. If this value is
/// specified without <paramref name="range"/> or set to true when the
/// range exceeds 4 MB in size, a <see cref="RequestFailedException"/>
/// is thrown.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{FileDownloadInfo}"/> describing the
/// downloaded file. <see cref="FileDownloadInfo.Content"/> contains
/// the file's data.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<FileDownloadInfo>> ReadAsync(
HttpRange range = default,
DataLakeRequestConditions conditions = default,
bool rangeGetContentHash = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Read)}");
try
{
scope.Start();
Response<Blobs.Models.BlobDownloadInfo> response = await _blockBlobClient.DownloadAsync(
range: range,
conditions: conditions.ToBlobRequestConditions(),
rangeGetContentHash: rangeGetContentHash,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(
response.Value.ToFileDownloadInfo(),
response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Read Data
#region Read To
/// <summary>
/// The <see cref="ReadTo(Stream, DataLakeRequestConditions, StorageTransferOptions, CancellationToken)"/>
/// operation downloads an entire file using parallel requests,
/// and writes the content to <paramref name="destination"/>.
/// </summary>
/// <param name="destination">
/// A <see cref="Stream"/> to write the downloaded content to.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// the download of this file.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="StorageTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> describing the operation.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response ReadTo(
Stream destination,
DataLakeRequestConditions conditions = default,
//IProgress<long> progressHandler = default,
StorageTransferOptions transferOptions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(ReadTo)}");
try
{
scope.Start();
BlobRequestConditions blobRequestConditions = conditions.ToBlobRequestConditions();
return _blockBlobClient.DownloadTo(
destination,
blobRequestConditions,
//progressHandler, // TODO: #8506
transferOptions: transferOptions,
cancellationToken: cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="ReadTo(string, DataLakeRequestConditions, StorageTransferOptions, CancellationToken)"/>
/// operation downloads an entire file using parallel requests,
/// and writes the content to <paramref name="path"/>.
/// </summary>
/// <param name="path">
/// A file path to write the downloaded content to.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// the download of this file.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="StorageTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> describing the operation.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response ReadTo(
string path,
DataLakeRequestConditions conditions = default,
//IProgress<long> progressHandler = default,
StorageTransferOptions transferOptions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(ReadTo)}");
try
{
scope.Start();
BlobRequestConditions blobRequestConditions = conditions.ToBlobRequestConditions();
return _blockBlobClient.DownloadTo(
path,
blobRequestConditions,
//progressHandler, // TODO: #8506
transferOptions: transferOptions,
cancellationToken: cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="ReadToAsync(Stream, DataLakeRequestConditions, StorageTransferOptions, CancellationToken)"/>
/// operation downloads an entire file using parallel requests,
/// and writes the content to <paramref name="destination"/>.
/// </summary>
/// <param name="destination">
/// A <see cref="Stream"/> to write the downloaded content to.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// the download of this file.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="StorageTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> describing the operation.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response> ReadToAsync(
Stream destination,
DataLakeRequestConditions conditions = default,
//IProgress<long> progressHandler = default,
StorageTransferOptions transferOptions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(ReadTo)}");
try
{
scope.Start();
BlobRequestConditions blobRequestConditions = conditions.ToBlobRequestConditions();
return await _blockBlobClient.DownloadToAsync(
destination,
blobRequestConditions,
//progressHandler, // TODO: #8506
transferOptions: transferOptions,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="ReadToAsync(string, DataLakeRequestConditions, StorageTransferOptions, CancellationToken)"/>
/// operation downloads an entire file using parallel requests,
/// and writes the content to <paramref name="path"/>.
/// </summary>
/// <param name="path">
/// A file path to write the downloaded content to.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// the download of this file.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="StorageTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> describing the operation.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response> ReadToAsync(
string path,
DataLakeRequestConditions conditions = default,
//IProgress<long> progressHandler = default,
StorageTransferOptions transferOptions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($".{nameof(DataLakeFileClient)}.{nameof(ReadTo)}");
try
{
scope.Start();
BlobRequestConditions blobRequestConditions = conditions.ToBlobRequestConditions();
return await _blockBlobClient.DownloadToAsync(
path,
blobRequestConditions,
//progressHandler, // TODO: #8506
transferOptions: transferOptions,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Read To
#region Upload
/// <summary>
/// The <see cref="Upload(Stream, DataLakeFileUploadOptions, CancellationToken)"/>
/// operation creates and uploads content to a file. If the file already exists, its content will be overwritten,
/// unless otherwise specified in the <see cref="DataLakeFileUploadOptions.Conditions"/> or alternatively use
/// <see cref="Upload(Stream)"/>, <see cref="Upload(Stream, bool, CancellationToken)"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<PathInfo> Upload(
Stream content,
DataLakeFileUploadOptions options,
CancellationToken cancellationToken = default) =>
StagedUploadInternal(
content,
options,
async: false,
cancellationToken: cancellationToken)
.EnsureCompleted();
/// <summary>
/// The <see cref="Upload(Stream, PathHttpHeaders, DataLakeRequestConditions, IProgress{long}, StorageTransferOptions, CancellationToken)"/>
/// operation creates and uploads content to a file. If the file already exists, its content will be overwritten,
/// unless otherwise specified in the <see cref="DataLakeRequestConditions"/> or alternatively use
/// <see cref="Upload(Stream)"/>, <see cref="Upload(Stream, bool, CancellationToken)"/>.
///
/// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" />.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the file.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to apply to the request.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="StorageTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Response<PathInfo> Upload(
Stream content,
PathHttpHeaders httpHeaders = default,
DataLakeRequestConditions conditions = default,
IProgress<long> progressHandler = default,
StorageTransferOptions transferOptions = default,
CancellationToken cancellationToken = default) =>
Upload(
content,
new DataLakeFileUploadOptions
{
HttpHeaders = httpHeaders,
Conditions = conditions,
ProgressHandler = progressHandler,
TransferOptions = transferOptions
},
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="Upload(Stream, bool, CancellationToken)"/>
/// operation creates and uploads content to a file.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the
/// state of the updated file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
#pragma warning disable AZC0002 // DO ensure all service methods, both asynchronous and synchronous, take an optional CancellationToken parameter called cancellationToken.
public virtual Response<PathInfo> Upload(
#pragma warning restore AZC0002 // DO ensure all service methods, both asynchronous and synchronous, take an optional CancellationToken parameter called cancellationToken.
Stream content) =>
Upload(
content,
overwrite: false);
/// <summary>
/// The <see cref="Upload(Stream, bool, CancellationToken)"/>
/// operation creates and uploads content to a file.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="overwrite">
/// Whether the upload should overwrite an existing file. The
/// default value is false.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the
/// state of the updated file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[ForwardsClientCalls]
public virtual Response<PathInfo> Upload(
Stream content,
bool overwrite = false,
CancellationToken cancellationToken = default) =>
Upload(
content,
conditions: overwrite ? null : new DataLakeRequestConditions { IfNoneMatch = new ETag(Constants.Wildcard) },
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="UploadAsync(Stream, DataLakeFileUploadOptions, CancellationToken)"/>
/// operation creates and uploads content to a file.If the file already exists, its content will be overwritten,
/// unless otherwise specified in the <see cref="DataLakeFileUploadOptions.Conditions"/> or alternatively use
/// <see cref="UploadAsync(Stream)"/>, <see cref="UploadAsync(Stream, bool, CancellationToken)"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[ForwardsClientCalls]
public virtual Task<Response<PathInfo>> UploadAsync(
Stream content,
DataLakeFileUploadOptions options,
CancellationToken cancellationToken = default) =>
StagedUploadInternal(
content,
options,
async: true,
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="UploadAsync(Stream, PathHttpHeaders, DataLakeRequestConditions, IProgress{long}, StorageTransferOptions, CancellationToken)"/>
/// operation creates and uploads content to a file. If the file already exists, its content will be overwritten,
/// unless otherwise specified in the <see cref="DataLakeRequestConditions"/> or alternatively use
/// <see cref="UploadAsync(Stream)"/>, <see cref="UploadAsync(Stream, bool, CancellationToken)"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the file.
///</param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to apply to the request.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="StorageTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Task<Response<PathInfo>> UploadAsync(
Stream content,
PathHttpHeaders httpHeaders = default,
DataLakeRequestConditions conditions = default,
IProgress<long> progressHandler = default,
StorageTransferOptions transferOptions = default,
CancellationToken cancellationToken = default) =>
StagedUploadInternal(
content,
new DataLakeFileUploadOptions
{
HttpHeaders = httpHeaders,
Conditions = conditions,
ProgressHandler = progressHandler,
TransferOptions = transferOptions
},
async: true,
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="UploadAsync(Stream, bool, CancellationToken)"/>
/// operation creates and uploads content to a file.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[ForwardsClientCalls]
#pragma warning disable AZC0002 // DO ensure all service methods, both asynchronous and synchronous, take an optional CancellationToken parameter called cancellationToken.
public virtual Task<Response<PathInfo>> UploadAsync(
#pragma warning restore AZC0002 // DO ensure all service methods, both asynchronous and synchronous, take an optional CancellationToken parameter called cancellationToken.
Stream content) =>
UploadAsync(
content,
overwrite: false);
/// <summary>
/// The <see cref="UploadAsync(Stream, bool, CancellationToken)"/>
/// operation creates and uploads content to a file.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="overwrite">
/// Whether the upload should overwrite an existing file. The
/// default value is false.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[ForwardsClientCalls]
public virtual Task<Response<PathInfo>> UploadAsync(
Stream content,
bool overwrite = false,
CancellationToken cancellationToken = default) =>
UploadAsync(
content,
conditions: overwrite ? null : new DataLakeRequestConditions { IfNoneMatch = new ETag(Constants.Wildcard) },
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="Upload(string, DataLakeFileUploadOptions, CancellationToken)"/>
/// operation creates and uploads content to a file.If the file already exists, its content will be overwritten,
/// unless otherwise specified in the <see cref="DataLakeFileUploadOptions.Conditions"/> or alternatively use
/// <see cref="Upload(Stream)"/>, <see cref="Upload(Stream, bool, CancellationToken)"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param> of this new block blob.
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[ForwardsClientCalls]
public virtual Response<PathInfo> Upload(
string path,
DataLakeFileUploadOptions options,
CancellationToken cancellationToken = default)
=> StagedUploadInternal(
path,
options,
async: false,
cancellationToken: cancellationToken)
.EnsureCompleted();
/// <summary>
/// The <see cref="Upload(string, PathHttpHeaders, DataLakeRequestConditions, IProgress{long}, StorageTransferOptions, CancellationToken)"/>
/// operation creates and uploads content to a file.If the file already exists, its content will be overwritten,
/// unless otherwise specified in the <see cref="DataLakeRequestConditions"/> or alternatively use
/// <see cref="Upload(Stream)"/>, <see cref="Upload(Stream, bool, CancellationToken)"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param> of this new block blob.
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the file.
///</param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to apply to the request.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="StorageTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
[ForwardsClientCalls]
public virtual Response<PathInfo> Upload(
string path,
PathHttpHeaders httpHeaders = default,
DataLakeRequestConditions conditions = default,
IProgress<long> progressHandler = default,
StorageTransferOptions transferOptions = default,
CancellationToken cancellationToken = default)
{
using (FileStream stream = new FileStream(path, FileMode.Open))
{
return StagedUploadInternal(
stream,
new DataLakeFileUploadOptions
{
HttpHeaders = httpHeaders,
Conditions = conditions,
ProgressHandler = progressHandler,
TransferOptions = transferOptions
},
async: false,
cancellationToken: cancellationToken)
.EnsureCompleted();
}
}
/// <summary>
/// The <see cref="Upload(Stream, bool, CancellationToken)"/>
/// operation creates and uploads content to a file.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param> of this new block blob.
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[ForwardsClientCalls]
#pragma warning disable AZC0002 // DO ensure all service methods, both asynchronous and synchronous, take an optional CancellationToken parameter called cancellationToken.
public virtual Response<PathInfo> Upload(
#pragma warning restore AZC0002 // DO ensure all service methods, both asynchronous and synchronous, take an optional CancellationToken parameter called cancellationToken.
string path) =>
Upload(
path,
overwrite: false);
/// <summary>
/// The <see cref="Upload(Stream, bool, CancellationToken)"/>
/// operation creates and uploads content to a file.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param> of this new block blob.
/// <param name="overwrite">
/// Whether the upload should overwrite an existing file. The
/// default value is false.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[ForwardsClientCalls]
public virtual Response<PathInfo> Upload(
string path,
bool overwrite = false,
CancellationToken cancellationToken = default) =>
Upload(
path,
conditions: overwrite ? null : new DataLakeRequestConditions { IfNoneMatch = new ETag(Constants.Wildcard) },
cancellationToken: cancellationToken);
/// <summary>
/// The <see cref="UploadAsync(string, DataLakeFileUploadOptions, CancellationToken)"/>
/// operation creates and uploads content to a file. If the file already exists, its content will be overwritten,
/// unless otherwise specified in the <see cref="DataLakeFileUploadOptions.Conditions"/> or alternatively use
/// <see cref="UploadAsync(Stream)"/>, <see cref="UploadAsync(Stream, bool, CancellationToken)"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[ForwardsClientCalls]
public virtual async Task<Response<PathInfo>> UploadAsync(
string path,
DataLakeFileUploadOptions options,
CancellationToken cancellationToken = default)
{
using (FileStream stream = new FileStream(path, FileMode.Open))
{
return await StagedUploadInternal(
stream,
options,
async: true,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
}
/// <summary>
/// The <see cref="UploadAsync(string, PathHttpHeaders, DataLakeRequestConditions, IProgress{long}, StorageTransferOptions, CancellationToken)"/>
/// operation creates and uploads content to a file. If the file already exists, its content will be overwritten,
/// unless otherwise specified in the <see cref="DataLakeRequestConditions"/> or alternatively use
/// <see cref="Upload(Stream)"/>, <see cref="Upload(Stream, bool, CancellationToken)"/>.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the file.
///</param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to apply to the request.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="StorageTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
[ForwardsClientCalls]
public virtual async Task<Response<PathInfo>> UploadAsync(
string path,
PathHttpHeaders httpHeaders = default,
DataLakeRequestConditions conditions = default,
IProgress<long> progressHandler = default,
StorageTransferOptions transferOptions = default,
CancellationToken cancellationToken = default)
=> await UploadAsync(
path,
new DataLakeFileUploadOptions
{
HttpHeaders = httpHeaders,
Conditions = conditions,
ProgressHandler = progressHandler,
TransferOptions = transferOptions
},
cancellationToken).ConfigureAwait(false);
/// <summary>
/// The <see cref="UploadAsync(Stream, bool, CancellationToken)"/>
/// operation creates and uploads content to a file.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[ForwardsClientCalls]
#pragma warning disable AZC0002 // DO ensure all service methods, both asynchronous and synchronous, take an optional CancellationToken parameter called cancellationToken.
public virtual async Task<Response<PathInfo>> UploadAsync(
#pragma warning restore AZC0002 // DO ensure all service methods, both asynchronous and synchronous, take an optional CancellationToken parameter called cancellationToken.
string path) =>
await UploadAsync(
path,
overwrite: false).ConfigureAwait(false);
/// <summary>
/// The <see cref="UploadAsync(Stream, bool, CancellationToken)"/>
/// operation creates and uploads content to a file.
///
/// For more information, see
/// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update" >
/// Update Path</see>.
/// </summary>
/// <param name="path">
/// A file path containing the content to upload.
/// </param>
/// <param name="overwrite">
/// Whether the upload should overwrite an existing file. The
/// default value is false.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
[ForwardsClientCalls]
public virtual async Task<Response<PathInfo>> UploadAsync(
string path,
bool overwrite = false,
CancellationToken cancellationToken = default) =>
await UploadAsync(
path,
conditions: overwrite ? null : new DataLakeRequestConditions { IfNoneMatch = new ETag(Constants.Wildcard) },
cancellationToken: cancellationToken).ConfigureAwait(false);
/// <summary>
/// This operation will upload data as indiviually staged
/// blocks if it's larger than the
/// <paramref name="options"/> <see cref="StorageTransferOptions.InitialTransferSize"/>.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content to upload.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="async">
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the
/// state of the updated file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
internal async Task<Response<PathInfo>> StagedUploadInternal(
Stream content,
DataLakeFileUploadOptions options,
bool async = true,
CancellationToken cancellationToken = default)
{
DataLakeFileClient client = new DataLakeFileClient(Uri, Pipeline, Version, ClientDiagnostics);
var uploader = GetPartitionedUploader(
options.TransferOptions,
operationName: $"{nameof(DataLakeFileClient)}.{nameof(Upload)}");
return await uploader.UploadInternal(
content,
options,
options.ProgressHandler,
async,
cancellationToken)
.ConfigureAwait(false);
}
/// <summary>
/// This operation will upload data it as individually staged
/// blocks if it's larger than the
/// <paramref name="options"/> <see cref="StorageTransferOptions.InitialTransferSize"/>.
/// </summary>
/// <param name="path">
/// A file path of the file to upload.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="async">
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// state of the updated block blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
internal async Task<Response<PathInfo>> StagedUploadInternal(
string path,
DataLakeFileUploadOptions options,
bool async = true,
CancellationToken cancellationToken = default)
{
using (FileStream stream = new FileStream(path, FileMode.Open))
{
return await StagedUploadInternal(
stream,
options,
async: async,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
}
#endregion Upload
#region ScheduleDeletion
/// <summary>
/// Schedules the file for deletation.
/// </summary>
/// <param name="options">
/// Schedule deletion parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
internal virtual Response<PathInfo> ScheduleDeletion(
DataLakeFileScheduleDeletionOptions options,
CancellationToken cancellationToken = default)
=> ScheduleDeletionInternal(
options,
async: false,
cancellationToken)
.EnsureCompleted();
/// <summary>
/// Schedules the file for deletation.
/// </summary>
/// <param name="options">
/// Schedule deletion parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{PathInfo}"/> describing the file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
internal virtual async Task<Response<PathInfo>> ScheduleDeletionAsync(
DataLakeFileScheduleDeletionOptions options,
CancellationToken cancellationToken = default)
=> await ScheduleDeletionInternal(
options,
async: true,
cancellationToken).ConfigureAwait(false);
/// <summary>
/// Schedules the file for deletion.
/// </summary>
/// <param name="options">
/// Schedule deletion parameters.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobInfo}"/> describing the file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
private async Task<Response<PathInfo>> ScheduleDeletionInternal(
DataLakeFileScheduleDeletionOptions options,
bool async,
CancellationToken cancellationToken)
{
using (Pipeline.BeginLoggingScope(nameof(DataLakeFileClient)))
{
Pipeline.LogMethodEnter(
nameof(DataLakeFileClient),
message:
$"{nameof(Uri)}: {Uri}\n" +
$"{nameof(options.TimeToExpire)}: {options.TimeToExpire}\n" +
$"{nameof(options.SetExpiryRelativeTo)}: {options.SetExpiryRelativeTo}\n" +
$"{nameof(options.ExpiresOn)}: {options.ExpiresOn}");
try
{
PathExpiryOptions blobExpiryOptions;
string expiresOn = null;
// Relative
if (options.TimeToExpire.HasValue)
{
if (options.SetExpiryRelativeTo.Value == DataLakeFileExpirationOrigin.CreationTime)
{
blobExpiryOptions = PathExpiryOptions.RelativeToCreation;
}
else
{
blobExpiryOptions = PathExpiryOptions.RelativeToNow;
}
expiresOn = options.TimeToExpire.Value.TotalMilliseconds.ToString(CultureInfo.InvariantCulture);
}
// Absolute
else
{
if (options.ExpiresOn.HasValue)
{
blobExpiryOptions = PathExpiryOptions.Absolute;
expiresOn = options.ExpiresOn?.ToString("R", CultureInfo.InvariantCulture);
}
else
{
blobExpiryOptions = PathExpiryOptions.NeverExpire;
}
}
Response<PathSetExpiryInternal> response = await DataLakeRestClient.Path.SetExpiryAsync(
ClientDiagnostics,
Pipeline,
BlobUri,
Version.ToVersionString(),
blobExpiryOptions,
expiresOn: expiresOn,
async: async,
operationName: $"{nameof(DataLakeFileClient)}.{nameof(ScheduleDeletion)}",
cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(
new PathInfo
{
ETag = response.Value.ETag,
LastModified = response.Value.LastModified
},
response.GetRawResponse());
}
catch (Exception ex)
{
Pipeline.LogException(ex);
throw;
}
finally
{
Pipeline.LogMethodExit(nameof(DataLakeFileClient));
}
}
}
#endregion ScheduleDeletion
#region Query
/// <summary>
/// The <see cref="Query"/> API returns the
/// result of a query against the file.
/// </summary>
/// <param name="querySqlExpression">
/// The query.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
/// <returns>
/// A <see cref="Response{FileDownloadInfo}"/>.
/// </returns>
public virtual Response<FileDownloadInfo> Query(
string querySqlExpression,
DataLakeQueryOptions options = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Query)}");
try
{
scope.Start();
Response<BlobDownloadInfo> response = _blockBlobClient.Query(
querySqlExpression,
options.ToBlobQueryOptions(),
cancellationToken);
return Response.FromValue(
response.Value.ToFileDownloadInfo(),
response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// The <see cref="Query"/> API returns the
/// result of a query against the file.
/// </summary>
/// <param name="querySqlExpression">
/// The query.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
/// <returns>
/// A <see cref="Response{FileDownloadInfo}"/>.
/// </returns>
public virtual async Task<Response<FileDownloadInfo>> QueryAsync(
string querySqlExpression,
DataLakeQueryOptions options = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(Query)}");
try
{
scope.Start();
Response<BlobDownloadInfo> response = await _blockBlobClient.QueryAsync(
querySqlExpression,
options.ToBlobQueryOptions(),
cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(
response.Value.ToFileDownloadInfo(),
response.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion Query
#region OpenRead
/// <summary>
/// Opens a stream for reading from the file. The stream will only download
/// the file as the stream is read from.
/// </summary>
/// <param name="position">
/// The position within the file to begin the stream.
/// Defaults to the beginning of the file.
/// </param>
/// <param name="bufferSize">
/// The buffer size to use when the stream downloads parts
/// of the file. Defaults to 1 MB.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// the download of this file.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// Returns a stream that will download the file as the stream
/// is read from.
/// </returns>
#pragma warning disable AZC0015 // Unexpected client method return type.
public virtual Stream OpenRead(
#pragma warning restore AZC0015 // Unexpected client method return type.
long position = 0,
int? bufferSize = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(OpenRead)}");
try
{
scope.Start();
return _blockBlobClient.OpenRead(
position,
bufferSize,
conditions.ToBlobRequestConditions(),
cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// Opens a stream for reading from the file. The stream will only download
/// the file as the stream is read from.
/// </summary>
/// <param name="allowfileModifications">
/// If true, you can continue streaming a blob even if it has been modified.
/// </param>
/// <param name="position">
/// The position within the file to begin the stream.
/// Defaults to the beginning of the file.
/// </param>
/// <param name="bufferSize">
/// The buffer size to use when the stream downloads parts
/// of the file. Defaults to 1 MB.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// Returns a stream that will download the file as the stream
/// is read from.
/// </returns>
#pragma warning disable AZC0015 // Unexpected client method return type.
public virtual Stream OpenRead(
#pragma warning restore AZC0015 // Unexpected client method return type.
bool allowfileModifications,
long position = 0,
int? bufferSize = default,
CancellationToken cancellationToken = default)
=> allowfileModifications ? OpenRead(position, bufferSize, new DataLakeRequestConditions(), cancellationToken)
: OpenRead(position, bufferSize, null, cancellationToken);
/// <summary>
/// Opens a stream for reading from the file. The stream will only download
/// the file as the stream is read from.
/// </summary>
/// <param name="position">
/// The position within the file to begin the stream.
/// Defaults to the beginning of the file.
/// </param>
/// <param name="bufferSize">
/// The buffer size to use when the stream downloads parts
/// of the file. Defaults to 1 MB.
/// </param>
/// <param name="conditions">
/// Optional <see cref="DataLakeRequestConditions"/> to add conditions on
/// the download of the file.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// Returns a stream that will download the file as the stream
/// is read from.
/// </returns>
#pragma warning disable AZC0015 // Unexpected client method return type.
public virtual async Task<Stream> OpenReadAsync(
#pragma warning restore AZC0015 // Unexpected client method return type.
long position = 0,
int? bufferSize = default,
DataLakeRequestConditions conditions = default,
CancellationToken cancellationToken = default)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(OpenRead)}");
try
{
scope.Start();
return await _blockBlobClient.OpenReadAsync(
position,
bufferSize,
conditions?.ToBlobRequestConditions(),
cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// Opens a stream for reading from the file. The stream will only download
/// the file as the stream is read from.
/// </summary>
/// <param name="allowfileModifications">
/// If true, you can continue streaming a blob even if it has been modified.
/// </param>
/// <param name="position">
/// The position within the file to begin the stream.
/// Defaults to the beginning of the file.
/// </param>
/// <param name="bufferSize">
/// The buffer size to use when the stream downloads parts
/// of the file. Defaults to 1 MB.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// Returns a stream that will download the file as the stream
/// is read from.
/// </returns>
#pragma warning disable AZC0015 // Unexpected client method return type.
public virtual async Task<Stream> OpenReadAsync(
#pragma warning restore AZC0015 // Unexpected client method return type.
bool allowfileModifications,
long position = 0,
int? bufferSize = default,
CancellationToken cancellationToken = default)
=> await (allowfileModifications ? OpenReadAsync(position, bufferSize, new DataLakeRequestConditions(), cancellationToken)
: OpenReadAsync(position, bufferSize, null, cancellationToken)).ConfigureAwait(false);
#endregion OpenRead
#region OpenWrite
/// <summary>
/// Opens a stream for writing to the file.
/// </summary>
/// <param name="overwrite">
/// Whether an existing blob should be deleted and recreated.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A stream to write to the file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
#pragma warning disable AZC0015 // Unexpected client method return type.
public virtual Stream OpenWrite(
#pragma warning restore AZC0015 // Unexpected client method return type.
bool overwrite,
DataLakeFileOpenWriteOptions options = default,
CancellationToken cancellationToken = default)
=> OpenWriteInternal(
overwrite: overwrite,
options: options,
async: false,
cancellationToken: cancellationToken)
.EnsureCompleted();
/// <summary>
/// Opens a stream for writing to the file..
/// </summary>
/// <param name="overwrite">
/// Whether an existing blob should be deleted and recreated.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A stream to write to the file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
#pragma warning disable AZC0015 // Unexpected client method return type.
public virtual async Task<Stream> OpenWriteAsync(
#pragma warning restore AZC0015 // Unexpected client method return type.
bool overwrite,
DataLakeFileOpenWriteOptions options = default,
CancellationToken cancellationToken = default)
=> await OpenWriteInternal(
overwrite: overwrite,
options: options,
async: true,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// Opens a stream for writing to the file.
/// </summary>
/// <param name="overwrite">
/// Whether an existing blob should be deleted and recreated.
/// </param>
/// <param name="options">
/// Optional parameters.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A stream to write to the file.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
private async Task<Stream> OpenWriteInternal(
bool overwrite,
DataLakeFileOpenWriteOptions options,
bool async,
CancellationToken cancellationToken)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(DataLakeFileClient)}.{nameof(OpenWrite)}");
try
{
scope.Start();
long position;
ETag? eTag;
if (overwrite)
{
Response<PathInfo> createResponse = await CreateInternal(
resourceType: PathResourceType.File,
httpHeaders: default,
metadata: default,
permissions: default,
umask: default,
conditions: options?.OpenConditions,
async: async,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
position = 0;
eTag = createResponse.Value.ETag;
}
else
{
try
{
Response<PathProperties> propertiesResponse;
if (async)
{
propertiesResponse = await GetPropertiesAsync(
conditions: options?.OpenConditions,
cancellationToken: cancellationToken).ConfigureAwait(false);
}
else
{
propertiesResponse = GetProperties(
conditions: options?.OpenConditions,
cancellationToken: cancellationToken);
}
position = propertiesResponse.Value.ContentLength;
eTag = propertiesResponse.Value.ETag;
}
catch (RequestFailedException ex)
when (ex.ErrorCode == BlobErrorCode.BlobNotFound)
{
Response<PathInfo> createResponse = await CreateInternal(
resourceType: PathResourceType.File,
httpHeaders: default,
metadata: default,
permissions: default,
umask: default,
conditions: options?.OpenConditions,
async: async,
cancellationToken: cancellationToken)
.ConfigureAwait(false);
position = 0;
eTag = createResponse.Value.ETag;
}
}
DataLakeRequestConditions conditions = new DataLakeRequestConditions
{
IfMatch = eTag,
LeaseId = options?.OpenConditions?.LeaseId
};
return new DataLakeFileWriteStream(
fileClient: this,
bufferSize: options?.BufferSize ?? Constants.DefaultBufferSize,
position: position,
conditions: conditions,
progressHandler: options?.ProgressHandler);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion OpenWrite
#region PartitionedUplaoder
internal PartitionedUploader<DataLakeFileUploadOptions, PathInfo> GetPartitionedUploader(
StorageTransferOptions transferOptions,
ArrayPool<byte> arrayPool = null,
string operationName = null)
=> new PartitionedUploader<DataLakeFileUploadOptions, PathInfo>(
GetPartitionedUploaderBehaviors(this),
transferOptions,
arrayPool,
operationName);
// static because it makes mocking easier in tests
internal static PartitionedUploader<DataLakeFileUploadOptions, PathInfo>.Behaviors GetPartitionedUploaderBehaviors(DataLakeFileClient client)
=> new PartitionedUploader<DataLakeFileUploadOptions, PathInfo>.Behaviors
{
InitializeDestination = async (args, async, cancellationToken)
=> await client.CreateInternal(
PathResourceType.File,
args.HttpHeaders,
args.Metadata,
args.Permissions,
args.Umask,
args.Conditions,
async,
cancellationToken).ConfigureAwait(false),
SingleUpload = async (stream, args, progressHandler, operationName, async, cancellationToken) =>
{
// After the File is Create, Lease ID is the only valid request parameter.
if (args?.Conditions != null)
args.Conditions = new DataLakeRequestConditions { LeaseId = args.Conditions.LeaseId };
// Append data
await client.AppendInternal(
stream,
offset: 0,
contentHash: default,
args.Conditions?.LeaseId,
progressHandler,
async,
cancellationToken).ConfigureAwait(false);
// Flush data
return await client.FlushInternal(
position: stream.Length,
retainUncommittedData: default,
close: default,
args.HttpHeaders,
args.Conditions,
async,
cancellationToken)
.ConfigureAwait(false);
},
UploadPartition = async (stream, offset, args, progressHandler, async, cancellationToken)
=> await client.AppendInternal(
stream,
offset,
contentHash: default,
args.Conditions.LeaseId,
progressHandler,
async,
cancellationToken).ConfigureAwait(false),
CommitPartitionedUpload = async (partitions, args, async, cancellationToken) =>
{
(var offset, var size) = partitions.LastOrDefault();
// After the File is Create, Lease ID is the only valid request parameter.
if (args?.Conditions != null)
args.Conditions = new DataLakeRequestConditions { LeaseId = args.Conditions.LeaseId };
return await client.FlushInternal(
offset + size,
retainUncommittedData: default,
close: default,
httpHeaders: args.HttpHeaders,
conditions: args.Conditions,
async,
cancellationToken).ConfigureAwait(false);
},
Scope = operationName => client.ClientDiagnostics.CreateScope(operationName ??
$"{nameof(Azure)}.{nameof(Storage)}.{nameof(Files)}.{nameof(DataLake)}.{nameof(DataLakeFileClient)}.{nameof(DataLakeFileClient.Upload)}")
};
#endregion
}
}
| 41.988437 | 171 | 0.553284 | [
"MIT"
] | AbelHu/azure-sdk-for-net | sdk/storage/Azure.Storage.Files.DataLake/src/DataLakeFileClient.cs | 174,296 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Merchello.Core.Gateways.Shipping.FixedRate;
using Merchello.Core.Models;
using NUnit.Framework;
namespace Merchello.Tests.UnitTests.Shipping
{
[TestFixture]
public class ShipRateTableTests
{
private ShippingFixedRateTable _shippingFixedRateTable;
[SetUp]
public void Init()
{
_shippingFixedRateTable = new ShippingFixedRateTable(Guid.NewGuid(), new List<IShipRateTier>());
_shippingFixedRateTable.IsTest = true;
}
/// <summary>
/// Test verifies that a ShipRateTier can be added to the rate table.
/// </summary>
[Test]
public void Can_Verify_That_A_ShipRateTier_Can_Be_Added_To_ShipRateTable()
{
//// Arrange
// handled via setup
//// Act
_shippingFixedRateTable.AddRow(10, 20, 5);
//// Assert
Assert.IsTrue(_shippingFixedRateTable.Rows.Any());
Console.WriteLine("Low: {0} to High: {1}", _shippingFixedRateTable.Rows.First().RangeLow, _shippingFixedRateTable.Rows.First().RangeHigh);
Assert.AreEqual(0, _shippingFixedRateTable.Rows.First().RangeLow);
}
/// <summary>
/// Test verifies that several shipratetiers can be added to the table and the class
/// </summary>
[Test]
public void Can_Verify_That_Several_RateTiers_Can_Be_Added_And_Ranges_Are_Preserved()
{
//// Arrange
// handled by setup
//// Act
_shippingFixedRateTable.AddRow(1, 5, 0);
_shippingFixedRateTable.AddRow(6, 4, 1);
_shippingFixedRateTable.AddRow(3, 4, 1);
foreach (var row in _shippingFixedRateTable.Rows)
{
Console.WriteLine("Low: {0} to High: {1}", row.RangeLow, row.RangeHigh);
}
//// Assert
Assert.AreEqual(3, _shippingFixedRateTable.Rows.Count());
Assert.AreEqual(0, _shippingFixedRateTable.Rows.First().RangeLow);
Assert.AreEqual(3, _shippingFixedRateTable.Rows.First().RangeHigh);
Assert.NotNull(_shippingFixedRateTable.Rows.First(x => x.RangeLow == 3));
Assert.NotNull(_shippingFixedRateTable.Rows.First(x => x.RangeHigh == 4));
Assert.AreEqual(4, _shippingFixedRateTable.Rows.Last().RangeLow);
Assert.AreEqual(6, _shippingFixedRateTable.Rows.Last().RangeHigh);
}
/// <summary>
/// Test verifies taht a rate tier that spans one or more existing rate tiers is not inserted
/// </summary>
[Test]
public void Can_Verify_That_A_Rate_Tier_That_Spans_Multiple_Existing_Tiers_Is_Not_Inserted()
{
//// Arrange
_shippingFixedRateTable.AddRow(0,5, 1);
_shippingFixedRateTable.AddRow(5, 10, 1);
_shippingFixedRateTable.AddRow(10, 20, 1);
_shippingFixedRateTable.AddRow(20, 25, 1);
_shippingFixedRateTable.AddRow(25, 999, 1);
Assert.AreEqual(5, _shippingFixedRateTable.Rows.Count());
//// Act
_shippingFixedRateTable.AddRow(4, 11, 1);
//// Assert
Assert.AreEqual(5, _shippingFixedRateTable.Rows.Count());
Assert.IsFalse(_shippingFixedRateTable.Rows.Any(x => x.RangeLow == 4));
}
/// <summary>
///
/// </summary>
[Test]
public void Can_Verify_That_A_Rate_Tier_Can_Be_Deleted()
{
//// Arrange
_shippingFixedRateTable.AddRow(0, 5, 1);
_shippingFixedRateTable.AddRow(5, 10, 1);
_shippingFixedRateTable.AddRow(10, 20, 1);
_shippingFixedRateTable.AddRow(20, 25, 1);
//// Act
_shippingFixedRateTable.DeleteRow(_shippingFixedRateTable.Rows.First(x => x.RangeLow == 5));
//// Assert
Assert.AreEqual(3, _shippingFixedRateTable.Rows.Count());
}
}
} | 35.293103 | 150 | 0.601856 | [
"MIT"
] | bowserm/Merchello | test/Merchello.Tests.UnitTests/Shipping/ShipRateTableTests.cs | 4,096 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using SignService.Models;
using SignService.Services;
namespace SignService.Controllers
{
[Authorize(Roles = "admin_signservice")]
[RequireHttps]
public class AdminController : Controller
{
readonly IUserAdminService adminService;
public AdminController(IUserAdminService adminService)
{
this.adminService = adminService;
}
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> RegisterExtensionAttributes()
{
await adminService.RegisterExtensionPropertiesAsync();
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> UnRegisterExtensionAttributes()
{
await adminService.UnRegisterExtensionPropertiesAsync();
return RedirectToAction(nameof(Index));
}
}
} | 26.414634 | 72 | 0.671283 | [
"MIT"
] | SabotageAndi/SignService | src/SignService/Controllers/AdminController.cs | 1,085 | C# |
/*
*
* (c) Copyright Ascensio System Limited 2010-2020
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
namespace ASC.Common.Security.Authorizing
{
[Serializable]
public sealed class Role : IRole
{
public const string Everyone = "Everyone";
public const string Visitors = "Visitors";
public const string Users = "Users";
public const string Administrators = "Administrators";
public const string System = "System";
public Guid ID { get; internal set; }
public string Name { get; internal set; }
public string AuthenticationType
{
get { return "ASC"; }
}
public bool IsAuthenticated
{
get { return false; }
}
public Role(Guid id, string name)
{
if (id == Guid.Empty) throw new ArgumentException("id");
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name");
ID = id;
Name = name;
}
public override int GetHashCode()
{
return ID.GetHashCode();
}
public override bool Equals(object obj)
{
var r = obj as Role;
return r != null && r.ID == ID;
}
public override string ToString()
{
return string.Format("Role: {0}", Name);
}
}
} | 26.205479 | 84 | 0.598536 | [
"Apache-2.0"
] | Ektai-Solution-Pty-Ltd/CommunityServer | common/ASC.Common/Security/Authorizing/Domain/Role.cs | 1,913 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
namespace Luis
{
public class LUISStockClient
{
public static async Task<StockLUIS> ParseUserInput(string strInput)
{
string strRet = string.Empty;
string strEscaped = Uri.EscapeDataString(strInput);
using (var client = new HttpClient())
{
string uri="https://api.projectoxford.ai/luis/v1/application?id=9fa4985b-351f-4e5e-8c8f-b726795a98b4&subscription-key=a5d38008ca0f4e2187314509e3671953&q="+ strEscaped;
HttpResponseMessage msg = await client.GetAsync(uri);
if (msg.IsSuccessStatusCode)
{
var jsonResponse = await msg.Content.ReadAsStringAsync();
var _Data = JsonConvert.DeserializeObject<StockLUIS>(jsonResponse);
return _Data;
}
}
return null;
}
}
public class StockLUIS
{
public string query { get; set; }
public lIntent[] intents { get; set; }
public lEntity[] entities { get; set; }
}
public class lIntent
{
public string intent { get; set; }
public float score { get; set; }
}
public class lEntity
{
public string entity { get; set; }
public string type { get; set; }
public int startIndex { get; set; }
public int endIndex { get; set; }
public float score { get; set; }
}
} | 29.381818 | 183 | 0.587252 | [
"MIT"
] | Aaron-Strong/BotBuilder | CSharp/Samples/Stock_Bot/Basic_Luis_StockBot/Luis.cs | 1,618 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.