content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace NetEscapades.AspNetCore.SecurityHeaders.Headers
{
/// <summary>
/// The header value to use for Content-SecurityHeader
/// </summary>
public class ContentSecurityPolicyHeader : HtmlOnlyHeaderPolicyBase
{
private readonly string _value;
private readonly Func<HttpContext, string> _builder;
/// <summary>
/// Initializes a new instance of the <see cref="ContentSecurityPolicyHeader"/> class.
/// </summary>
/// <param name="asReportOnly">If true, the header is added as report only</param>
/// <param name="value">The value to apply for the header</param>
public ContentSecurityPolicyHeader(string value, bool asReportOnly)
{
_value = value;
ReportOnly = asReportOnly;
HasPerRequestValues = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="ContentSecurityPolicyHeader"/> class.
/// </summary>
/// <param name="builder">A function to generate the header's value for a request </param>
/// <param name="asReportOnly">If true, the header is added as report only</param>
public ContentSecurityPolicyHeader(Func<HttpContext, string> builder, bool asReportOnly)
{
_builder = builder;
ReportOnly = asReportOnly;
HasPerRequestValues = true;
}
/// <inheritdoc />
public override string Header => ReportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy";
/// <summary>
/// If true, the CSP header is added as "Content-Security-Policy-Report-Only".
/// If false, it's set to "Content-Security-Policy";
/// </summary>
internal bool ReportOnly { get; }
/// <summary>
/// If true, the header directives are unique per request, and require
/// runtime formatting (e.g. for use with Nonce)
/// </summary>
internal bool HasPerRequestValues { get; }
/// <inheritdoc />
protected override string GetValue(HttpContext context) => HasPerRequestValues ? _builder(context) : _value;
/// <summary>
/// Configure a content security policy
/// </summary>
/// <param name="configure">Configure the CSP</param>
/// <param name="asReportOnly">If true, the header is added as report only</param>
/// <returns>The configured <see cref="ContentSecurityPolicyHeader "/></returns>
public static ContentSecurityPolicyHeader Build(Action<CspBuilder> configure, bool asReportOnly)
{
var builder = new CspBuilder();
configure(builder);
var cspResult = builder.Build();
return cspResult.HasPerRequestValues
? new ContentSecurityPolicyHeader(cspResult.Builder, asReportOnly)
: new ContentSecurityPolicyHeader(cspResult.ConstantValue, asReportOnly);
}
}
} | 40.342105 | 120 | 0.631115 | [
"MIT"
] | huan086/NetEscapades.AspNetCore.SecurityHeaders | src/NetEscapades.AspNetCore.SecurityHeaders/Headers/ContentSecurityPolicyHeader.cs | 3,068 | C# |
using System;
using LHGames.Helper;
namespace LHGames.Navigation.Pathfinding
{
public class Edge
{
public Node Source { get; set; }
public Node Destination { get; set; }
public double Weight => WeightForTileType(Destination.Tile.TileType);
public Edge(Node source, Node destination)
{
Source = source;
Destination = destination;
}
public override string ToString()
{
return $"Edge: {Source} --({Weight})--> {Destination}";
}
public static double WeightForTileType(TileContent content)
{
double weight = 0.0;
switch (content)
{
case TileContent.Lava:
case TileContent.Resource:
case TileContent.Shop:
case TileContent.Player:
weight = Double.MaxValue;
break;
case TileContent.Wall:
weight = 5.0;
break;
case TileContent.House:
case TileContent.Empty:
weight = 1.0;
break;
default:
throw new ArgumentOutOfRangeException(nameof(content), content, null);
}
return weight;
}
}
} | 28.125 | 90 | 0.494815 | [
"MIT"
] | LHGames-2018/GLaDOS | LHGames/Navigation/Pathfinding/Edge.cs | 1,350 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using GameEngine;
namespace Troma
{
public struct TargetState
{
public bool State;
public Entity Entity;
}
public class TargetManager
{
#region Fields
private static List<Entity> _masterList = new List<Entity>();
public static List<Entity> MasterList
{
get { return _masterList; }
}
public static int Count
{
get { return _masterList.Count; }
}
#endregion
#region Initialize
/// <summary>
/// Initializes the manager
/// </summary>
public static void Initialize()
{
_masterList.AddRange(EntityManager.EntitiesWith<Target>());
foreach (Entity e in _masterList)
{
e.GetComponent<CollisionBox>().GenerateBoundingBox();
CollisionManager.AddBox(e.GetComponent<CollisionBox>().BoxList);
//e.GetComponent<AnimatedModel3D>().PlayClip(new AnimInfo(0, 2), 2);
}
}
#endregion
public static bool IsTargetAchieved(BoundingBox box)
{
TargetState result = Contains(box);
if (result.State)
{
EntityManager.Remove(result.Entity);
CollisionManager.Remove(result.Entity.GetComponent<CollisionBox>().BoxList);
_masterList.Remove(result.Entity);
/*
result.Entity.GetComponent<AnimatedModel3D>().PlayClip(new AnimInfo(0, 60), 2);
CollisionManager.Remove(result.Entity.GetComponent<CollisionBox>().BoxList);
_masterList.Remove(result.Entity);
*/
}
if (result.State)
TimerManager.Add(45, PlayImpactSound);
return result.State;
}
private static TargetState Contains(BoundingBox box)
{
foreach (Entity entity in _masterList)
{
if (entity.GetComponent<CollisionBox>().BoxList.Contains(box))
return new TargetState { State = true, Entity = entity };
}
return new TargetState { State = false };
}
/// <summary>
/// Clear all the lists in the manager.
/// </summary>
public static void Clear()
{
_masterList.Clear();
}
public static void PlayImpactSound(object o, EventArgs e)
{
SFXManager.Play("TargetImpact", 0.25f, 0);
}
}
}
| 26.245098 | 95 | 0.548375 | [
"MIT"
] | dethi/troma | src/Game/Troma/Troma/Game/TargetManager.cs | 2,679 | C# |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using Amazon.DirectConnect.Model;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.DirectConnect.Model.Internal.MarshallTransformations
{
/// <summary>
/// CreateInterconnectResultUnmarshaller
/// </summary>
internal class CreateInterconnectResultUnmarshaller : IUnmarshaller<CreateInterconnectResult, XmlUnmarshallerContext>, IUnmarshaller<CreateInterconnectResult, JsonUnmarshallerContext>
{
CreateInterconnectResult IUnmarshaller<CreateInterconnectResult, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
public CreateInterconnectResult Unmarshall(JsonUnmarshallerContext context)
{
if (context.CurrentTokenType == JsonUnmarshallerContext.TokenType.Null)
return null;
CreateInterconnectResult createInterconnectResult = new CreateInterconnectResult();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
while (context.Read())
{
if ((context.IsKey) && (context.CurrentDepth == targetDepth))
{
context.Read();
context.Read();
if (context.TestExpression("InterconnectId", targetDepth))
{
createInterconnectResult.InterconnectId = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("InterconnectName", targetDepth))
{
createInterconnectResult.InterconnectName = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("InterconnectState", targetDepth))
{
createInterconnectResult.InterconnectState = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("Region", targetDepth))
{
createInterconnectResult.Region = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("Location", targetDepth))
{
createInterconnectResult.Location = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("Bandwidth", targetDepth))
{
createInterconnectResult.Bandwidth = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth <= originalDepth)
{
return createInterconnectResult;
}
}
return createInterconnectResult;
}
private static CreateInterconnectResultUnmarshaller instance;
public static CreateInterconnectResultUnmarshaller GetInstance()
{
if (instance == null)
instance = new CreateInterconnectResultUnmarshaller();
return instance;
}
}
}
| 38.066667 | 189 | 0.615962 | [
"Apache-2.0"
] | jdluzen/aws-sdk-net-android | AWSSDK/Amazon.DirectConnect/Model/Internal/MarshallTransformations/CreateInterconnectResultUnmarshaller.cs | 3,997 | C# |
public class Song
{
private string artist;
private string songName;
private int minutes;
private int seconds;
private string Artist
{
get
{
return this.artist;
}
set
{
if (value == null || value.Length < 3 || value.Length > 20)
{
throw new InvalidArtistNameException();
}
this.artist = value;
}
}
private string SongName
{
get
{
return this.songName;
}
set
{
if (value == null || value.Length < 3 || value.Length > 30)
{
throw new InvalidSongNameException();
}
this.songName = value;
}
}
public int Minutes
{
get
{
return this.minutes;
}
private set
{
if (value < 0 || value > 14)
{
throw new InvalidSongMinutesException();
}
this.minutes = value;
}
}
public int Seconds
{
get
{
return this.seconds;
}
private set
{
if (value < 0 || value > 59)
{
throw new InvalidSongSecondsException();
}
this.seconds = value;
}
}
public Song(string artist, string songName, int minutes, int seconds)
{
Artist = artist;
SongName = songName;
Minutes = minutes;
Seconds = seconds;
}
} | 19.280488 | 73 | 0.43074 | [
"MIT"
] | MustafaAmish/All-Curses-in-SoftUni | 04. C# OOP Basics/10. Inheritance - Exercise/OnlineRadioDatabase/Song.cs | 1,583 | C# |
namespace NeoSharp.Core.Types
{
/// <summary>
/// Define the behavior in case of exceeding the maximum
/// </summary>
public enum PoolMaxBehaviour : byte
{
/// <summary>
/// Don't allow more items
/// </summary>
DontAllowMore,
/// <summary>
/// Remove from the end
/// </summary>
RemoveFromEnd
}
} | 22.705882 | 60 | 0.523316 | [
"MIT"
] | BSathvik/neo-sharp | src/NeoSharp.Core/Types/PoolMaxBehaviour.cs | 388 | C# |
using System.IO;
namespace Apos.Content.Compile {
/// <summary>
/// A string content is simply a file with text.
/// </summary>
public class StringCompiler : Compiler<string, Settings<string>> {
/// <summary>
/// Builds a string content.
/// </summary>
public override void Build(Stream input, Stream output, Settings<string> settings) {
using (StreamReader sr = new StreamReader(input))
using (BinaryWriter bw = new BinaryWriter(output)) {
string text = sr.ReadToEnd();
bw.Write(text);
}
}
}
}
| 31.25 | 92 | 0.568 | [
"MIT"
] | Apostolique/Apos.Content | Source/Compile/StringCompiler.cs | 627 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
namespace NSW.StarCitizen.Tools.Lib.Helpers
{
public abstract class CfgRow {}
public sealed class CfgDataRow : CfgRow
{
public string Key { get; }
public string Value { get; private set; }
public static CfgDataRow? Create(string key, string value) =>
!string.IsNullOrWhiteSpace(key) ? new CfgDataRow(key, value) : null;
private CfgDataRow(string key, string value)
{
Key = key;
Value = value;
}
public void UpdateValue(string value) => Value = value;
public override string ToString() => Key + "=" + Value;
public override bool Equals(object value) =>
ReferenceEquals(this, value) || (value is CfgDataRow dataRow &&
string.Compare(Key, dataRow.Key, StringComparison.OrdinalIgnoreCase) == 0 && Value == dataRow.Value);
public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Key);
}
public sealed class CfgTextRow : CfgRow
{
public static CfgTextRow Empty { get; } = new CfgTextRow(string.Empty);
public static CfgTextRow Create(string content) => string.IsNullOrWhiteSpace(content) ? Empty : new CfgTextRow(content);
public string Content { get; }
private CfgTextRow(string content)
{
Content = content;
}
public override string ToString() => Content;
public override bool Equals(object value) =>
ReferenceEquals(this, value) || (value is CfgTextRow textRow && Content == textRow.Content);
public override int GetHashCode() => Content.GetHashCode();
}
public class CfgData : IEnumerable<CfgRow>
{
public const string CommentRowPrefix = ";";
private readonly List<CfgRow> _rows = new List<CfgRow>();
public string? this[string key] => GetRowByKey(key)?.Value;
public IEnumerator<CfgRow> GetEnumerator() => _rows.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public CfgData() {}
public CfgData(int capacity)
{
_rows = new List<CfgRow>(capacity);
}
public CfgData(IEnumerable<CfgRow> collection)
{
_rows = new List<CfgRow>(collection);
}
public CfgData(string content)
{
string? line;
using var reader = new StringReader(content);
while ((line = reader.ReadLine()) != null)
{
AddRow(line);
}
}
public void Clear() => _rows.Clear();
public void AddCommentRow(string text) => _rows.Add(CfgTextRow.Create($"{CommentRowPrefix} {text}"));
public bool AddRow(string original)
{
if (IsTextString(original))
{
_rows.Add(CfgTextRow.Create(original));
return true;
}
int pos = original.IndexOf('=');
if (pos < 0)
{
_rows.Add(CfgTextRow.Create(original));
return true;
}
string key = original.Substring(0, pos).Trim();
string value = original.Substring(pos + 1).Trim();
var row = CfgDataRow.Create(key, value);
if (row == null)
{
_rows.Add(CfgTextRow.Create(original));
return true;
}
if (ContainsKey(key))
return false;
_rows.Add(row);
return true;
}
public CfgDataRow? AddOrUpdateRow(string key, string value)
{
var row = GetRowByKey(key);
if (row != null)
{
row.UpdateValue(value);
return row;
}
var addRow = CfgDataRow.Create(key, value);
if (addRow != null)
{
_rows.Add(addRow);
return addRow;
}
return null;
}
public CfgDataRow? RemoveRow(string key)
{
var row = GetRowByKey(key);
if (row != null)
{
_rows.Remove(row);
return row;
}
return null;
}
public bool TryGetValue(string key, out string? value)
{
var row = GetRowByKey(key);
if (row != null)
{
value = row.Value;
return true;
}
value = null;
return false;
}
public IReadOnlyDictionary<string, string> ToDictionary()
=> _rows.OfType<CfgDataRow>().ToDictionary(row => row.Key, row => row.Value, StringComparer.OrdinalIgnoreCase);
public IReadOnlyDictionary<string, CfgDataRow> ToRowDictionary()
=> _rows.OfType<CfgDataRow>().ToDictionary(row => row.Key, row => row, StringComparer.OrdinalIgnoreCase);
private CfgDataRow? GetRowByKey(string key)
{
if (!string.IsNullOrWhiteSpace(key))
return _rows.OfType<CfgDataRow>().SingleOrDefault(r => string.Compare(key, r.Key, StringComparison.OrdinalIgnoreCase) == 0);
return null;
}
private bool ContainsKey(string key) =>
!string.IsNullOrWhiteSpace(key) &&
_rows.OfType<CfgDataRow>().Any(r => string.Compare(key, r.Key, StringComparison.OrdinalIgnoreCase) == 0);
private static bool IsTextString(string original) =>
string.IsNullOrWhiteSpace(original) ||
original.StartsWith(CommentRowPrefix, StringComparison.Ordinal) ||
original.StartsWith("--", StringComparison.Ordinal) ||
original.StartsWith("//", StringComparison.Ordinal);
public override string ToString()
{
StringBuilder builder = new StringBuilder();
foreach (var row in this)
{
builder.AppendLine(row.ToString());
}
return builder.ToString();
}
public override bool Equals(object value)
{
if (ReferenceEquals(this, value))
{
return true;
}
if (value is CfgData cfgData)
{
return Enumerable.SequenceEqual(_rows, cfgData._rows);
}
return false;
}
public override int GetHashCode() => _rows.GetHashCode();
}
public class CfgFile
{
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly string _fileName;
public CfgFile(string fileName)
{
_fileName = fileName;
}
public async Task<CfgData> ReadAsync()
{
var data = new CfgData();
if (!File.Exists(_fileName))
return data;
try
{
using var reader = File.OpenText(_fileName);
string line;
while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
{
data.AddRow(line);
}
}
catch (Exception e)
{
_logger.Error(e, $"Failed read file: {_fileName}");
}
return data;
}
public CfgData Read()
{
var data = new CfgData();
if (!File.Exists(_fileName))
return data;
try
{
string? line;
using var reader = File.OpenText(_fileName);
while ((line = reader.ReadLine()) != null)
{
data.AddRow(line);
}
}
catch (Exception e)
{
_logger.Error(e, $"Failed read file: {_fileName}");
}
return data;
}
public async Task<bool> SaveAsync(CfgData data)
{
try
{
using var writer = File.CreateText(_fileName);
foreach (var row in data)
{
await writer.WriteLineAsync(row.ToString()).ConfigureAwait(false);
}
await writer.FlushAsync().ConfigureAwait(false);
return true;
}
catch (Exception e)
{
_logger.Error(e, $"Failed save file: {_fileName}");
return false;
}
}
public bool Save(CfgData data)
{
try
{
using var writer = File.CreateText(_fileName);
foreach (var row in data)
{
writer.WriteLine(row.ToString());
}
writer.Flush();
return true;
}
catch (Exception e)
{
_logger.Error(e, $"Failed save file: {_fileName}");
return false;
}
}
}
} | 30.278689 | 140 | 0.514348 | [
"MIT"
] | h0useRus/StarCitizen | SCTools/SCToolsLib/Helpers/CfgReader.cs | 9,235 | 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.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Metadata.Builders
{
/// <summary>
/// <para>
/// Provides a simple API for configuring a one-to-one ownership.
/// </para>
/// </summary>
public class ReferenceOwnershipBuilder<TEntity, TRelatedEntity> : ReferenceOwnershipBuilder
where TEntity : class
where TRelatedEntity : class
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public ReferenceOwnershipBuilder(
[NotNull] EntityType declaringEntityType,
[NotNull] EntityType relatedEntityType,
[NotNull] InternalRelationshipBuilder builder)
: base(declaringEntityType, relatedEntityType, builder)
{
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
protected ReferenceOwnershipBuilder(
InternalRelationshipBuilder builder,
ReferenceOwnershipBuilder oldBuilder,
bool inverted = false,
bool foreignKeySet = false,
bool principalKeySet = false,
bool requiredSet = false)
: base(builder, oldBuilder, inverted, foreignKeySet, principalKeySet, requiredSet)
{
}
/// <summary>
/// Adds or updates an annotation on the foreign key. If an annotation with the key specified in
/// <paramref name="annotation" /> already exists its value will be updated.
/// </summary>
/// <param name="annotation"> The key of the annotation to be added or updated. </param>
/// <param name="value"> The value to be stored in the annotation. </param>
/// <returns> The same builder instance so that multiple configuration calls can be chained. </returns>
public new virtual ReferenceOwnershipBuilder<TEntity, TRelatedEntity> HasForeignKeyAnnotation(
[NotNull] string annotation, [NotNull] object value)
=> (ReferenceOwnershipBuilder<TEntity, TRelatedEntity>)base.HasForeignKeyAnnotation(annotation, value);
/// <summary>
/// <para>
/// Configures the property(s) to use as the foreign key for this relationship.
/// </para>
/// <para>
/// If the specified property name(s) do not exist on the entity type then a new shadow state
/// property(s) will be added to serve as the foreign key. A shadow state property is one
/// that does not have a corresponding property in the entity class. The current value for the
/// property is stored in the <see cref="ChangeTracker" /> rather than being stored in instances
/// of the entity class.
/// </para>
/// <para>
/// If <see cref="HasPrincipalKey(string[])" /> is not specified, then an attempt will be made to
/// match the data type and order of foreign key properties against the primary key of the principal
/// entity type. If they do not match, new shadow state properties that form a unique index will be
/// added to the principal entity type to serve as the reference key.
/// </para>
/// </summary>
/// <param name="foreignKeyPropertyNames">
/// The name(s) of the foreign key property(s).
/// </param>
/// <returns> The same builder instance so that multiple configuration calls can be chained. </returns>
public new virtual ReferenceOwnershipBuilder<TEntity, TRelatedEntity> HasForeignKey(
[NotNull] params string[] foreignKeyPropertyNames)
=> new ReferenceOwnershipBuilder<TEntity, TRelatedEntity>(
Builder.HasForeignKey(
Check.NotNull(foreignKeyPropertyNames, nameof(foreignKeyPropertyNames)),
RelatedEntityType,
ConfigurationSource.Explicit),
this,
foreignKeySet: true);
/// <summary>
/// <para>
/// Configures the property(s) to use as the foreign key for this relationship.
/// </para>
/// <para>
/// If the specified property name(s) do not exist on the entity type then a new shadow state
/// property(s) will be added to serve as the foreign key. A shadow state property is one
/// that does not have a corresponding property in the entity class. The current value for the
/// property is stored in the <see cref="ChangeTracker" /> rather than being stored in instances
/// of the entity class.
/// </para>
/// <para>
/// If <see cref="HasPrincipalKey(string[])" /> is not specified, then an attempt will be made to
/// match the data type and order of foreign key properties against the primary key of the principal
/// entity type. If they do not match, new shadow state properties that form a unique index will be
/// added to the principal entity type to serve as the reference key.
/// </para>
/// </summary>
/// <param name="foreignKeyExpression">
/// <para>
/// A lambda expression representing the foreign key property(s) (<c>t => t.Id1</c>).
/// </para>
/// <para>
/// If the foreign key is made up of multiple properties then specify an anonymous type including the
/// properties (<c>t => new { t.Id1, t.Id2 }</c>). The order specified should match the order of
/// corresponding keys in <see cref="HasPrincipalKey(string[])" />.
/// </para>
/// </param>
/// <returns> The same builder instance so that multiple configuration calls can be chained. </returns>
public virtual ReferenceOwnershipBuilder<TEntity, TRelatedEntity> HasForeignKey(
[NotNull] Expression<Func<TRelatedEntity, object>> foreignKeyExpression)
=> new ReferenceOwnershipBuilder<TEntity, TRelatedEntity>(
Builder.HasForeignKey(
Check.NotNull(foreignKeyExpression, nameof(foreignKeyExpression)).GetPropertyAccessList(),
RelatedEntityType,
ConfigurationSource.Explicit),
this,
foreignKeySet: true);
/// <summary>
/// Configures the unique property(s) that this relationship targets. Typically you would only call this
/// method if you want to use a property(s) other than the primary key as the principal property(s). If
/// the specified property(s) is not already a unique constraint (or the primary key) then a new unique
/// constraint will be introduced.
/// </summary>
/// <remarks>
/// <para>
/// If multiple principal key properties are specified, the order of principal key properties should
/// match the order that the primary key or unique constraint properties were configured on the principal
/// entity type.
/// </para>
/// </remarks>
/// <param name="keyPropertyNames"> The name(s) of the reference key property(s). </param>
/// <returns> The same builder instance so that multiple configuration calls can be chained. </returns>
public new virtual ReferenceOwnershipBuilder<TEntity, TRelatedEntity> HasPrincipalKey(
[NotNull] params string[] keyPropertyNames)
=> new ReferenceOwnershipBuilder<TEntity, TRelatedEntity>(
Builder.HasPrincipalKey(
Check.NotNull(keyPropertyNames, nameof(keyPropertyNames)),
ConfigurationSource.Explicit),
this,
principalKeySet: true);
/// <summary>
/// Configures the unique property(s) that this relationship targets. Typically you would only call this
/// method if you want to use a property(s) other than the primary key as the principal property(s). If
/// the specified property(s) is not already a unique constraint (or the primary key) then a new unique
/// constraint will be introduced.
/// </summary>
/// <remarks>
/// <para>
/// If multiple principal key properties are specified, the order of principal key properties should
/// match the order that the primary key or unique constraint properties were configured on the principal
/// entity type.
/// </para>
/// </remarks>
/// <param name="keyExpression">
/// <para>
/// A lambda expression representing the reference key property(s) (<c>t => t.Id</c>).
/// </para>
/// <para>
/// If the principal key is made up of multiple properties then specify an anonymous type including
/// the properties (<c>t => new { t.Id1, t.Id2 }</c>).
/// </para>
/// </param>
/// <returns> The same builder instance so that multiple configuration calls can be chained. </returns>
public virtual ReferenceOwnershipBuilder<TEntity, TRelatedEntity> HasPrincipalKey(
[NotNull] Expression<Func<TEntity, object>> keyExpression)
=> new ReferenceOwnershipBuilder<TEntity, TRelatedEntity>(
Builder.HasPrincipalKey(
Check.NotNull(keyExpression, nameof(keyExpression)).GetPropertyAccessList(),
ConfigurationSource.Explicit),
this,
principalKeySet: true);
/// <summary>
/// Configures how a delete operation is applied to dependent entities in the relationship when the
/// principal is deleted or the relationship is severed.
/// </summary>
/// <param name="deleteBehavior"> The action to perform. </param>
/// <returns> The same builder instance so that multiple configuration calls can be chained. </returns>
public new virtual ReferenceOwnershipBuilder<TEntity, TRelatedEntity> OnDelete(DeleteBehavior deleteBehavior)
=> new ReferenceOwnershipBuilder<TEntity, TRelatedEntity>(
Builder.DeleteBehavior(deleteBehavior, ConfigurationSource.Explicit), this);
/// <summary>
/// Adds or updates an annotation on the entity type. If an annotation with the key specified in
/// <paramref name="annotation" /> already exists its value will be updated.
/// </summary>
/// <param name="annotation"> The key of the annotation to be added or updated. </param>
/// <param name="value"> The value to be stored in the annotation. </param>
/// <returns> The same builder instance so that multiple configuration calls can be chained. </returns>
public new virtual ReferenceOwnershipBuilder<TEntity, TRelatedEntity> HasEntityTypeAnnotation(
[NotNull] string annotation, [NotNull] object value)
=> (ReferenceOwnershipBuilder<TEntity, TRelatedEntity>)base.HasEntityTypeAnnotation(annotation, value);
/// <summary>
/// <para>
/// Returns an object that can be used to configure a property of the entity type.
/// If no property with the given name exists, then a new property will be added.
/// </para>
/// <para>
/// When adding a new property, if a property with the same name exists in the entity class
/// then it will be added to the model. If no property exists in the entity class, then
/// a new shadow state property will be added. A shadow state property is one that does not have a
/// corresponding property in the entity class. The current value for the property is stored in
/// the <see cref="ChangeTracker" /> rather than being stored in instances of the entity class.
/// </para>
/// </summary>
/// <typeparam name="TProperty"> The type of the property to be configured. </typeparam>
/// <param name="propertyExpression">
/// A lambda expression representing the property to be configured (
/// <c>blog => blog.Url</c>).
/// </param>
/// <returns> An object that can be used to configure the property. </returns>
public virtual PropertyBuilder<TProperty> Property<TProperty>([NotNull] Expression<Func<TRelatedEntity, TProperty>> propertyExpression)
=> new PropertyBuilder<TProperty>(RelatedEntityType.Builder.Property(
Check.NotNull(propertyExpression, nameof(propertyExpression)).GetPropertyAccess(),
ConfigurationSource.Explicit));
/// <summary>
/// Excludes the given property from the entity type. This method is typically used to remove properties
/// from the entity type that were added by convention.
/// </summary>
/// <param name="propertyName"> The name of then property to be removed from the entity type. </param>
public new virtual ReferenceOwnershipBuilder<TEntity, TRelatedEntity> Ignore([NotNull] string propertyName)
=> (ReferenceOwnershipBuilder<TEntity, TRelatedEntity>)base.Ignore(propertyName);
/// <summary>
/// Excludes the given property from the entity type. This method is typically used to remove properties
/// from the entity type that were added by convention.
/// </summary>
/// <param name="propertyExpression">
/// A lambda expression representing the property to be ignored
/// (<c>blog => blog.Url</c>).
/// </param>
public virtual ReferenceOwnershipBuilder<TEntity, TRelatedEntity> Ignore(
[NotNull] Expression<Func<TRelatedEntity, object>> propertyExpression)
=> (ReferenceOwnershipBuilder<TEntity, TRelatedEntity>)
base.Ignore(Check.NotNull(propertyExpression, nameof(propertyExpression)).GetPropertyAccess().Name);
/// <summary>
/// Configures an index on the specified properties. If there is an existing index on the given
/// set of properties, then the existing index will be returned for configuration.
/// </summary>
/// <param name="indexExpression">
/// <para>
/// A lambda expression representing the property(s) to be included in the index
/// (<c>blog => blog.Url</c>).
/// </para>
/// <para>
/// If the index is made up of multiple properties then specify an anonymous type including the
/// properties (<c>post => new { post.Title, post.BlogId }</c>).
/// </para>
/// </param>
/// <returns> An object that can be used to configure the index. </returns>
public virtual IndexBuilder HasIndex([NotNull] Expression<Func<TEntity, object>> indexExpression)
=> new IndexBuilder(RelatedEntityType.Builder.HasIndex(
Check.NotNull(indexExpression, nameof(indexExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit));
/// <summary>
/// <para>
/// Configures a relationship where the target entity is owned by (or part of) this entity.
/// The target entity key value is always propagated from the entity it belongs to.
/// </para>
/// <para>
/// The target entity type for each ownership relationship is treated as a different entity type
/// even if the navigation is of the same type. Configuration of the target entity type
/// isn't applied to the target entity type of other ownership relationships.
/// </para>
/// <para>
/// Most operations on an owned entity require accessing it through the owner entity using the corresponding navigation.
/// </para>
/// </summary>
/// <typeparam name="TNewRelatedEntity"> The entity type that this relationship targets. </typeparam>
/// <param name="navigationExpression">
/// A lambda expression representing the reference navigation property on this entity type that represents
/// the relationship (<c>customer => customer.Address</c>).
/// </param>
/// <returns> An object that can be used to configure the entity type. </returns>
public virtual ReferenceOwnershipBuilder<TRelatedEntity, TNewRelatedEntity> OwnsOne<TNewRelatedEntity>(
[NotNull] Expression<Func<TRelatedEntity, TNewRelatedEntity>> navigationExpression)
where TNewRelatedEntity : class
=> OwnsOneBuilder<TNewRelatedEntity>(Check.NotNull(navigationExpression, nameof(navigationExpression)).GetPropertyAccess());
/// <summary>
/// <para>
/// Configures a relationship where the target entity is owned by (or part of) this entity.
/// The target entity key value is always propagated from the entity it belongs to.
/// </para>
/// <para>
/// The target entity type for each ownership relationship is treated as a different entity type
/// even if the navigation is of the same type. Configuration of the target entity type
/// isn't applied to the target entity type of other ownership relationships.
/// </para>
/// <para>
/// Most operations on an owned entity require accessing it through the owner entity using the corresponding navigation.
/// </para>
/// </summary>
/// <typeparam name="TNewRelatedEntity"> The entity type that this relationship targets. </typeparam>
/// <param name="navigationExpression">
/// A lambda expression representing the reference navigation property on this entity type that represents
/// the relationship (<c>customer => customer.Address</c>).
/// </param>
/// <param name="buildAction"> An action that performs configuration of the relationship. </param>
/// <returns> An object that can be used to configure the entity type. </returns>
public virtual ReferenceOwnershipBuilder<TEntity, TRelatedEntity> OwnsOne<TNewRelatedEntity>(
[NotNull] Expression<Func<TRelatedEntity, TNewRelatedEntity>> navigationExpression,
[NotNull] Action<ReferenceOwnershipBuilder<TRelatedEntity, TNewRelatedEntity>> buildAction)
where TNewRelatedEntity : class
{
Check.NotNull(navigationExpression, nameof(navigationExpression));
Check.NotNull(buildAction, nameof(buildAction));
using (DeclaringEntityType.Model.ConventionDispatcher.StartBatch())
{
buildAction.Invoke(OwnsOneBuilder<TNewRelatedEntity>(navigationExpression.GetPropertyAccess()));
return this;
}
}
private ReferenceOwnershipBuilder<TRelatedEntity, TNewRelatedEntity> OwnsOneBuilder<TNewRelatedEntity>(PropertyInfo navigation)
where TNewRelatedEntity : class
{
InternalRelationshipBuilder relationship;
using (RelatedEntityType.Model.ConventionDispatcher.StartBatch())
{
relationship = RelatedEntityType.Builder.Owns(typeof(TNewRelatedEntity), navigation, ConfigurationSource.Explicit);
relationship.IsUnique(true, ConfigurationSource.Explicit);
}
return new ReferenceOwnershipBuilder<TRelatedEntity, TNewRelatedEntity>(
RelatedEntityType,
relationship.Metadata.DeclaringEntityType,
relationship);
}
/// <summary>
/// <para>
/// Configures a relationship where this entity type has a reference that points
/// to a single instance of the other type in the relationship.
/// </para>
/// <para>
/// After calling this method, you should chain a call to
/// <see cref="ReferenceNavigationBuilder{TEntity,TRelatedEntity}
/// .WithMany(Expression{Func{TRelatedEntity,IEnumerable{TEntity}}})" />
/// or
/// <see cref="ReferenceNavigationBuilder{TEntity,TRelatedEntity}
/// .WithOne(Expression{Func{TRelatedEntity,TEntity}})" />
/// to fully configure the relationship. Calling just this method without the chained call will not
/// produce a valid relationship.
/// </para>
/// </summary>
/// <typeparam name="TNewRelatedEntity"> The entity type that this relationship targets. </typeparam>
/// <param name="navigationExpression">
/// A lambda expression representing the reference navigation property on this entity type that represents
/// the relationship (<c>post => post.Blog</c>). If no property is specified, the relationship will be
/// configured without a navigation property on this end.
/// </param>
/// <returns> An object that can be used to configure the relationship. </returns>
public virtual ReferenceNavigationBuilder<TRelatedEntity, TNewRelatedEntity> HasOne<TNewRelatedEntity>(
[CanBeNull] Expression<Func<TRelatedEntity, TNewRelatedEntity>> navigationExpression = null)
where TNewRelatedEntity : class
{
var relatedEntityType = RelatedEntityType.FindInDefinitionPath(typeof(TNewRelatedEntity)) ??
Builder.ModelBuilder.Entity(typeof(TNewRelatedEntity), ConfigurationSource.Explicit).Metadata;
var navigation = navigationExpression?.GetPropertyAccess();
return new ReferenceNavigationBuilder<TRelatedEntity, TNewRelatedEntity>(
RelatedEntityType,
relatedEntityType,
navigation,
RelatedEntityType.Builder.Navigation(relatedEntityType.Builder, navigation, ConfigurationSource.Explicit,
setTargetAsPrincipal: RelatedEntityType == relatedEntityType));
}
/// <summary>
/// <para>
/// Configures a relationship where this entity type has a collection that contains
/// instances of the other type in the relationship.
/// </para>
/// <para>
/// After calling this method, you should chain a call to
/// <see cref="CollectionNavigationBuilder{TEntity,TRelatedEntity}
/// .WithOne(Expression{Func{TRelatedEntity,TEntity}})" />
/// to fully configure the relationship. Calling just this method without the chained call will not
/// produce a valid relationship.
/// </para>
/// </summary>
/// <typeparam name="TNewRelatedEntity"> The entity type that this relationship targets. </typeparam>
/// <param name="navigationExpression">
/// A lambda expression representing the collection navigation property on this entity type that represents
/// the relationship (<c>blog => blog.Posts</c>). If no property is specified, the relationship will be
/// configured without a navigation property on this end.
/// </param>
/// <returns> An object that can be used to configure the relationship. </returns>
public virtual CollectionNavigationBuilder<TRelatedEntity, TNewRelatedEntity> HasMany<TNewRelatedEntity>(
[CanBeNull] Expression<Func<TRelatedEntity, IEnumerable<TNewRelatedEntity>>> navigationExpression = null)
where TNewRelatedEntity : class
{
var relatedEntityType = Builder.ModelBuilder.Entity(typeof(TNewRelatedEntity), ConfigurationSource.Explicit).Metadata;
var navigation = navigationExpression?.GetPropertyAccess();
InternalRelationshipBuilder relationship;
using (var batch = RelatedEntityType.Model.ConventionDispatcher.StartBatch())
{
relationship = relatedEntityType.Builder
.Relationship(RelatedEntityType.Builder, ConfigurationSource.Explicit)
.IsUnique(false, ConfigurationSource.Explicit)
.RelatedEntityTypes(RelatedEntityType, relatedEntityType, ConfigurationSource.Explicit)
.PrincipalToDependent(navigation, ConfigurationSource.Explicit);
relationship = batch.Run(relationship);
}
return new CollectionNavigationBuilder<TRelatedEntity, TNewRelatedEntity>(
RelatedEntityType,
relatedEntityType,
navigation,
relationship);
}
/// <summary>
/// Configures the <see cref="ChangeTrackingStrategy" /> to be used for this entity type.
/// This strategy indicates how the context detects changes to properties for an instance of the entity type.
/// </summary>
/// <param name="changeTrackingStrategy"> The change tracking strategy to be used. </param>
/// <returns> The same builder instance so that multiple configuration calls can be chained. </returns>
public new virtual ReferenceOwnershipBuilder<TEntity, TRelatedEntity> HasChangeTrackingStrategy(
ChangeTrackingStrategy changeTrackingStrategy)
=> (ReferenceOwnershipBuilder<TEntity, TRelatedEntity>)base.HasChangeTrackingStrategy(changeTrackingStrategy);
/// <summary>
/// <para>
/// Sets the <see cref="PropertyAccessMode" /> to use for all properties of this entity type.
/// </para>
/// <para>
/// By default, the backing field, if one is found by convention or has been specified, is used when
/// new objects are constructed, typically when entities are queried from the database.
/// Properties are used for all other accesses. Calling this method witll change that behavior
/// for all properties of this entity type as described in the <see cref="PropertyAccessMode" /> enum.
/// </para>
/// <para>
/// Calling this method overrides for all properties of this entity type any access mode that was
/// set on the model.
/// </para>
/// </summary>
/// <param name="propertyAccessMode"> The <see cref="PropertyAccessMode" /> to use for properties of this entity type. </param>
/// <returns> The same builder instance so that multiple configuration calls can be chained. </returns>
public new virtual ReferenceOwnershipBuilder<TEntity, TRelatedEntity> UsePropertyAccessMode(PropertyAccessMode propertyAccessMode)
=> (ReferenceOwnershipBuilder<TEntity, TRelatedEntity>)base.UsePropertyAccessMode(propertyAccessMode);
}
}
| 60.198718 | 143 | 0.629468 | [
"Apache-2.0"
] | vadzimpm/EntityFramework | src/EFCore/Metadata/Builders/ReferenceOwnershipBuilder`.cs | 28,175 | C# |
//-----------------------------------------------------------------------
// <copyright file="SplitBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace Csla.Test.DataPortalTest
{
[Serializable()]
public abstract class SplitBase<T> : Csla.BusinessBase<T>
where T : SplitBase<T>
{
#region Business Methods
public static PropertyInfo<int> IdProperty = RegisterProperty<int>(c => c.Id, RelationshipTypes.PrivateField);
private int _id = IdProperty.DefaultValue;
public int Id
{
get { return GetProperty(IdProperty, _id); }
set { SetProperty(IdProperty, ref _id, value); }
}
#endregion
#region Factory Methods
public static T NewObject()
{
return Csla.DataPortal.Create<T>();
}
public static T GetObject(int id)
{
return Csla.DataPortal.Fetch<T>(new Criteria(id));
}
public static void DeleteObject(int id)
{
Csla.DataPortal.Delete<T>(new Criteria(id));
}
#endregion
#region Data Access
[Serializable()]
private class Criteria : CriteriaBase<Criteria>
{
private int _id;
public int Id
{
get { return _id; }
}
public Criteria(int id)
{ _id = id; }
}
protected override void DataPortal_Create()
{
_id = 0;
Csla.ApplicationContext.GlobalContext.Clear();
ApplicationContext.GlobalContext.Add("Split", "Created");
}
private void DataPortal_Fetch(Criteria criteria)
{
_id = criteria.Id;
Csla.ApplicationContext.GlobalContext.Clear();
ApplicationContext.GlobalContext.Add("Split", "Fetched");
}
protected override void DataPortal_Insert()
{
Csla.ApplicationContext.GlobalContext.Clear();
ApplicationContext.GlobalContext.Add("Split", "Inserted");
}
protected override void DataPortal_Update()
{
Csla.ApplicationContext.GlobalContext.Clear();
ApplicationContext.GlobalContext.Add("Split", "Updated");
}
private void DataPortal_Delete(Criteria criteria)
{
Csla.ApplicationContext.GlobalContext.Clear();
ApplicationContext.GlobalContext.Add("Split", "Deleted");
}
protected override void DataPortal_DeleteSelf()
{
Csla.ApplicationContext.GlobalContext.Clear();
ApplicationContext.GlobalContext.Add("Split", "SelfDeleted");
}
#endregion
}
} | 25.737864 | 114 | 0.623916 | [
"MIT"
] | Alstig/csla | Source/Csla.test/DataPortal/SplitBase.cs | 2,651 | C# |
using System;
using System.Collections.Generic;
using DDDSample1.Domain.VehicleDuties;
using DDDSample1.Domain.Shared;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
[TestClass]
public class VehicleDutyMapperTest
{
[TestMethod]
public void testToDTO()
{
string key = "vdkey";
string vehicle = "vehicle1";
DateTime date = new DateTime(2022, 10, 11);
List<String> trips = new List<string>() { "trip1", "trip2", "trip3" };
List<String> workblocks = new List<string>() { "wb1", "wb2", "wb3" };
long dateMiliseconds = (long)(new TimeSpan(date.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks)).TotalMilliseconds;
CreatingVehicleDutyDto cvddto = new CreatingVehicleDutyDto(key, vehicle, dateMiliseconds, trips.ToArray(), workblocks.ToArray());
VehicleDutyDto vddtoMapper = VehicleDutyMapper.toDTO(cvddto);
VehicleDutyDto vddto = new VehicleDutyDto(key, vehicle, date, trips, workblocks);
Assert.AreEqual(vddto.Key, vddtoMapper.Key);
Assert.AreEqual(vddto.Vehicle, vddtoMapper.Vehicle);
Assert.AreEqual(vddto.Date, vddtoMapper.Date);
foreach (String s in vddtoMapper.Trips)
{
Assert.IsNotNull(vddto.Trips.Contains(s));
}
foreach (String s in vddtoMapper.Workblocks)
{
Assert.IsNotNull(vddtoMapper.Workblocks.Contains(s));
}
}
[TestMethod]
public void testToDomain()
{
string key = "vdkey";
string vehicle = "vehicle1";
DateTime date = new DateTime(2022, 10, 11);
List<String> trips = new List<string>() { "trip1", "trip2", "trip3" };
List<String> workblocks = new List<string>() { "wb1", "wb2", "wb3" };
long dateMiliseconds = (long)(new TimeSpan(date.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks)).TotalMilliseconds;
VehicleDuty vdMapper = VehicleDutyMapper.toDomain(VehicleDutyMapper.toDTO(new CreatingVehicleDutyDto(key, vehicle, dateMiliseconds, trips.ToArray(), workblocks.ToArray())));
VehicleDuty vd = new VehicleDuty(key, vehicle, date, trips, workblocks);
Assert.AreEqual(vdMapper.Key, vd.Key);
Assert.AreEqual(vdMapper.Vehicle, vd.Vehicle);
Assert.AreEqual(vdMapper.Date, vd.Date);
foreach (VDTripKey vdk in vd.Trips)
{
Assert.IsNotNull(vdMapper.Trips.Contains(vdk));
}
foreach (VDWorkblockKey vdwb in vd.Workblocks)
{
Assert.IsNotNull(vdMapper.Workblocks.Contains(vdwb));
}
}
}
} | 43.353846 | 185 | 0.608233 | [
"MIT"
] | TRibeiro94/ISEP-ARQSI-2020 | Semester_Project/MDV/Tests/UnitTests/Domain/VehicleDuties/VehicleDutyMapper.cs | 2,818 | C# |
using FluentValidation;
using UnitsNet;
using UnitsNet.NumberExtensions.NumberToRatio;
using VCRC.Components;
namespace VCRC.Validators;
public class CompressorValidator : AbstractValidator<Compressor>
{
public CompressorValidator()
{
RuleFor(compressor => compressor.IsentropicEfficiency).ExclusiveBetween(Ratio.Zero, 100.Percent())
.WithMessage("Isentropic efficiency of the compressor should be in (0;100) %!");
}
} | 30.2 | 106 | 0.754967 | [
"MIT"
] | portyanikhin/VCRC | VCRC/Validators/CompressorValidator.cs | 455 | C# |
using System;
using Stringier.Patterns.Errors;
using Stringier.Patterns.Debugging;
namespace Stringier.Patterns.Nodes {
/// <summary>
/// Represents a <see cref="Ranger"/> which supports nesting of the range.
/// </summary>
internal sealed class NestedRanger : Ranger {
/// <summary>
/// The current nesting level.
/// </summary>
private Int32 Level;
/// <summary>
/// Initialize a new <see cref="NestedRanger"/> with the given <paramref name="from"/> and <paramref name="to"/>
/// </summary>
/// <param name="from">The <see cref="Pattern"/> to start from.</param>
/// <param name="to">The <see cref="Pattern"/> to read to.</param>
internal NestedRanger(Pattern from, Pattern to) : base(from, to) => Level = 0;
/// <summary>
/// Call the Consume parser of this <see cref="Node"/> on the <paramref name="source"/> with the <paramref name="result"/>.
/// </summary>
/// <param name="source">The <see cref="Source"/> to consume.</param>
/// <param name="result">A <see cref="Result"/> containing whether a match occured and the captured <see cref="String"/>.</param>
/// <param name="trace">The <see cref="ITrace"/> to record steps in.</param>
internal override void Consume(ref Source source, ref Result result, ITrace? trace) {
From.Consume(ref source, ref result, trace);
if (result) {
Level++;
}
while (Level > 0) {
if (source.EOF) {
break;
}
source.Position++;
result.Length++;
if (From.CheckHeader(ref source)) {
From.Consume(ref source, ref result, trace);
if (result) {
Level++;
}
}
if (To.CheckHeader(ref source)) {
To.Consume(ref source, ref result, trace);
if (result) {
Level--;
}
}
}
if (Level != 0) {
result.Error.Set(ErrorType.ConsumeFailed, this);
}
}
}
}
| 31.413793 | 131 | 0.62404 | [
"BSD-3-Clause"
] | HugoRoss/Stringier | Patterns/Nodes/NestedRanger.cs | 1,824 | C# |
using DHwD_web.Data.Interfaces;
using DHwD_web.Helpers;
using Microsoft.EntityFrameworkCore;
using Models.ModelsDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DHwD_web.Data
{
public class SqlUserRepo : IUserRepo
{
private readonly AppWebDbContext _dbContext;
public SqlUserRepo(AppWebDbContext dbContext)
{
_dbContext = dbContext;
}
public bool CreateNewUser(User user)
{
Points points = new Points();
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
if (GetUserByNickName_Token(user.NickName, user.Token) != null)
return false;
_dbContext.Users.Add(user);
try
{
SaveChanges();
}
catch (Exception)
{
return false;
}
var a = GetUserByNickName_Token(user.NickName, user.Token);
points.UserId = a.Id;
points.DataTimeEdit = DateTime.UtcNow;
points.DataTimeCreate = DateTime.UtcNow;
_dbContext.Points.Add(points);
SaveChanges();
return true;
}
public IEnumerable<User> GetallUser()
{
return _dbContext.Users.ToList();
}
public async Task<User> GetUserById(int id)
{
return await Task.FromResult<User>(_dbContext.Users.FirstOrDefault(x => x.Id == id));
}
public User GetUserByNickName_Token(string nickName, string token)
{
return _dbContext.Users.FirstOrDefault(x => x.NickName == nickName && x.Token == token);
}
public bool SaveChanges()
{
try
{
return (_dbContext.SaveChanges() >= 0);
}
catch (DbUpdateConcurrencyException)
{
return false;
}
catch (DbUpdateException)
{
return false;
}
catch (Exception)
{
return false;
}
}
}
}
| 26.547619 | 100 | 0.521076 | [
"MIT"
] | MateuszLas421/DHwD_web | DHwD_web/Data/SqlUserRepo.cs | 2,232 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Tanure.CalendarPOC.Models;
using Xamarin.Forms;
namespace Tanure.CalendarPOC.ViewModels
{
public class CalendarViewModel : ViewModelBase
{
public event EventHandler<DayModel[,]> OnMakeCalendar;
private Tanure.CalendarPOC.Models.CalendarModel _calendar;
public CalendarViewModel()
{
_calendar = new Tanure.CalendarPOC.Models.CalendarModel(DateTime.Now);
this.PriorCommand = new Command(() =>
{
_calendar.PriorMonth();
OnPropertyChanged(nameof(YearMonthLabel));
OnPropertyChanged(nameof(SelectedDates));
this.RefreshChanges();
});
this.NextCommand = new Command(() =>
{
_calendar.NextMonth();
OnPropertyChanged(nameof(YearMonthLabel));
OnPropertyChanged(nameof(SelectedDates));
this.RefreshChanges();
});
}
#region [ Commands ]
public ICommand NextCommand { get; protected set; }
public ICommand PriorCommand { get; protected set; }
#endregion
public ObservableCollection<DayModel> SelectedDates
{
get
{
return _calendar.GetSelectedDates();
}
}
public void Draw()
{
this.RefreshChanges();
}
public string YearMonthLabel
{
get { return $"{CultureInfo.CurrentUICulture.DateTimeFormat.AbbreviatedMonthNames[_calendar.CurrentMonth - 1]} / {_calendar.CurrentYear} "; }
}
public void UpdateSelectedDates()
{
OnPropertyChanged(nameof(SelectedDates));
}
private void RefreshChanges()
{
OnMakeCalendar?.Invoke(this, _calendar.CurrentCalendar);
}
}
}
| 25.238095 | 153 | 0.596698 | [
"MIT"
] | tanure/XFCalendar | Tanure.CalendarPOC/ViewModels/CalendarViewModel.cs | 2,122 | C# |
using System;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
using SFA.DAS.RoatpOversight.Web.Domain;
namespace SFA.DAS.RoatpOversight.Web.Extensions
{
public static class HtmlHelperExtensions
{
public static HtmlString AddClassIfPropertyInError<TModel, TProperty>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string errorClass)
{
var expressionText = ExpressionHelper.GetExpressionText(expression);
var fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionText);
var state = htmlHelper.ViewData.ModelState[fullHtmlFieldName];
if (state?.Errors == null || state.Errors.Count == 0)
{
return HtmlString.Empty;
}
return new HtmlString(errorClass);
}
}
}
| 34.133333 | 118 | 0.68457 | [
"MIT"
] | SkillsFundingAgency/das-roatp-oversight | src/SFA.DAS.RoatpOversight.Web/Extensions/HtmlHelperExtensions.cs | 1,026 | C# |
namespace SkorubaIdentityServer4Admin.Admin.Api.ExceptionHandling
{
public class ApiError
{
public string Code { get; set; }
public string Description { get; set; }
}
}
| 13.6 | 66 | 0.642157 | [
"MIT"
] | 1n5an1ty/IdentityServer4.Admin | templates/template-publish/content/src/SkorubaIdentityServer4Admin.Admin.Api/ExceptionHandling/ApiError.cs | 206 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using myEcommerce.WebUI;
using myEcommerce.WebUI.Controllers;
namespace myEcommerce.WebUI.Tests.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void About()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.About() as ViewResult;
// Assert
Assert.AreEqual("Your application description page.", result.ViewBag.Message);
}
[TestMethod]
public void Contact()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Contact() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
}
| 23.636364 | 90 | 0.576923 | [
"MIT"
] | wchandler2018/ecommerceASP.NET | myEcommerce/myEcommerce.WebUI.Tests/Controllers/HomeControllerTest.cs | 1,302 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TeamCitySharp.Fields
{
public class LastChangesField : IField
{
#region Properties
public ChangeField ChangeField { get; private set; }
public bool Count { get; private set; }
#endregion
#region Public Methods
public static LastChangesField WithFields(ChangeField changeField = null, bool count = true)
{
return new LastChangesField
{
ChangeField = changeField,
Count = count
};
}
#endregion
#region Overrides IField
public string FieldId
{
get { return "lastChanges"; }
}
public override string ToString()
{
var currentFields = String.Empty;
FieldHelper.AddField(Count, ref currentFields, "count");
FieldHelper.AddFieldGroup(ChangeField, ref currentFields);
return currentFields;
}
#endregion
}
}
| 18.823529 | 96 | 0.652083 | [
"MIT"
] | MVS-Telecom/TeamCitySharp | src/TeamCitySharp/Fields/LastChangesField.cs | 962 | C# |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace StateFunding
{
public static class KerbalHelper
{
public static Vessel GetVessel(ProtoCrewMember Kerb)
{
Vessel[] Vessels = (Vessel[])FlightGlobals.Vessels.ToArray();
for (int i = 0; i < Vessels.Length; i++)
{
Vessel Vsl = Vessels[i];
ProtoCrewMember[] Crew = Vsl.GetVesselCrew().ToArray();
for (int k = 0; k < Crew.Length; k++)
{
ProtoCrewMember CrewMember = Crew[k];
if (CrewMember.name == Kerb.name)
{
return Vsl;
}
}
}
return null;
}
public static ProtoCrewMember[] GetActiveKerbals()
{
List<ProtoCrewMember> ReturnKerbals = new List<ProtoCrewMember>();
IEnumerator Kerbals = HighLogic.CurrentGame.CrewRoster.Crew.GetEnumerator();
while (Kerbals.MoveNext())
{
ProtoCrewMember Kerbal = (ProtoCrewMember)Kerbals.Current;
if (Kerbal.rosterStatus.ToString() == "Assigned")
{
if (!KerbalHelper.IsStranded(Kerbal))
{
ReturnKerbals.Add(Kerbal);
}
}
}
return ReturnKerbals.ToArray();
}
public static bool IsStranded(ProtoCrewMember Kerb)
{
Vessel Vsl = GetVessel(Kerb);
if (Vsl != null
&& KerbalHelper.QualifiedStranded(Kerb)
&& Vsl.missionTime > TimeHelper.ToYears(2))
{
return true;
}
return false;
}
public static int TimeToStranded(ProtoCrewMember Kerb)
{
Vessel Vsl = GetVessel(Kerb);
if (Vsl != null)
{
return TimeHelper.Days(TimeHelper.ToYears(2) - Vsl.missionTime);
}
return 0;
}
public static bool QualifiedStranded(ProtoCrewMember Kerb)
{
Vessel Vsl = GetVessel(Kerb);
if (Vsl != null
&& Vsl.protoVessel.vesselType != VesselType.Base
&& Vsl.protoVessel.vesselType != VesselType.Rover
&& Vsl.protoVessel.vesselType != VesselType.Station)
{
if (!VesselHelper.HasLiquidFuel(Vsl) || !VesselHelper.HasEnergy(Vsl))
{
if (!VesselHelper.VesselHasModuleAlias(Vsl, "ScienceLab"))
{
if (!VesselHelper.VesselHasModuleAlias(Vsl, "Drill"))
{
return true;
}
}
}
}
return false;
}
public static ProtoCrewMember[] GetStrandedKerbals()
{
List<ProtoCrewMember> ReturnKerbals = new List<ProtoCrewMember>();
IEnumerator Kerbals = HighLogic.CurrentGame.CrewRoster.Crew.GetEnumerator();
while (Kerbals.MoveNext())
{
ProtoCrewMember Kerbal = (ProtoCrewMember)Kerbals.Current;
if (KerbalHelper.IsStranded(Kerbal))
{
ReturnKerbals.Add(Kerbal);
}
}
return ReturnKerbals.ToArray();
}
public static ProtoCrewMember[] GetKerbals()
{
List<ProtoCrewMember> ReturnKerbals = new List<ProtoCrewMember>();
IEnumerator Kerbals = HighLogic.CurrentGame.CrewRoster.Crew.GetEnumerator();
while (Kerbals.MoveNext())
{
ProtoCrewMember Kerbal = (ProtoCrewMember)Kerbals.Current;
if (Kerbal.rosterStatus.ToString() == "Assigned")
{
ReturnKerbals.Add(Kerbal);
}
}
return ReturnKerbals.ToArray();
}
}
}
| 29.55 | 88 | 0.49021 | [
"MIT"
] | Alohacajun/StateFundingContinued | Source/Helpers/KerbalHelper.cs | 4,139 | C# |
using Microsoft.EntityFrameworkCore;
using ProjectName.Core.Models;
namespace ProjectName.DAL
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions options) : base(options)
{
}
public DbSet<Item> Items { get; set; }
public DbSet<Article> Articles { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
ConfigureEntityItem(builder);
}
private void ConfigureEntityItem(ModelBuilder builder)
{
builder.Entity<Item>()
.Property(t => t.Name)
.HasMaxLength(50)
.IsRequired();
}
}
} | 24.928571 | 69 | 0.583095 | [
"MIT"
] | amularczyk/webapi-core-boilerplate | ProjectName/ProjectName.DAL/DataContext.cs | 700 | C# |
using Microsoft.Win32;
using System;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;
using Tesseract;
namespace CopyTranslatePaste
{
class Utils
{
public static readonly HttpClient HttpClient = new HttpClient();
public static string Base64Code(string Message)
{
byte[] bytes = Encoding.Default.GetBytes(Message);
return Convert.ToBase64String(bytes);
}
public static string Base64Decode(string Message)
{
byte[] bytes = Convert.FromBase64String(Message);
return Encoding.Default.GetString(bytes);
}
public static string TextProcessor(string src)
{
var res = src;
// 连字符单词合并
res = Regex.Replace(res, "([^\n])-\n([^\n])", "$1$2");
// 文本断行合并
res = Regex.Replace(res, "([^\n])\n([^\n])", "$1 $2");
// 多个换行合并成一行
res = Regex.Replace(res, "\n+", "\n");
return res;
}
public async static Task<string> DoOCR(string lang, Pix pix)
{
var task = Task.Run(() =>
{
using var ocr = new TesseractEngine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tessdata"), lang, EngineMode.Default);
using var page = ocr.Process(pix);
return page.GetText();
});
return await task;
}
public static async Task<string> GetContentFromFiles(string lang)
{
var dialog = new OpenFileDialog()
{
Filter = "图像文件(.jpg;*.png)|*.jpg;*.png",
Title = "选取文件"
};
if (dialog.ShowDialog().GetValueOrDefault())
{
string text;
var filePath = dialog.FileName;
try
{
var pix = PixConverter.ToPix(new System.Drawing.Bitmap(filePath));
text = await Utils.DoOCR(lang, pix);
}
catch (Exception exp)
{
throw new Exception($"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tessdata")}\n{exp.Message}");
}
return text ?? "";
}
else
{
return null;
}
}
public static async Task<string> GetContentFromClipboard(string lang)
{
try
{
if (Clipboard.ContainsImage())
{
var pic = Clipboard.GetImage();
var bitMap = new Bitmap(pic.PixelWidth, pic.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
var imageData = bitMap.LockBits(new Rectangle(System.Drawing.Point.Empty, bitMap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
pic.CopyPixels(Int32Rect.Empty, imageData.Scan0, imageData.Height * imageData.Stride, imageData.Stride);
bitMap.UnlockBits(imageData);
var res = await DoOCR(lang, PixConverter.ToPix(bitMap));
return res;
}
else if (Clipboard.ContainsText())
{
return Clipboard.GetText();
}
else
{
return " ℹ 剪切板中无内容,请先复制文字或图片。";
}
}
catch (Exception e)
{
throw new Exception($"读取剪切板异常{e.Message}");
}
}
public static void SetClipboard(string src)
{
Clipboard.SetText(src);
}
public static string GetCurrentVersion()
{
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
public async static Task<string> GetLatestVersion()
{
var task = await Task.Run(async () =>
{
try
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri(ConfigurationManager.AppSettings.Get("LatestOnlineConfig")),
Method = HttpMethod.Get
};
var res = await HttpClient.SendAsync(request);
res.EnsureSuccessStatusCode();
var text = await res.Content.ReadAsStringAsync();
var body = new XmlDocument();
body.LoadXml(text);
return body.SelectSingleNode(".//AssemblyVersion").InnerText;
}
catch (Exception exception)
{
throw new Exception($"获取新版本时遇到错误:{exception.Message}");
}
});
return task;
}
}
}
| 34.351351 | 208 | 0.503344 | [
"MIT"
] | HanyuuFurude/CopyTranslatePaste | Utils.cs | 5,220 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
namespace GitLib
{
using System.Runtime.InteropServices;
public static partial class libgit2
{
/// <summary>
/// Flags for index entries
/// </summary>
public enum git_index_entry_flag_t : int
{
GIT_INDEX_ENTRY_EXTENDED = (int)(0x4000),
GIT_INDEX_ENTRY_VALID = (int)(0x8000),
}
public const git_index_entry_flag_t GIT_INDEX_ENTRY_EXTENDED = git_index_entry_flag_t.GIT_INDEX_ENTRY_EXTENDED;
public const git_index_entry_flag_t GIT_INDEX_ENTRY_VALID = git_index_entry_flag_t.GIT_INDEX_ENTRY_VALID;
/// <summary>
/// Bitmasks for on-disk fields of `git_index_entry`'s `flags_extended`
/// </summary>
/// <remarks>
/// In memory, the `flags_extended` fields are divided into two parts: the
/// fields that are read from and written to disk, and other fields that
/// in-memory only and used by libgit2. Only the flags in
/// `GIT_INDEX_ENTRY_EXTENDED_FLAGS` will get saved on-disk.Thee first three bitmasks match the three fields in the
/// `git_index_entry` `flags_extended` value that belong on disk. You
/// can use them to interpret the data in the `flags_extended`.The rest of the bitmasks match the other fields in the `git_index_entry`
/// `flags_extended` value that are only used in-memory by libgit2.
/// You can use them to interpret the data in the `flags_extended`.
/// </remarks>
[Flags]
public enum git_index_entry_extended_flag_t : int
{
GIT_INDEX_ENTRY_INTENT_TO_ADD = (int)(1 << 13),
GIT_INDEX_ENTRY_SKIP_WORKTREE = (int)(1 << 14),
GIT_INDEX_ENTRY_EXTENDED_FLAGS = (int)(GIT_INDEX_ENTRY_INTENT_TO_ADD | GIT_INDEX_ENTRY_SKIP_WORKTREE),
GIT_INDEX_ENTRY_UPTODATE = (int)(1 << 2),
}
public const git_index_entry_extended_flag_t GIT_INDEX_ENTRY_INTENT_TO_ADD = git_index_entry_extended_flag_t.GIT_INDEX_ENTRY_INTENT_TO_ADD;
public const git_index_entry_extended_flag_t GIT_INDEX_ENTRY_SKIP_WORKTREE = git_index_entry_extended_flag_t.GIT_INDEX_ENTRY_SKIP_WORKTREE;
public const git_index_entry_extended_flag_t GIT_INDEX_ENTRY_EXTENDED_FLAGS = git_index_entry_extended_flag_t.GIT_INDEX_ENTRY_EXTENDED_FLAGS;
public const git_index_entry_extended_flag_t GIT_INDEX_ENTRY_UPTODATE = git_index_entry_extended_flag_t.GIT_INDEX_ENTRY_UPTODATE;
/// <summary>
/// Capabilities of system that affect index actions.
/// </summary>
public enum git_index_capability_t : int
{
GIT_INDEX_CAPABILITY_IGNORE_CASE = (int)1,
GIT_INDEX_CAPABILITY_NO_FILEMODE = (int)2,
GIT_INDEX_CAPABILITY_NO_SYMLINKS = (int)4,
GIT_INDEX_CAPABILITY_FROM_OWNER = (int)-1,
}
public const git_index_capability_t GIT_INDEX_CAPABILITY_IGNORE_CASE = git_index_capability_t.GIT_INDEX_CAPABILITY_IGNORE_CASE;
public const git_index_capability_t GIT_INDEX_CAPABILITY_NO_FILEMODE = git_index_capability_t.GIT_INDEX_CAPABILITY_NO_FILEMODE;
public const git_index_capability_t GIT_INDEX_CAPABILITY_NO_SYMLINKS = git_index_capability_t.GIT_INDEX_CAPABILITY_NO_SYMLINKS;
public const git_index_capability_t GIT_INDEX_CAPABILITY_FROM_OWNER = git_index_capability_t.GIT_INDEX_CAPABILITY_FROM_OWNER;
/// <summary>
/// Flags for APIs that add files matching pathspec
/// </summary>
[Flags]
public enum git_index_add_option_t : int
{
GIT_INDEX_ADD_DEFAULT = (int)0,
GIT_INDEX_ADD_FORCE = (int)(1u<<0),
GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH = (int)(1u<<1),
GIT_INDEX_ADD_CHECK_PATHSPEC = (int)(1u<<2),
}
public const git_index_add_option_t GIT_INDEX_ADD_DEFAULT = git_index_add_option_t.GIT_INDEX_ADD_DEFAULT;
public const git_index_add_option_t GIT_INDEX_ADD_FORCE = git_index_add_option_t.GIT_INDEX_ADD_FORCE;
public const git_index_add_option_t GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH = git_index_add_option_t.GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH;
public const git_index_add_option_t GIT_INDEX_ADD_CHECK_PATHSPEC = git_index_add_option_t.GIT_INDEX_ADD_CHECK_PATHSPEC;
public enum git_index_stage_t : int
{
/// <summary>
/// Match any index stage.
/// </summary>
/// <remarks>
/// Some index APIs take a stage to match; pass this value to match
/// any entry matching the path regardless of stage.
/// </remarks>
GIT_INDEX_STAGE_ANY = (int)-1,
/// <summary>
/// A normal staged file in the index.
/// </summary>
GIT_INDEX_STAGE_NORMAL = (int)0,
/// <summary>
/// The ancestor side of a conflict.
/// </summary>
GIT_INDEX_STAGE_ANCESTOR = (int)1,
/// <summary>
/// The "ours" side of a conflict.
/// </summary>
GIT_INDEX_STAGE_OURS = (int)2,
/// <summary>
/// The "theirs" side of a conflict.
/// </summary>
GIT_INDEX_STAGE_THEIRS = (int)3,
}
/// <summary>
/// Match any index stage.
/// </summary>
/// <remarks>
/// Some index APIs take a stage to match; pass this value to match
/// any entry matching the path regardless of stage.
/// </remarks>
public const git_index_stage_t GIT_INDEX_STAGE_ANY = git_index_stage_t.GIT_INDEX_STAGE_ANY;
/// <summary>
/// A normal staged file in the index.
/// </summary>
public const git_index_stage_t GIT_INDEX_STAGE_NORMAL = git_index_stage_t.GIT_INDEX_STAGE_NORMAL;
/// <summary>
/// The ancestor side of a conflict.
/// </summary>
public const git_index_stage_t GIT_INDEX_STAGE_ANCESTOR = git_index_stage_t.GIT_INDEX_STAGE_ANCESTOR;
/// <summary>
/// The "ours" side of a conflict.
/// </summary>
public const git_index_stage_t GIT_INDEX_STAGE_OURS = git_index_stage_t.GIT_INDEX_STAGE_OURS;
/// <summary>
/// The "theirs" side of a conflict.
/// </summary>
public const git_index_stage_t GIT_INDEX_STAGE_THEIRS = git_index_stage_t.GIT_INDEX_STAGE_THEIRS;
/// <summary>
/// Time structure used in a git index entry
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public partial struct git_index_time
{
public int seconds;
/// <summary>
/// nsec should not be stored as time_t compatible
/// </summary>
public uint nanoseconds;
}
/// <summary>
/// In-memory representation of a file entry in the index.
/// </summary>
/// <remarks>
/// This is a public structure that represents a file entry in the index.
/// The meaning of the fields corresponds to core Git's documentation (in
/// "Documentation/technical/index-format.txt").The `flags` field consists of a number of bit fields which can be
/// accessed via the first set of `GIT_INDEX_ENTRY_...` bitmasks below.
/// These flags are all read from and persisted to disk.The `flags_extended` field also has a number of bit fields which can be
/// accessed via the later `GIT_INDEX_ENTRY_...` bitmasks below. Some of
/// these flags are read from and written to disk, but some are set aside
/// for in-memory only reference.Note that the time and size fields are truncated to 32 bits. This
/// is enough to detect changes, which is enough for the index to
/// function as a cache, but it should not be taken as an authoritative
/// source for that data.
/// </remarks>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public partial struct git_index_entry
{
public git_index_time ctime;
public git_index_time mtime;
public uint dev;
public uint ino;
public uint mode;
public uint uid;
public uint gid;
public uint file_size;
public git_oid id;
public ushort flags;
public ushort flags_extended;
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))]
public string path;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int git_index_matched_path_cb([MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerRelaxedNoCleanup))] string path, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerRelaxedNoCleanup))] string matched_pathspec, IntPtr payload);
/// <summary>
/// Create a new bare Git index object as a memory representation
/// of the Git index file in 'index_path', without a repository
/// to back it.
/// </summary>
/// <param name="out">the pointer for the new index</param>
/// <param name="index_path">the path to the index file in disk</param>
/// <returns>0 or an error code</returns>
/// <remarks>
/// Since there is no ODB or working directory behind this index,
/// any Index methods which rely on these (e.g. index_add_bypath)
/// will fail with the GIT_ERROR error code.If you need to access the index of an actual repository,
/// use the `git_repository_index` wrapper.The index must be freed once it's no longer in use.
/// </remarks>
public static git_result git_index_open(out git_index @out, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string index_path)
{
var __result__ = git_index_open__(out @out, index_path).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_open", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_open__(out git_index @out, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string index_path);
/// <summary>
/// Create an in-memory index object.
/// </summary>
/// <param name="out">the pointer for the new index</param>
/// <returns>0 or an error code</returns>
/// <remarks>
/// This index object cannot be read/written to the filesystem,
/// but may be used to perform in-memory index operations.The index must be freed once it's no longer in use.
/// </remarks>
public static git_result git_index_new(out git_index @out)
{
var __result__ = git_index_new__(out @out).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_new", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_new__(out git_index @out);
/// <summary>
/// Free an existing index object.
/// </summary>
/// <param name="index">an existing index object</param>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern void git_index_free(git_index index);
/// <summary>
/// Get the repository this index relates to
/// </summary>
/// <param name="index">The index</param>
/// <returns>A pointer to the repository</returns>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern git_repository git_index_owner(git_index index);
/// <summary>
/// Read index capabilities flags.
/// </summary>
/// <param name="index">An existing index object</param>
/// <returns>A combination of GIT_INDEX_CAPABILITY values</returns>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int git_index_caps(git_index index);
/// <summary>
/// Set index capabilities flags.
/// </summary>
/// <param name="index">An existing index object</param>
/// <param name="caps">A combination of GIT_INDEX_CAPABILITY values</param>
/// <returns>0 on success, -1 on failure</returns>
/// <remarks>
/// If you pass `GIT_INDEX_CAPABILITY_FROM_OWNER` for the caps, then
/// capabilities will be read from the config of the owner object,
/// looking at `core.ignorecase`, `core.filemode`, `core.symlinks`.
/// </remarks>
public static git_result git_index_set_caps(git_index index, int caps)
{
var __result__ = git_index_set_caps__(index, caps).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_set_caps", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_set_caps__(git_index index, int caps);
/// <summary>
/// Get index on-disk version.
/// </summary>
/// <param name="index">An existing index object</param>
/// <returns>the index version</returns>
/// <remarks>
/// Valid return values are 2, 3, or 4. If 3 is returned, an index
/// with version 2 may be written instead, if the extension data in
/// version 3 is not necessary.
/// </remarks>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern uint git_index_version(git_index index);
/// <summary>
/// Set index on-disk version.
/// </summary>
/// <param name="index">An existing index object</param>
/// <param name="version">The new version number</param>
/// <returns>0 on success, -1 on failure</returns>
/// <remarks>
/// Valid values are 2, 3, or 4. If 2 is given, git_index_write may
/// write an index with version 3 instead, if necessary to accurately
/// represent the index.
/// </remarks>
public static git_result git_index_set_version(git_index index, uint version)
{
var __result__ = git_index_set_version__(index, version).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_set_version", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_set_version__(git_index index, uint version);
/// <summary>
/// Update the contents of an existing index object in memory by reading
/// from the hard disk.
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="force">if true, always reload, vs. only read if file has changed</param>
/// <returns>0 or an error code</returns>
/// <remarks>
/// If `force` is true, this performs a "hard" read that discards in-memory
/// changes and always reloads the on-disk index data. If there is no
/// on-disk version, the index will be cleared.If `force` is false, this does a "soft" read that reloads the index
/// data from disk only if it has changed since the last time it was
/// loaded. Purely in-memory index data will be untouched. Be aware: if
/// there are changes on disk, unwritten in-memory changes are discarded.
/// </remarks>
public static git_result git_index_read(git_index index, int force)
{
var __result__ = git_index_read__(index, force).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_read", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_read__(git_index index, int force);
/// <summary>
/// Write an existing index object from memory back to disk
/// using an atomic file lock.
/// </summary>
/// <param name="index">an existing index object</param>
/// <returns>0 or an error code</returns>
public static git_result git_index_write(git_index index)
{
var __result__ = git_index_write__(index).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_write", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_write__(git_index index);
/// <summary>
/// Get the full path to the index file on disk.
/// </summary>
/// <param name="index">an existing index object</param>
/// <returns>path to index file or NULL for in-memory index</returns>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
[return:MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerRelaxedNoCleanup))]
public static extern string git_index_path(git_index index);
/// <summary>
/// Get the checksum of the index
/// </summary>
/// <param name="index">an existing index object</param>
/// <returns>a pointer to the checksum of the index</returns>
/// <remarks>
/// This checksum is the SHA-1 hash over the index file (except the
/// last 20 bytes which are the checksum itself). In cases where the
/// index does not exist on-disk, it will be zeroed out.
/// </remarks>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern ref readonly git_oid git_index_checksum(git_index index);
/// <summary>
/// Read a tree into the index file with stats
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="tree">tree to read</param>
/// <returns>0 or an error code</returns>
/// <remarks>
/// The current index contents will be replaced by the specified tree.
/// </remarks>
public static git_result git_index_read_tree(git_index index, git_tree tree)
{
var __result__ = git_index_read_tree__(index, tree).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_read_tree", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_read_tree__(git_index index, git_tree tree);
/// <summary>
/// Write the index as a tree
/// </summary>
/// <param name="out">Pointer where to store the OID of the written tree</param>
/// <param name="index">Index to write</param>
/// <returns>0 on success, GIT_EUNMERGED when the index is not clean
/// or an error code</returns>
/// <remarks>
/// This method will scan the index and write a representation
/// of its current state back to disk; it recursively creates
/// tree objects for each of the subtrees stored in the index,
/// but only returns the OID of the root tree. This is the OID
/// that can be used e.g. to create a commit.The index instance cannot be bare, and needs to be associated
/// to an existing repository.The index must not contain any file in conflict.
/// </remarks>
public static git_result git_index_write_tree(out git_oid @out, git_index index)
{
var __result__ = git_index_write_tree__(out @out, index).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_write_tree", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_write_tree__(out git_oid @out, git_index index);
/// <summary>
/// Write the index as a tree to the given repository
/// </summary>
/// <param name="out">Pointer where to store OID of the the written tree</param>
/// <param name="index">Index to write</param>
/// <param name="repo">Repository where to write the tree</param>
/// <returns>0 on success, GIT_EUNMERGED when the index is not clean
/// or an error code</returns>
/// <remarks>
/// This method will do the same as `git_index_write_tree`, but
/// letting the user choose the repository where the tree will
/// be written.The index must not contain any file in conflict.
/// </remarks>
public static git_result git_index_write_tree_to(out git_oid @out, git_index index, git_repository repo)
{
var __result__ = git_index_write_tree_to__(out @out, index, repo).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_write_tree_to", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_write_tree_to__(out git_oid @out, git_index index, git_repository repo);
/// <summary>
/// Get the count of entries currently in the index
/// </summary>
/// <param name="index">an existing index object</param>
/// <returns>integer of count of current entries</returns>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern size_t git_index_entrycount(git_index index);
/// <summary>
/// Clear the contents (all the entries) of an index object.
/// </summary>
/// <param name="index">an existing index object</param>
/// <returns>0 on success, error code
/// <
/// 0 on failure</returns>
/// <remarks>
/// This clears the index object in memory; changes must be explicitly
/// written to disk for them to take effect persistently.
/// </remarks>
public static git_result git_index_clear(git_index index)
{
var __result__ = git_index_clear__(index).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_clear", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_clear__(git_index index);
/// <summary>
/// Get a pointer to one of the entries in the index
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="n">the position of the entry</param>
/// <returns>a pointer to the entry; NULL if out of bounds</returns>
/// <remarks>
/// The entry is not modifiable and should not be freed. Because the
/// `git_index_entry` struct is a publicly defined struct, you should
/// be able to make your own permanent copy of the data if necessary.
/// </remarks>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern ref readonly git_index_entry git_index_get_byindex(git_index index, size_t n);
/// <summary>
/// Get a pointer to one of the entries in the index
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="path">path to search</param>
/// <param name="stage">stage to search</param>
/// <returns>a pointer to the entry; NULL if it was not found</returns>
/// <remarks>
/// The entry is not modifiable and should not be freed. Because the
/// `git_index_entry` struct is a publicly defined struct, you should
/// be able to make your own permanent copy of the data if necessary.
/// </remarks>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern ref readonly git_index_entry git_index_get_bypath(git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string path, int stage);
/// <summary>
/// Remove an entry from the index
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="path">path to search</param>
/// <param name="stage">stage to search</param>
/// <returns>0 or an error code</returns>
public static git_result git_index_remove(git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string path, int stage)
{
var __result__ = git_index_remove__(index, path, stage).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_remove", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_remove__(git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string path, int stage);
/// <summary>
/// Remove all entries from the index under a given directory
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="dir">container directory path</param>
/// <param name="stage">stage to search</param>
/// <returns>0 or an error code</returns>
public static git_result git_index_remove_directory(git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string dir, int stage)
{
var __result__ = git_index_remove_directory__(index, dir, stage).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_remove_directory", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_remove_directory__(git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string dir, int stage);
/// <summary>
/// Add or update an index entry from an in-memory struct
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="source_entry">new entry object</param>
/// <returns>0 or an error code</returns>
/// <remarks>
/// If a previous index entry exists that has the same path and stage
/// as the given 'source_entry', it will be replaced. Otherwise, the
/// 'source_entry' will be added.A full copy (including the 'path' string) of the given
/// 'source_entry' will be inserted on the index.
/// </remarks>
public static git_result git_index_add(git_index index, in git_index_entry source_entry)
{
var __result__ = git_index_add__(index, source_entry).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_add", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_add__(git_index index, in git_index_entry source_entry);
/// <summary>
/// Return the stage number from a git index entry
/// </summary>
/// <param name="entry">The entry</param>
/// <returns>the stage number</returns>
/// <remarks>
/// This entry is calculated from the entry's flag attribute like this:(entry->flags
/// &
/// GIT_INDEX_ENTRY_STAGEMASK) >> GIT_INDEX_ENTRY_STAGESHIFT
/// </remarks>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int git_index_entry_stage(in git_index_entry entry);
/// <summary>
/// Return whether the given index entry is a conflict (has a high stage
/// entry). This is simply shorthand for `git_index_entry_stage > 0`.
/// </summary>
/// <param name="entry">The entry</param>
/// <returns>1 if the entry is a conflict entry, 0 otherwise</returns>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int git_index_entry_is_conflict(in git_index_entry entry);
/// <summary>
/// Create an iterator that will return every entry contained in the
/// index at the time of creation. Entries are returned in order,
/// sorted by path. This iterator is backed by a snapshot that allows
/// callers to modify the index while iterating without affecting the
/// iterator.
/// </summary>
/// <param name="iterator_out">The newly created iterator</param>
/// <param name="index">The index to iterate</param>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int git_index_iterator_new(out git_index_iterator iterator_out, git_index index);
/// <summary>
/// Return the next index entry in-order from the iterator.
/// </summary>
/// <param name="out">Pointer to store the index entry in</param>
/// <param name="iterator">The iterator</param>
/// <returns>0, GIT_ITEROVER on iteration completion or an error code</returns>
public static git_result git_index_iterator_next(out IntPtr @out, git_index_iterator iterator)
{
var __result__ = git_index_iterator_next__(out @out, iterator).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_iterator_next", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_iterator_next__(out IntPtr @out, git_index_iterator iterator);
/// <summary>
/// Free the index iterator
/// </summary>
/// <param name="iterator">The iterator to free</param>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern void git_index_iterator_free(git_index_iterator iterator);
/// <summary>
/// Add or update an index entry from a file on disk
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="path">filename to add</param>
/// <returns>0 or an error code</returns>
/// <remarks>
/// The file `path` must be relative to the repository's
/// working folder and must be readable.This method will fail in bare index instances.This forces the file to be added to the index, not looking
/// at gitignore rules. Those rules can be evaluated through
/// the git_status APIs (in status.h) before calling this.If this file currently is the result of a merge conflict, this
/// file will no longer be marked as conflicting. The data about
/// the conflict will be moved to the "resolve undo" (REUC) section.
/// </remarks>
public static git_result git_index_add_bypath(git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string path)
{
var __result__ = git_index_add_bypath__(index, path).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_add_bypath", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_add_bypath__(git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string path);
/// <summary>
/// Add or update an index entry from a buffer in memory
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="entry">filename to add</param>
/// <param name="buffer">data to be written into the blob</param>
/// <param name="len">length of the data</param>
/// <returns>0 or an error code</returns>
/// <remarks>
/// This method will create a blob in the repository that owns the
/// index and then add the index entry to the index. The `path` of the
/// entry represents the position of the blob relative to the
/// repository's root folder.If a previous index entry exists that has the same path as the
/// given 'entry', it will be replaced. Otherwise, the 'entry' will be
/// added. The `id` and the `file_size` of the 'entry' are updated with the
/// real value of the blob.This forces the file to be added to the index, not looking
/// at gitignore rules. Those rules can be evaluated through
/// the git_status APIs (in status.h) before calling this.If this file currently is the result of a merge conflict, this
/// file will no longer be marked as conflicting. The data about
/// the conflict will be moved to the "resolve undo" (REUC) section.
/// </remarks>
public static git_result git_index_add_frombuffer(git_index index, in git_index_entry entry, IntPtr buffer, size_t len)
{
var __result__ = git_index_add_frombuffer__(index, entry, buffer, len).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_add_frombuffer", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_add_frombuffer__(git_index index, in git_index_entry entry, IntPtr buffer, size_t len);
/// <summary>
/// Remove an index entry corresponding to a file on disk
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="path">filename to remove</param>
/// <returns>0 or an error code</returns>
/// <remarks>
/// The file `path` must be relative to the repository's
/// working folder. It may exist.If this file currently is the result of a merge conflict, this
/// file will no longer be marked as conflicting. The data about
/// the conflict will be moved to the "resolve undo" (REUC) section.
/// </remarks>
public static git_result git_index_remove_bypath(git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string path)
{
var __result__ = git_index_remove_bypath__(index, path).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_remove_bypath", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_remove_bypath__(git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string path);
/// <summary>
/// Add or update index entries matching files in the working directory.
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="pathspec">array of path patterns</param>
/// <param name="flags">combination of git_index_add_option_t flags</param>
/// <param name="callback">notification callback for each added/updated path (also
/// gets index of matching pathspec entry); can be NULL;
/// return 0 to add, >0 to skip,
/// <
/// 0 to abort scan.</param>
/// <param name="payload">payload passed through to callback function</param>
/// <returns>0 on success, negative callback return value, or error code</returns>
/// <remarks>
/// This method will fail in bare index instances.The `pathspec` is a list of file names or shell glob patterns that will
/// be matched against files in the repository's working directory. Each
/// file that matches will be added to the index (either updating an
/// existing entry or adding a new entry). You can disable glob expansion
/// and force exact matching with the `GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH`
/// flag.Files that are ignored will be skipped (unlike `git_index_add_bypath`).
/// If a file is already tracked in the index, then it *will* be updated
/// even if it is ignored. Pass the `GIT_INDEX_ADD_FORCE` flag to skip
/// the checking of ignore rules.To emulate `git add -A` and generate an error if the pathspec contains
/// the exact path of an ignored file (when not using FORCE), add the
/// `GIT_INDEX_ADD_CHECK_PATHSPEC` flag. This checks that each entry
/// in the `pathspec` that is an exact match to a filename on disk is
/// either not ignored or already in the index. If this check fails, the
/// function will return GIT_EINVALIDSPEC.To emulate `git add -A` with the "dry-run" option, just use a callback
/// function that always returns a positive value. See below for details.If any files are currently the result of a merge conflict, those files
/// will no longer be marked as conflicting. The data about the conflicts
/// will be moved to the "resolve undo" (REUC) section.If you provide a callback function, it will be invoked on each matching
/// item in the working directory immediately *before* it is added to /
/// updated in the index. Returning zero will add the item to the index,
/// greater than zero will skip the item, and less than zero will abort the
/// scan and return that value to the caller.
/// </remarks>
public static git_result git_index_add_all(git_index index, string[] pathspec, uint flags, git_index_matched_path_cb callback, IntPtr payload)
{
var pathspec__ = git_strarray.Allocate(pathspec);
var __result__ = git_index_add_all__(index, in pathspec__, flags, callback, payload);
pathspec__.Free();
__result__.Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_add_all", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_add_all__(git_index index, in git_strarray pathspec, uint flags, git_index_matched_path_cb callback, IntPtr payload);
/// <summary>
/// Remove all matching index entries.
/// </summary>
/// <param name="index">An existing index object</param>
/// <param name="pathspec">array of path patterns</param>
/// <param name="callback">notification callback for each removed path (also
/// gets index of matching pathspec entry); can be NULL;
/// return 0 to add, >0 to skip,
/// <
/// 0 to abort scan.</param>
/// <param name="payload">payload passed through to callback function</param>
/// <returns>0 on success, negative callback return value, or error code</returns>
/// <remarks>
/// If you provide a callback function, it will be invoked on each matching
/// item in the index immediately *before* it is removed. Return 0 to
/// remove the item, > 0 to skip the item, and
/// <
/// 0 to abort the scan.
/// </remarks>
public static git_result git_index_remove_all(git_index index, string[] pathspec, git_index_matched_path_cb callback, IntPtr payload)
{
var pathspec__ = git_strarray.Allocate(pathspec);
var __result__ = git_index_remove_all__(index, in pathspec__, callback, payload);
pathspec__.Free();
__result__.Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_remove_all", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_remove_all__(git_index index, in git_strarray pathspec, git_index_matched_path_cb callback, IntPtr payload);
/// <summary>
/// Update all index entries to match the working directory
/// </summary>
/// <param name="index">An existing index object</param>
/// <param name="pathspec">array of path patterns</param>
/// <param name="callback">notification callback for each updated path (also
/// gets index of matching pathspec entry); can be NULL;
/// return 0 to add, >0 to skip,
/// <
/// 0 to abort scan.</param>
/// <param name="payload">payload passed through to callback function</param>
/// <returns>0 on success, negative callback return value, or error code</returns>
/// <remarks>
/// This method will fail in bare index instances.This scans the existing index entries and synchronizes them with the
/// working directory, deleting them if the corresponding working directory
/// file no longer exists otherwise updating the information (including
/// adding the latest version of file to the ODB if needed).If you provide a callback function, it will be invoked on each matching
/// item in the index immediately *before* it is updated (either refreshed
/// or removed depending on working directory state). Return 0 to proceed
/// with updating the item, > 0 to skip the item, and
/// <
/// 0 to abort the scan.
/// </remarks>
public static git_result git_index_update_all(git_index index, string[] pathspec, git_index_matched_path_cb callback, IntPtr payload)
{
var pathspec__ = git_strarray.Allocate(pathspec);
var __result__ = git_index_update_all__(index, in pathspec__, callback, payload);
pathspec__.Free();
__result__.Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_update_all", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_update_all__(git_index index, in git_strarray pathspec, git_index_matched_path_cb callback, IntPtr payload);
/// <summary>
/// Find the first position of any entries which point to given
/// path in the Git index.
/// </summary>
/// <param name="at_pos">the address to which the position of the index entry is written (optional)</param>
/// <param name="index">an existing index object</param>
/// <param name="path">path to search</param>
/// <returns>a zero-based position in the index if found; GIT_ENOTFOUND otherwise</returns>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int git_index_find(ref size_t at_pos, git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string path);
/// <summary>
/// Find the first position of any entries matching a prefix. To find the first position
/// of a path inside a given folder, suffix the prefix with a '/'.
/// </summary>
/// <param name="at_pos">the address to which the position of the index entry is written (optional)</param>
/// <param name="index">an existing index object</param>
/// <param name="prefix">the prefix to search for</param>
/// <returns>0 with valid value in at_pos; an error code otherwise</returns>
public static git_result git_index_find_prefix(ref size_t at_pos, git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string prefix)
{
var __result__ = git_index_find_prefix__(ref at_pos, index, prefix).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_find_prefix", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_find_prefix__(ref size_t at_pos, git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string prefix);
/// <summary>
/// Add or update index entries to represent a conflict. Any staged
/// entries that exist at the given paths will be removed.
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="ancestor_entry">the entry data for the ancestor of the conflict</param>
/// <param name="our_entry">the entry data for our side of the merge conflict</param>
/// <param name="their_entry">the entry data for their side of the merge conflict</param>
/// <returns>0 or an error code</returns>
/// <remarks>
/// The entries are the entries from the tree included in the merge. Any
/// entry may be null to indicate that that file was not present in the
/// trees during the merge. For example, ancestor_entry may be NULL to
/// indicate that a file was added in both branches and must be resolved.
/// </remarks>
public static git_result git_index_conflict_add(git_index index, in git_index_entry ancestor_entry, in git_index_entry our_entry, in git_index_entry their_entry)
{
var __result__ = git_index_conflict_add__(index, ancestor_entry, our_entry, their_entry).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_conflict_add", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_conflict_add__(git_index index, in git_index_entry ancestor_entry, in git_index_entry our_entry, in git_index_entry their_entry);
/// <summary>
/// Get the index entries that represent a conflict of a single file.
/// </summary>
/// <param name="ancestor_out">Pointer to store the ancestor entry</param>
/// <param name="our_out">Pointer to store the our entry</param>
/// <param name="their_out">Pointer to store the their entry</param>
/// <param name="index">an existing index object</param>
/// <param name="path">path to search</param>
/// <returns>0 or an error code</returns>
/// <remarks>
/// The entries are not modifiable and should not be freed. Because the
/// `git_index_entry` struct is a publicly defined struct, you should
/// be able to make your own permanent copy of the data if necessary.
/// </remarks>
public static git_result git_index_conflict_get(out IntPtr ancestor_out, out IntPtr our_out, out IntPtr their_out, git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string path)
{
var __result__ = git_index_conflict_get__(out ancestor_out, out our_out, out their_out, index, path).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_conflict_get", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_conflict_get__(out IntPtr ancestor_out, out IntPtr our_out, out IntPtr their_out, git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string path);
/// <summary>
/// Removes the index entries that represent a conflict of a single file.
/// </summary>
/// <param name="index">an existing index object</param>
/// <param name="path">path to remove conflicts for</param>
/// <returns>0 or an error code</returns>
public static git_result git_index_conflict_remove(git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string path)
{
var __result__ = git_index_conflict_remove__(index, path).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_conflict_remove", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_conflict_remove__(git_index index, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UTF8MarshallerStrict))] string path);
/// <summary>
/// Remove all conflicts in the index (entries with a stage greater than 0).
/// </summary>
/// <param name="index">an existing index object</param>
/// <returns>0 or an error code</returns>
public static git_result git_index_conflict_cleanup(git_index index)
{
var __result__ = git_index_conflict_cleanup__(index).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_conflict_cleanup", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_conflict_cleanup__(git_index index);
/// <summary>
/// Determine if the index contains entries representing file conflicts.
/// </summary>
/// <returns>1 if at least one conflict is found, 0 otherwise.</returns>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int git_index_has_conflicts(git_index index);
/// <summary>
/// Create an iterator for the conflicts in the index.
/// </summary>
/// <param name="iterator_out">The newly created conflict iterator</param>
/// <param name="index">The index to scan</param>
/// <returns>0 or an error code</returns>
/// <remarks>
/// The index must not be modified while iterating; the results are undefined.
/// </remarks>
public static git_result git_index_conflict_iterator_new(out git_index_conflict_iterator iterator_out, git_index index)
{
var __result__ = git_index_conflict_iterator_new__(out iterator_out, index).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_conflict_iterator_new", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_conflict_iterator_new__(out git_index_conflict_iterator iterator_out, git_index index);
/// <summary>
/// Returns the current conflict (ancestor, ours and theirs entry) and
/// advance the iterator internally to the next value.
/// </summary>
/// <param name="ancestor_out">Pointer to store the ancestor side of the conflict</param>
/// <param name="our_out">Pointer to store our side of the conflict</param>
/// <param name="their_out">Pointer to store their side of the conflict</param>
/// <returns>0 (no error), GIT_ITEROVER (iteration is done) or an error code
/// (negative value)</returns>
public static git_result git_index_conflict_next(out IntPtr ancestor_out, out IntPtr our_out, out IntPtr their_out, git_index_conflict_iterator iterator)
{
var __result__ = git_index_conflict_next__(out ancestor_out, out our_out, out their_out, iterator).Check();
return __result__;
}
[DllImport(GitLibName, EntryPoint = "git_index_conflict_next", CallingConvention = CallingConvention.Cdecl)]
private static extern git_result git_index_conflict_next__(out IntPtr ancestor_out, out IntPtr our_out, out IntPtr their_out, git_index_conflict_iterator iterator);
/// <summary>
/// Frees a `git_index_conflict_iterator`.
/// </summary>
/// <param name="iterator">pointer to the iterator</param>
[DllImport(GitLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern void git_index_conflict_iterator_free(git_index_conflict_iterator iterator);
}
}
| 53.979654 | 308 | 0.642004 | [
"BSD-2-Clause"
] | xoofx/GitLib.NET | src/GitLib/generated/index.generated.cs | 53,062 | 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("TP01Configuration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("TP01Configuration")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("789aa599-8088-4b62-908a-4f8007488ee6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.513514 | 84 | 0.750175 | [
"MIT"
] | SQLYogi/.Net-Framework | TP01Configuration/Properties/AssemblyInfo.cs | 1,428 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace SportsAppMS
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 30.568966 | 143 | 0.609701 | [
"MIT"
] | ivanvenkov/SportsApp | SportsAppMS/SportsAppMS/Startup.cs | 1,773 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// ParkingGoodsDetail Data Structure.
/// </summary>
public class ParkingGoodsDetail : AlipayObject
{
/// <summary>
/// 1^2^3(表示周一、周二、周三),此时间与商品履约开始、结束时间取交集,如2019-01-01到2019-03-01期间的周一、周二、周三
/// </summary>
[JsonPropertyName("arg_date_week")]
public string ArgDateWeek { get; set; }
/// <summary>
/// "商品有效时间结束时间,此时间属于日范围内结束时间,如果 结束时间小于开始时间,则默认跨天"
/// </summary>
[JsonPropertyName("arg_end_time")]
public string ArgEndTime { get; set; }
/// <summary>
/// 商品有效时间开始时间,此时间属于日范围内开始时间
/// </summary>
[JsonPropertyName("arg_start_time")]
public string ArgStartTime { get; set; }
/// <summary>
/// 业务参数 json
/// </summary>
[JsonPropertyName("biz_data")]
public string BizData { get; set; }
/// <summary>
/// 商品可购买结束日期,截止此时间次日0点(针对日租),会按照日期跨度,按照日维度创建多个商品
/// </summary>
[JsonPropertyName("buy_end_date")]
public string BuyEndDate { get; set; }
/// <summary>
/// 商品可购买开始日期(针对日租)
/// </summary>
[JsonPropertyName("buy_start_date")]
public string BuyStartDate { get; set; }
/// <summary>
/// 20.00
/// </summary>
[JsonPropertyName("cost_price")]
public string CostPrice { get; set; }
/// <summary>
/// 总次数(本期暂不支持)
/// </summary>
[JsonPropertyName("count_num")]
public string CountNum { get; set; }
/// <summary>
/// 现价,保留小数点后两位
/// </summary>
[JsonPropertyName("current_price")]
public string CurrentPrice { get; set; }
/// <summary>
/// 日次数(本期暂不支持)
/// </summary>
[JsonPropertyName("date_num")]
public string DateNum { get; set; }
/// <summary>
/// 商品描述
/// </summary>
[JsonPropertyName("desc")]
public string Desc { get; set; }
/// <summary>
/// 销售结束时间,格式"YYYY-MM-DD HH:mm:ss",24小时制
/// </summary>
[JsonPropertyName("end_sell_time")]
public string EndSellTime { get; set; }
/// <summary>
/// 支付宝商品ID列表
/// </summary>
[JsonPropertyName("goods_id")]
public string GoodsId { get; set; }
/// <summary>
/// 库存
/// </summary>
[JsonPropertyName("goods_num")]
public string GoodsNum { get; set; }
/// <summary>
/// "租期类型,01 时租(本期暂不支持),02 日租,03 周租(本期暂 不支持),04月租(本期暂不支持)"
/// </summary>
[JsonPropertyName("goods_rent_type")]
public string GoodsRentType { get; set; }
/// <summary>
/// NOT_EFFECT:下架;EFFECT:上架;PAUSED:已暂停;
/// </summary>
[JsonPropertyName("goods_status")]
public string GoodsStatus { get; set; }
/// <summary>
/// 商品类型01-按时,02-按次(本期暂不支持)
/// </summary>
[JsonPropertyName("goods_type")]
public string GoodsType { get; set; }
/// <summary>
/// 商品关键字
/// </summary>
[JsonPropertyName("keywords")]
public string Keywords { get; set; }
/// <summary>
/// 商品名称
/// </summary>
[JsonPropertyName("name")]
public string Name { get; set; }
/// <summary>
/// isv内部产生商品ID
/// </summary>
[JsonPropertyName("out_id")]
public string OutId { get; set; }
/// <summary>
/// 支付宝返回停车场ID
/// </summary>
[JsonPropertyName("parking_id")]
public string ParkingId { get; set; }
/// <summary>
/// 上架时间,格式"YYY-MM-DD HH:mm:ss",24小时制
/// </summary>
[JsonPropertyName("put_time")]
public string PutTime { get; set; }
/// <summary>
/// 销售开始时间,格式"YYYY-MM-DD HH:mm:ss",24小时制
/// </summary>
[JsonPropertyName("start_sell_time")]
public string StartSellTime { get; set; }
}
}
| 27.516779 | 82 | 0.517073 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Domain/ParkingGoodsDetail.cs | 4,778 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Security.Authentication;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Diagnostics;
using Azure.Messaging.EventHubs.Authorization;
using Azure.Messaging.EventHubs.Consumer;
using Azure.Messaging.EventHubs.Core;
using Azure.Messaging.EventHubs.Diagnostics;
using Azure.Messaging.EventHubs.Producer;
using Microsoft.Azure.Amqp;
namespace Azure.Messaging.EventHubs.Amqp
{
/// <summary>
/// A transport client abstraction responsible for brokering operations for AMQP-based connections.
/// It is intended that the public <see cref="EventHubConnection" /> make use of an instance via containment
/// and delegate operations to it.
/// </summary>
///
/// <seealso cref="Azure.Messaging.EventHubs.Core.TransportClient" />
///
internal class AmqpClient : TransportClient
{
/// <summary>
/// The buffer to apply when considering refreshing; credentials that expire less than this duration will be refreshed.
/// </summary>
///
private static TimeSpan CredentialRefreshBuffer { get; } = TimeSpan.FromMinutes(5);
/// <summary>Indicates whether or not this instance has been closed.</summary>
private volatile bool _closed;
/// <summary>The currently active token to use for authorization with the Event Hubs service.</summary>
private AccessToken _accessToken;
/// <summary>
/// Indicates whether or not this client has been closed.
/// </summary>
///
/// <value>
/// <c>true</c> if the client is closed; otherwise, <c>false</c>.
/// </value>
///
public override bool IsClosed => _closed;
/// <summary>
/// The endpoint for the Event Hubs service to which the client is associated.
/// </summary>
///
public override Uri ServiceEndpoint { get; }
/// <summary>
/// The name of the Event Hub to which the client is bound.
/// </summary>
///
private string EventHubName { get; }
/// <summary>
/// Gets the credential to use for authorization with the Event Hubs service.
/// </summary>
///
private EventHubTokenCredential Credential { get; }
/// <summary>
/// The converter to use for translating between AMQP messages and client library
/// types.
/// </summary>
///
private AmqpMessageConverter MessageConverter { get; }
/// <summary>
/// The AMQP connection scope responsible for managing transport constructs for this instance.
/// </summary>
///
private AmqpConnectionScope ConnectionScope { get; }
/// <summary>
/// The AMQP link intended for use with management operations.
/// </summary>
///
private FaultTolerantAmqpObject<RequestResponseAmqpLink> ManagementLink { get; }
/// <summary>
/// Initializes a new instance of the <see cref="AmqpClient"/> class.
/// </summary>
///
/// <param name="host">The fully qualified host name for the Event Hubs namespace. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub to connect the client to.</param>
/// <param name="credential">The Azure managed identity credential to use for authorization. Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
/// <param name="clientOptions">A set of options to apply when configuring the client.</param>
///
/// <remarks>
/// As an internal type, this class performs only basic sanity checks against its arguments. It
/// is assumed that callers are trusted and have performed deep validation.
///
/// Any parameters passed are assumed to be owned by this instance and safe to mutate or dispose;
/// creation of clones or otherwise protecting the parameters is assumed to be the purview of the
/// caller.
/// </remarks>
///
public AmqpClient(string host,
string eventHubName,
EventHubTokenCredential credential,
EventHubConnectionOptions clientOptions) : this(host, eventHubName, credential, clientOptions, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AmqpClient"/> class.
/// </summary>
///
/// <param name="host">The fully qualified host name for the Event Hubs namespace. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub to connect the client to.</param>
/// <param name="credential">The Azure managed identity credential to use for authorization. Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
/// <param name="clientOptions">A set of options to apply when configuring the client.</param>
/// <param name="connectionScope">The optional scope to use for AMQP connection management. If <c>null</c>, a new scope will be created.</param>
/// <param name="messageConverter">The optional converter to use for transforming AMQP message-related types. If <c>null</c>, a new converter will be created.</param>
///
/// <remarks>
/// As an internal type, this class performs only basic sanity checks against its arguments. It
/// is assumed that callers are trusted and have performed deep validation.
///
/// Any parameters passed are assumed to be owned by this instance and safe to mutate or dispose;
/// creation of clones or otherwise protecting the parameters is assumed to be the purview of the
/// caller.
/// </remarks>
///
protected AmqpClient(string host,
string eventHubName,
EventHubTokenCredential credential,
EventHubConnectionOptions clientOptions,
AmqpConnectionScope connectionScope,
AmqpMessageConverter messageConverter)
{
Argument.AssertNotNullOrEmpty(host, nameof(host));
Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName));
Argument.AssertNotNull(credential, nameof(credential));
Argument.AssertNotNull(clientOptions, nameof(clientOptions));
try
{
EventHubsEventSource.Log.EventHubClientCreateStart(host, eventHubName);
ServiceEndpoint = new UriBuilder
{
Scheme = clientOptions.TransportType.GetUriScheme(),
Host = host
}.Uri;
EventHubName = eventHubName;
Credential = credential;
MessageConverter = messageConverter ?? new AmqpMessageConverter();
ConnectionScope = connectionScope ?? new AmqpConnectionScope(ServiceEndpoint, eventHubName, credential, clientOptions.TransportType, clientOptions.Proxy);
ManagementLink = new FaultTolerantAmqpObject<RequestResponseAmqpLink>(
timeout => ConnectionScope.OpenManagementLinkAsync(timeout, CancellationToken.None),
link =>
{
link.Session?.SafeClose();
link.SafeClose();
});
}
finally
{
EventHubsEventSource.Log.EventHubClientCreateComplete(host, eventHubName);
}
}
/// <summary>
/// Retrieves information about an Event Hub, including the number of partitions present
/// and their identifiers.
/// </summary>
///
/// <param name="retryPolicy">The retry policy to use as the basis for retrieving the information.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>The set of information for the Event Hub that this client is associated with.</returns>
///
public override async Task<EventHubProperties> GetPropertiesAsync(EventHubsRetryPolicy retryPolicy,
CancellationToken cancellationToken)
{
Argument.AssertNotClosed(_closed, nameof(AmqpClient));
Argument.AssertNotNull(retryPolicy, nameof(retryPolicy));
var failedAttemptCount = 0;
var retryDelay = default(TimeSpan?);
var stopWatch = ValueStopwatch.StartNew();
try
{
var tryTimeout = retryPolicy.CalculateTryTimeout(0);
while (!cancellationToken.IsCancellationRequested)
{
try
{
EventHubsEventSource.Log.GetPropertiesStart(EventHubName);
// Create the request message and the management link.
var token = await AcquireAccessTokenAsync(cancellationToken).ConfigureAwait(false);
using AmqpMessage request = MessageConverter.CreateEventHubPropertiesRequest(EventHubName, token);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
RequestResponseAmqpLink link = await ManagementLink.GetOrCreateAsync(UseMinimum(ConnectionScope.SessionTimeout, tryTimeout.CalculateRemaining(stopWatch.GetElapsedTime()))).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// Send the request and wait for the response.
using AmqpMessage response = await link.RequestAsync(request, tryTimeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// Process the response.
AmqpError.ThrowIfErrorResponse(response, EventHubName);
return MessageConverter.CreateEventHubPropertiesFromResponse(response);
}
catch (Exception ex)
{
Exception activeEx = ex.TranslateServiceException(EventHubName);
// Determine if there should be a retry for the next attempt; if so enforce the delay but do not quit the loop.
// Otherwise, mark the exception as active and break out of the loop.
++failedAttemptCount;
retryDelay = retryPolicy.CalculateRetryDelay(activeEx, failedAttemptCount);
if ((retryDelay.HasValue) && (!ConnectionScope.IsDisposed) && (!cancellationToken.IsCancellationRequested))
{
EventHubsEventSource.Log.GetPropertiesError(EventHubName, activeEx.Message);
await Task.Delay(retryDelay.Value, cancellationToken).ConfigureAwait(false);
tryTimeout = retryPolicy.CalculateTryTimeout(failedAttemptCount);
stopWatch = ValueStopwatch.StartNew();
}
else if (ex is AmqpException)
{
ExceptionDispatchInfo.Capture(activeEx).Throw();
}
else
{
throw;
}
}
}
// If no value has been returned nor exception thrown by this point,
// then cancellation has been requested.
throw new TaskCanceledException();
}
catch (Exception ex)
{
EventHubsEventSource.Log.GetPropertiesError(EventHubName, ex.Message);
throw;
}
finally
{
EventHubsEventSource.Log.GetPropertiesComplete(EventHubName);
}
}
/// <summary>
/// Retrieves information about a specific partition for an Event Hub, including elements that describe the available
/// events in the partition event stream.
/// </summary>
///
/// <param name="partitionId">The unique identifier of a partition associated with the Event Hub.</param>
/// <param name="retryPolicy">The retry policy to use as the basis for retrieving the information.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>The set of information for the requested partition under the Event Hub this client is associated with.</returns>
///
public override async Task<PartitionProperties> GetPartitionPropertiesAsync(string partitionId,
EventHubsRetryPolicy retryPolicy,
CancellationToken cancellationToken)
{
Argument.AssertNotClosed(_closed, nameof(AmqpClient));
Argument.AssertNotNullOrEmpty(partitionId, nameof(partitionId));
Argument.AssertNotNull(retryPolicy, nameof(retryPolicy));
var failedAttemptCount = 0;
var retryDelay = default(TimeSpan?);
var token = default(string);
var link = default(RequestResponseAmqpLink);
var stopWatch = ValueStopwatch.StartNew();
try
{
var tryTimeout = retryPolicy.CalculateTryTimeout(0);
while (!cancellationToken.IsCancellationRequested)
{
try
{
EventHubsEventSource.Log.GetPartitionPropertiesStart(EventHubName, partitionId);
// Create the request message and the management link.
token = await AcquireAccessTokenAsync(cancellationToken).ConfigureAwait(false);
using AmqpMessage request = MessageConverter.CreatePartitionPropertiesRequest(EventHubName, partitionId, token);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
link = await ManagementLink.GetOrCreateAsync(UseMinimum(ConnectionScope.SessionTimeout, tryTimeout.CalculateRemaining(stopWatch.GetElapsedTime()))).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// Send the request and wait for the response.
using AmqpMessage response = await link.RequestAsync(request, tryTimeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// Process the response.
AmqpError.ThrowIfErrorResponse(response, EventHubName);
return MessageConverter.CreatePartitionPropertiesFromResponse(response);
}
catch (Exception ex)
{
Exception activeEx = ex.TranslateServiceException(EventHubName);
// Determine if there should be a retry for the next attempt; if so enforce the delay but do not quit the loop.
// Otherwise, mark the exception as active and break out of the loop.
++failedAttemptCount;
retryDelay = retryPolicy.CalculateRetryDelay(activeEx, failedAttemptCount);
if ((retryDelay.HasValue) && (!ConnectionScope.IsDisposed) && (!cancellationToken.IsCancellationRequested))
{
EventHubsEventSource.Log.GetPartitionPropertiesError(EventHubName, partitionId, activeEx.Message);
await Task.Delay(retryDelay.Value, cancellationToken).ConfigureAwait(false);
tryTimeout = retryPolicy.CalculateTryTimeout(failedAttemptCount);
stopWatch = ValueStopwatch.StartNew();
}
else if (ex is AmqpException)
{
ExceptionDispatchInfo.Capture(activeEx).Throw();
}
else
{
throw;
}
}
}
// If no value has been returned nor exception thrown by this point,
// then cancellation has been requested.
throw new TaskCanceledException();
}
catch (Exception ex)
{
EventHubsEventSource.Log.GetPartitionPropertiesError(EventHubName, partitionId, ex.Message);
throw;
}
finally
{
EventHubsEventSource.Log.GetPartitionPropertiesComplete(EventHubName, partitionId);
}
}
/// <summary>
/// Creates a producer strongly aligned with the active protocol and transport,
/// responsible for publishing <see cref="EventData" /> to the Event Hub.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition to which the transport producer should be bound; if <c>null</c>, the producer is unbound.</param>
/// <param name="requestedFeatures">The flags specifying the set of special transport features that should be opted-into.</param>
/// <param name="partitionOptions">The set of options, if any, that should be considered when initializing the producer.</param>
/// <param name="retryPolicy">The policy which governs retry behavior and try timeouts.</param>
///
/// <returns>A <see cref="TransportProducer"/> configured in the requested manner.</returns>
///
public override TransportProducer CreateProducer(string partitionId,
TransportProducerFeatures requestedFeatures,
PartitionPublishingOptions partitionOptions,
EventHubsRetryPolicy retryPolicy)
{
Argument.AssertNotClosed(_closed, nameof(AmqpClient));
return new AmqpProducer
(
EventHubName,
partitionId,
ConnectionScope,
MessageConverter,
retryPolicy,
requestedFeatures,
partitionOptions
);
}
/// <summary>
/// Creates a consumer strongly aligned with the active protocol and transport, responsible
/// for reading <see cref="EventData" /> from a specific Event Hub partition, in the context
/// of a specific consumer group.
///
/// A consumer may be exclusive, which asserts ownership over the partition for the consumer
/// group to ensure that only one consumer from that group is reading the from the partition.
/// These exclusive consumers are sometimes referred to as "Epoch Consumers."
///
/// A consumer may also be non-exclusive, allowing multiple consumers from the same consumer
/// group to be actively reading events from the partition. These non-exclusive consumers are
/// sometimes referred to as "Non-epoch Consumers."
///
/// Designating a consumer as exclusive may be specified by setting the <paramref name="ownerLevel" />.
/// When <c>null</c>, consumers are created as non-exclusive.
/// </summary>
///
/// <param name="consumerGroup">The name of the consumer group this consumer is associated with. Events are read in the context of this group.</param>
/// <param name="partitionId">The identifier of the Event Hub partition from which events will be received.</param>
/// <param name="eventPosition">The position within the partition where the consumer should begin reading events.</param>
/// <param name="retryPolicy">The policy which governs retry behavior and try timeouts.</param>
/// <param name="trackLastEnqueuedEventProperties">Indicates whether information on the last enqueued event on the partition is sent as events are received.</param>
/// <param name="ownerLevel">The relative priority to associate with the link; for a non-exclusive link, this value should be <c>null</c>.</param>
/// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whether an operation was requested. If <c>null</c> a default will be used.</param>
/// <param name="prefetchSizeInBytes">The cache size of the prefetch queue. When set, the link makes a best effort to ensure prefetched messages fit into the specified size.</param>
///
/// <returns>A <see cref="TransportConsumer" /> configured in the requested manner.</returns>
///
public override TransportConsumer CreateConsumer(string consumerGroup,
string partitionId,
EventPosition eventPosition,
EventHubsRetryPolicy retryPolicy,
bool trackLastEnqueuedEventProperties,
long? ownerLevel,
uint? prefetchCount,
long? prefetchSizeInBytes)
{
Argument.AssertNotClosed(_closed, nameof(AmqpClient));
return new AmqpConsumer
(
EventHubName,
consumerGroup,
partitionId,
eventPosition,
trackLastEnqueuedEventProperties,
ownerLevel,
prefetchCount,
prefetchSizeInBytes,
ConnectionScope,
MessageConverter,
retryPolicy
);
}
/// <summary>
/// Closes the connection to the transport client instance.
/// </summary>
///
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
public override async Task CloseAsync(CancellationToken cancellationToken)
{
if (_closed)
{
return;
}
_closed = true;
var clientId = GetHashCode().ToString(CultureInfo.InvariantCulture);
var clientType = GetType().Name;
try
{
EventHubsEventSource.Log.ClientCloseStart(clientType, EventHubName, clientId);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
if (ManagementLink?.TryGetOpenedObject(out var _) == true)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
await ManagementLink.CloseAsync().ConfigureAwait(false);
}
ManagementLink?.Dispose();
ConnectionScope?.Dispose();
}
catch (Exception ex)
{
_closed = false;
EventHubsEventSource.Log.ClientCloseError(clientType, EventHubName, clientId, ex.Message);
throw;
}
finally
{
EventHubsEventSource.Log.ClientCloseComplete(clientType, EventHubName, clientId);
}
}
/// <summary>
/// Acquires an access token for authorization with the Event Hubs service.
/// </summary>
///
/// <returns>The token to use for service authorization.</returns>
///
private async Task<string> AcquireAccessTokenAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
AccessToken activeToken = _accessToken;
// If there was no current token, or it is within the buffer for expiration, request a new token.
// There is a benign race condition here, where there may be multiple requests in-flight for a new token. Since
// overlapping requests should be within a small window, allow the acquired token to replace the current one without
// attempting to coordinate or ensure that the most recent is kept.
if ((string.IsNullOrEmpty(activeToken.Token)) || (activeToken.ExpiresOn <= DateTimeOffset.UtcNow.Add(CredentialRefreshBuffer)))
{
activeToken = await Credential.GetTokenUsingDefaultScopeAsync(cancellationToken).ConfigureAwait(false);
if ((string.IsNullOrEmpty(activeToken.Token)))
{
throw new AuthenticationException(Resources.CouldNotAcquireAccessToken);
}
_accessToken = activeToken;
}
return activeToken.Token;
}
/// <summary>
/// Uses the minimum value of the two specified <see cref="TimeSpan" /> instances.
/// </summary>
///
/// <param name="firstOption">The first option to consider.</param>
/// <param name="secondOption">The second option to consider.</param>
///
/// <returns></returns>
///
private static TimeSpan UseMinimum(TimeSpan firstOption,
TimeSpan secondOption) => (firstOption < secondOption) ? firstOption : secondOption;
}
}
| 49.339416 | 232 | 0.58758 | [
"MIT"
] | Oleza1972/azure-sdk-for-net | sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpClient.cs | 27,040 | C# |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.data
{
/// <summary>
/// <para>This interface defines a data structure compatible with the data binding
/// controllers.
/// It defines a minimum of functionality which the controller need to work.</para>
/// </summary>
public interface IListData
{
#region Events
/// <summary>
/// <para>The change event which will be fired if there is a change in the data
/// structure.The data should contain a map with three key value pairs:
/// <item>start: The start index of the change.</item>
/// <item>end: The end index of the change.</item>
/// <item>type: The type of the change as a String. This can be ‘add’,
/// ‘remove’ or ‘order’</item>
/// <item>item: The item which has been changed.</item></para>
/// </summary>
event Action<qx.eventx.type.Data> OnChange;
/// <summary>
/// <para>The changeLength event will be fired every time the length of the
/// data structure changes.</para>
/// </summary>
event Action<qx.eventx.type.Event> OnChangeLength;
#endregion Events
#region Methods
/// <summary>
/// <para>Check if the given item is in the current data structure.</para>
/// </summary>
/// <param name="item">The item which is possibly in the data structure.</param>
/// <returns>true, if the array contains the given item.</returns>
bool Contains(object item);
/// <summary>
/// <para>Returns the item at the given index</para>
/// </summary>
/// <param name="index">The index requested of the data element.</param>
/// <returns>The element at the given index.</returns>
object GetItem(double index);
/// <summary>
/// <para>Returns the current length of the data structure.</para>
/// </summary>
/// <returns>The current length of the data structure.</returns>
double GetLength();
/// <summary>
/// <para>Sets the given item at the given position in the data structure. A
/// change event has to be fired.</para>
/// </summary>
/// <param name="index">The index of the data element.</param>
/// <param name="item">The new item to set.</param>
void SetItem(double index, object item);
/// <summary>
/// <para>Method to remove and add new element to the data. For every remove or
/// add a change event should be fired.</para>
/// </summary>
/// <param name="startIndex">The index where the splice should start</param>
/// <param name="amount">Defines number of element which will be removed at the given position.</param>
/// <param name="varargs">All following parameters will be added at the given position to the array.</param>
/// <returns>An array containing the removed elements.</returns>
qx.data.Array Splice(double startIndex, double amount, object varargs);
/// <summary>
/// <para>Returns the list data as native array.</para>
/// </summary>
/// <returns>The native array.</returns>
JsArray ToArray();
#endregion Methods
}
} | 36.117647 | 110 | 0.678827 | [
"MIT"
] | SharpKit/SharpKit-SDK | Defs/Qooxdoo/data/IListData.cs | 3,070 | C# |
using Chart.ModelSpace;
using System;
using System.Collections.Generic;
using System.Windows;
namespace Chart.SeriesSpace
{
public class BarSeries : BaseSeries, ISeries
{
/// <summary>
/// Render the shape
/// </summary>
/// <param name="position"></param>
/// <param name="series"></param>
/// <param name="items"></param>
/// <returns></returns>
public override void CreateItem(int position, string series, IList<IInputModel> items)
{
var currentModel = GetModel(position, series, items);
if (currentModel?.Point == null)
{
return;
}
var size = Math.Max(position - (position - 1.0), 0.0) / 4;
var shapeModel = new InputShapeModel
{
Size = 1,
Color = currentModel.Color ?? Color
};
var points = new Point[]
{
Composer.GetPixels(Panel, position - size, currentModel.Point),
Composer.GetPixels(Panel, position + size, currentModel.Point),
Composer.GetPixels(Panel, position + size, 0.0),
Composer.GetPixels(Panel, position - size, 0.0),
Composer.GetPixels(Panel, position - size, currentModel.Point)
};
Panel.CreateShape(points, shapeModel);
}
}
}
| 27.255319 | 91 | 0.591725 | [
"MIT"
] | Indemos/Terminal | Chart/Series/BarSeries.cs | 1,281 | C# |
using ChangeDresser.UI.DTO.SelectionWidgetDTOs;
using ChangeDresser.UI.Enums;
using Verse;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using RimWorld;
using System.Linq;
using static AlienRace.AlienPartGenerator;
using AlienRace;
using static AlienRace.ThingDef_AlienRace;
using System;
namespace ChangeDresser.UI.DTO
{
class AlienDresserDTO : DresserDTO
{
public AlienDresserDTO(Pawn pawn, CurrentEditorEnum currentEditorEnum, IEnumerable<CurrentEditorEnum> editors) : base(pawn, currentEditorEnum, editors)
{
base.EditorTypeSelectionDto.SetSelectedEditor(currentEditorEnum);
}
protected override void Initialize()
{
AlienComp ac = base.Pawn.TryGetComp<AlienComp>();
if (ac == null || !(base.Pawn.def is ThingDef_AlienRace ar))
{
Log.Error("[Change Dresser] Failed to get alien race for " + base.Pawn.Name.ToStringShort);
return;
}
AlienSettings raceSettings = ar.alienRace;
GeneralSettings generalSettings = raceSettings?.generalSettings;
if (this.EditorTypeSelectionDto.Contains(CurrentEditorEnum.ChangeDresserAlienSkinColor))
{
#if ALIEN_DEBUG
Log.Warning("AlienDresserDTO.initialize - start");
#endif
if (raceSettings != null)
{
Dictionary<Type, AlienRace.StyleSettings> styleSettings = raceSettings.styleSettings;
var c = ac.GetChannel("skin");
if (c != null)
{
base.AlienSkinColorPrimary = new SelectionColorWidgetDTO(c.first);
base.AlienSkinColorPrimary.SelectionChangeListener += this.PrimarySkinColorChange;
base.AlienSkinColorSecondary = new SelectionColorWidgetDTO(c.second);
base.AlienSkinColorPrimary.SelectionChangeListener += this.SecondarySkinColorChange;
}
if (styleSettings?.ContainsKey(typeof(HairDef)) == true)
{
base.HairColorSelectionDto = new HairColorSelectionDTO(this.Pawn.story.hairColor, IOUtil.LoadColorPresets(ColorPresetType.Hair));
base.HairColorSelectionDto.SelectionChangeListener += this.PrimaryHairColorChange;
ColorPresetsDTO hairColorPresets = IOUtil.LoadColorPresets(ColorPresetType.Hair);
if (GradientHairColorUtil.IsGradientHairAvailable)
{
if (!GradientHairColorUtil.GetGradientHair(this.Pawn, out bool enabled, out Color color))
{
enabled = false;
color = Color.white;
}
base.GradientHairColorSelectionDto = new HairColorSelectionDTO(color, hairColorPresets, enabled);
base.GradientHairColorSelectionDto.SelectionChangeListener += this.GradientHairColorChange;
}
}
}
}
if (this.EditorTypeSelectionDto.Contains(CurrentEditorEnum.ChangeDresserHair))
{
if (raceSettings != null)
{
Dictionary<Type, AlienRace.StyleSettings> styleSettings = raceSettings.styleSettings;
base.HasHair = styleSettings?.ContainsKey(typeof(HairDef)) == true;
#if ALIEN_DEBUG
Log.Warning("initialize - got hair settings: HasHair = " + base.HasHair);
#endif
if (base.HasHair)
{
List<string> hairTags = styleSettings[typeof(HairDef)].styleTags;
if (hairTags != null)
{
IEnumerable<HairDef> hairDefs = from hair in DefDatabase<HairDef>.AllDefs
where hair.styleTags.SharesElementWith(hairTags)
select hair;
#if ALIEN_DEBUG
System.Text.StringBuilder sb = new System.Text.StringBuilder("Hair Defs: ");
foreach (HairDef d in hairDefs)
{
sb.Append(d.defName);
sb.Append(", ");
}
Log.Warning("initialize - " + sb.ToString());
#endif
/*if (this.EditorTypeSelectionDto.Contains(CurrentEditorEnum.ChangeDresserHair))
{
if (hairSettings != null)
{
List<string> filter = (List<string>)hairSettings.GetType().GetField("hairTags")?.GetValue(hairSettings);
base.HairStyleSelectionDto = new HairStyleSelectionDTO(this.Pawn.story.hairDef, this.Pawn.gender, filter);
}
}*/
base.HairStyleSelectionDto = new HairStyleSelectionDTO(this.Pawn.story.hairDef, this.Pawn.gender, hairDefs);
}
else
{
base.HairStyleSelectionDto = new HairStyleSelectionDTO(this.Pawn.story.hairDef, this.Pawn.gender, Settings.ShareHairAcrossGenders);
}
}
else
{
#if ALIEN_DEBUG
Log.Warning("initialize - remove hair editors");
#endif
base.EditorTypeSelectionDto.Remove(CurrentEditorEnum.ChangeDresserHair);//, CurrentEditorEnum.ChangeDresserAlienHairColor);
#if ALIEN_DEBUG
Log.Warning("initialize - hair editors removed");
#endif
}
}
}
if (this.EditorTypeSelectionDto.Contains(CurrentEditorEnum.ChangeDresserBody))
{
var apg = generalSettings?.alienPartGenerator;
if (apg != null)
{
List<string> crownTypes = apg.aliencrowntypes;
if (ac.crownType != null && ac.crownType != "" &&
crownTypes?.Count > 1)
{
this.HeadTypeSelectionDto = new HeadTypeSelectionDTO(ac.crownType, this.Pawn.gender, crownTypes);
}
List<BodyTypeDef> alienbodytypes = apg.alienbodytypes;
if (alienbodytypes != null && alienbodytypes.Count > 1)
{
this.BodyTypeSelectionDto = new BodyTypeSelectionDTO(this.Pawn.story.bodyType, this.Pawn.gender, alienbodytypes);
}
else
{
Log.Warning("No alien body types found. Defaulting to human.");
this.BodyTypeSelectionDto = new BodyTypeSelectionDTO(this.Pawn.story.bodyType, this.Pawn.gender);
}
}
if (generalSettings.maleGenderProbability > 0f && generalSettings.maleGenderProbability < 1f)
{
base.GenderSelectionDto = new GenderSelectionDTO(base.Pawn.gender);
base.GenderSelectionDto.SelectionChangeListener += GenderChange;
}
#if ALIEN_DEBUG
Log.Warning("initialize - done");
#endif
}
}
private void PrimarySkinColorChange(object sender)
{
var c = base.Pawn.TryGetComp<AlienComp>()?.GetChannel("skin");
if (c != null)
c.first = base.AlienSkinColorPrimary.SelectedColor;
}
private void SecondarySkinColorChange(object sender)
{
var c = base.Pawn.TryGetComp<AlienComp>()?.GetChannel("skin");
if (c != null)
c.second = base.AlienSkinColorPrimary.SelectedColor;
}
private void PrimaryHairColorChange(object sender)
{
this.Pawn.story.hairColor = base.HairColorSelectionDto.SelectedColor;//base.AlienHairColorPrimary.SelectedColor;
}
private void GradientHairColorChange(object sender)
{
GradientHairColorUtil.SetGradientHair(base.Pawn, base.GradientHairColorSelectionDto.IsGradientEnabled, base.GradientHairColorSelectionDto.SelectedColor);
}
/*private void SecondaryHairColorChange(object sender)
{
SecondaryHairColorFieldInfo.SetValue(this.alienComp, base.AlienHairColorSecondary.SelectedColor);
}*/
private void GenderChange(object sender)
{
if (this.Pawn.story.bodyType == BodyTypeDefOf.Male &&
this.Pawn.gender == Gender.Male)
{
this.Pawn.story.bodyType = BodyTypeDefOf.Female;
}
else if (this.Pawn.story.bodyType == BodyTypeDefOf.Female &&
this.Pawn.gender == Gender.Female)
{
this.Pawn.story.bodyType = BodyTypeDefOf.Male;
}
}
internal override void SetCrownType(object value)
{
//AlienPartGenerator apg = (base.Pawn.def as ThingDef_AlienRace)?.alienRace?.generalSettings?.alienPartGenerator;
AlienComp ac = base.Pawn.TryGetComp<AlienComp>();
if (ac != null)
{
var split = value.ToString().Split('/');
if (split.Count() > 0)
{
ac.crownType = split.Last().Replace("Male_", "").Replace("Female_", "");
typeof(Pawn_StoryTracker).GetField("headGraphicPath", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(this.Pawn.story, value);
}
}
}
}
}
| 46.054545 | 166 | 0.54017 | [
"MIT"
] | KiameV/rimworld-changedresser | Source/UI/DTO/AlienDresserDTO.cs | 10,134 | 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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
/// <summary>
/// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services.
/// </summary>
internal sealed class EditAndContinueWorkspaceService : IEditAndContinueWorkspaceService
{
[ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService)), Shared]
private sealed class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices)
=> new EditAndContinueWorkspaceService(workspaceServices.Workspace);
}
internal static readonly TraceLog Log = new(2048, "EnC");
private readonly Workspace _workspace;
private readonly EditSessionTelemetry _editSessionTelemetry;
private readonly DebuggingSessionTelemetry _debuggingSessionTelemetry;
private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider;
private readonly Action<DebuggingSessionTelemetry.Data> _reportTelemetry;
/// <summary>
/// A document id is added whenever a diagnostic is reported while in run mode.
/// These diagnostics are cleared as soon as we enter break mode or the debugging session terminates.
/// </summary>
private readonly HashSet<DocumentId> _documentsWithReportedDiagnosticsDuringRunMode;
private readonly object _documentsWithReportedDiagnosticsDuringRunModeGuard = new();
private DebuggingSession? _debuggingSession;
private EditSession? _editSession;
internal EditAndContinueWorkspaceService(
Workspace workspace,
Func<Project, CompilationOutputs>? testCompilationOutputsProvider = null,
Action<DebuggingSessionTelemetry.Data>? testReportTelemetry = null)
{
_workspace = workspace;
_debuggingSessionTelemetry = new DebuggingSessionTelemetry();
_editSessionTelemetry = new EditSessionTelemetry();
_documentsWithReportedDiagnosticsDuringRunMode = new HashSet<DocumentId>();
_compilationOutputsProvider = testCompilationOutputsProvider ?? GetCompilationOutputs;
_reportTelemetry = testReportTelemetry ?? ReportTelemetry;
}
// test only:
internal DebuggingSession? Test_GetDebuggingSession() => _debuggingSession;
internal EditSession? Test_GetEditSession() => _editSession;
internal Workspace Test_GetWorkspace() => _workspace;
private static CompilationOutputs GetCompilationOutputs(Project project)
{
// The Project System doesn't always indicate whether we emit PDB, what kind of PDB we emit nor the path of the PDB.
// To work around we look for the PDB on the path specified in the PDB debug directory.
// https://github.com/dotnet/roslyn/issues/35065
return new CompilationOutputFilesWithImplicitPdbPath(project.CompilationOutputInfo.AssemblyPath);
}
public void OnSourceFileUpdated(Document document)
{
var debuggingSession = _debuggingSession;
if (debuggingSession != null)
{
// fire and forget
_ = Task.Run(() => debuggingSession.LastCommittedSolution.OnSourceFileUpdatedAsync(document, debuggingSession.CancellationToken));
}
}
public void StartDebuggingSession(Solution solution)
{
var previousSession = Interlocked.CompareExchange(ref _debuggingSession, new DebuggingSession(solution, _compilationOutputsProvider), null);
Contract.ThrowIfFalse(previousSession == null, "New debugging session can't be started until the existing one has ended.");
}
public void StartEditSession(IManagedEditAndContinueDebuggerService debuggerService, out ImmutableArray<DocumentId> documentsToReanalyze)
{
var debuggingSession = _debuggingSession;
Contract.ThrowIfNull(debuggingSession, "Edit session can only be started during debugging session");
var newSession = new EditSession(debuggingSession, _editSessionTelemetry, debuggerService);
var previousSession = Interlocked.CompareExchange(ref _editSession, newSession, null);
Contract.ThrowIfFalse(previousSession == null, "New edit session can't be started until the existing one has ended.");
// clear diagnostics reported during run mode:
ClearReportedRunModeDiagnostics(out documentsToReanalyze);
}
public void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze)
{
// first, publish null session:
var session = Interlocked.Exchange(ref _editSession, null);
Contract.ThrowIfNull(session, "Edit session has not started.");
// then cancel all ongoing work bound to the session:
session.Cancel();
// clear all reported rude edits:
documentsToReanalyze = session.GetDocumentsWithReportedDiagnostics();
_debuggingSessionTelemetry.LogEditSession(_editSessionTelemetry.GetDataAndClear());
session.Dispose();
}
public void EndDebuggingSession(out ImmutableArray<DocumentId> documentsToReanalyze)
{
var debuggingSession = Interlocked.Exchange(ref _debuggingSession, null);
Contract.ThrowIfNull(debuggingSession, "Debugging session has not started.");
// cancel all ongoing work bound to the session:
debuggingSession.Cancel();
_reportTelemetry(_debuggingSessionTelemetry.GetDataAndClear());
// clear diagnostics reported during run mode:
ClearReportedRunModeDiagnostics(out documentsToReanalyze);
debuggingSession.Dispose();
}
internal static bool SupportsEditAndContinue(Project project)
=> project.LanguageServices.GetService<IEditAndContinueAnalyzer>() != null;
public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, DocumentActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken)
{
try
{
var debuggingSession = _debuggingSession;
if (debuggingSession == null)
{
return ImmutableArray<Diagnostic>.Empty;
}
// Not a C# or VB project.
var project = document.Project;
if (!SupportsEditAndContinue(project))
{
return ImmutableArray<Diagnostic>.Empty;
}
// Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only)
if (document.State.Attributes.DesignTimeOnly || !document.SupportsSyntaxTree)
{
return ImmutableArray<Diagnostic>.Empty;
}
// Do not analyze documents (and report diagnostics) of projects that have not been built.
// Allow user to make any changes in these documents, they won't be applied within the current debugging session.
// Do not report the file read error - it might be an intermittent issue. The error will be reported when the
// change is attempted to be applied.
var (mvid, _) = await debuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false);
if (mvid == Guid.Empty)
{
return ImmutableArray<Diagnostic>.Empty;
}
var (oldDocument, oldDocumentState) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false);
if (oldDocumentState == CommittedSolution.DocumentState.OutOfSync ||
oldDocumentState == CommittedSolution.DocumentState.Indeterminate ||
oldDocumentState == CommittedSolution.DocumentState.DesignTimeOnly)
{
// Do not report diagnostics for existing out-of-sync documents or design-time-only documents.
return ImmutableArray<Diagnostic>.Empty;
}
// The document has not changed while the application is running since the last changes were committed:
var editSession = _editSession;
if (editSession == null)
{
if (document == oldDocument)
{
return ImmutableArray<Diagnostic>.Empty;
}
// Any changes made in loaded, built projects outside of edit session are rude edits (the application is running):
var newSyntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(newSyntaxTree);
var changedSpans = await GetChangedSpansAsync(oldDocument, newSyntaxTree, cancellationToken).ConfigureAwait(false);
return GetRunModeDocumentDiagnostics(document, newSyntaxTree, changedSpans);
}
var oldProject = oldDocument?.Project ?? debuggingSession.LastCommittedSolution.GetProject(project.Id);
if (oldProject == null)
{
// TODO https://github.com/dotnet/roslyn/issues/1204:
// Project deleted (shouldn't happen since Project System does not allow removing projects while debugging) or
// was not loaded when the debugging session started.
return ImmutableArray<Diagnostic>.Empty;
}
var documentActiveStatementSpans = await activeStatementSpanProvider(cancellationToken).ConfigureAwait(false);
var analysis = await editSession.Analyses.GetDocumentAnalysisAsync(oldProject, document, documentActiveStatementSpans, cancellationToken).ConfigureAwait(false);
if (analysis.HasChanges)
{
// Once we detected a change in a document let the debugger know that the corresponding loaded module
// is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying
// the change blocks the UI when the user "continues".
if (debuggingSession.AddModulePreparedForUpdate(mvid))
{
// fire and forget:
_ = Task.Run(() => editSession.DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken);
}
}
if (analysis.RudeEditErrors.IsEmpty)
{
return ImmutableArray<Diagnostic>.Empty;
}
editSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors);
// track the document, so that we can refresh or clean diagnostics at the end of edit session:
editSession.TrackDocumentWithReportedDiagnostics(document.Id);
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e))
{
return ImmutableArray<Diagnostic>.Empty;
}
}
private static async Task<IEnumerable<TextSpan>> GetChangedSpansAsync(Document? oldDocument, SyntaxTree newSyntaxTree, CancellationToken cancellationToken)
{
if (oldDocument != null)
{
var oldSyntaxTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(oldSyntaxTree);
return GetSpansInNewDocument(await GetDocumentTextChangesAsync(oldSyntaxTree, newSyntaxTree, cancellationToken).ConfigureAwait(false));
}
var newRoot = await newSyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
return SpecializedCollections.SingletonEnumerable(newRoot.FullSpan);
}
private ImmutableArray<Diagnostic> GetRunModeDocumentDiagnostics(Document newDocument, SyntaxTree newSyntaxTree, IEnumerable<TextSpan> changedSpans)
{
if (!changedSpans.Any())
{
return ImmutableArray<Diagnostic>.Empty;
}
lock (_documentsWithReportedDiagnosticsDuringRunModeGuard)
{
_documentsWithReportedDiagnosticsDuringRunMode.Add(newDocument.Id);
}
var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ChangesNotAppliedWhileRunning);
var args = new[] { newDocument.Project.Name };
return changedSpans.SelectAsArray(span => Diagnostic.Create(descriptor, Location.Create(newSyntaxTree, span), args));
}
// internal for testing
internal static async Task<IList<TextChange>> GetDocumentTextChangesAsync(SyntaxTree oldSyntaxTree, SyntaxTree newSyntaxTree, CancellationToken cancellationToken)
{
var list = newSyntaxTree.GetChanges(oldSyntaxTree);
if (list.Count != 0)
{
return list;
}
var oldText = await oldSyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
var newText = await newSyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (oldText.ContentEquals(newText))
{
return Array.Empty<TextChange>();
}
var roList = newText.GetTextChanges(oldText);
if (roList.Count != 0)
{
return roList.ToArray();
}
return Array.Empty<TextChange>();
}
// internal for testing
internal static IEnumerable<TextSpan> GetSpansInNewDocument(IEnumerable<TextChange> changes)
{
var oldPosition = 0;
var newPosition = 0;
foreach (var change in changes)
{
if (change.Span.Start < oldPosition)
{
Debug.Fail("Text changes not ordered");
yield break;
}
RoslynDebug.Assert(change.NewText is object);
if (change.Span.Length == 0 && change.NewText.Length == 0)
{
continue;
}
// skip unchanged text:
newPosition += change.Span.Start - oldPosition;
yield return new TextSpan(newPosition, change.NewText.Length);
// apply change:
oldPosition = change.Span.End;
newPosition += change.NewText.Length;
}
}
private void ClearReportedRunModeDiagnostics(out ImmutableArray<DocumentId> documentsToReanalyze)
{
// clear diagnostics reported during run mode:
lock (_documentsWithReportedDiagnosticsDuringRunModeGuard)
{
documentsToReanalyze = _documentsWithReportedDiagnosticsDuringRunMode.ToImmutableArray();
_documentsWithReportedDiagnosticsDuringRunMode.Clear();
}
}
/// <summary>
/// Determine whether the updates made to projects containing the specified file (or all projects that are built,
/// if <paramref name="sourceFilePath"/> is null) are ready to be applied and the debugger should attempt to apply
/// them on "continue".
/// </summary>
/// <returns>
/// Returns <see cref="ManagedModuleUpdateStatus.Blocked"/> if there are rude edits or other errors
/// that block the application of the updates. Might return <see cref="ManagedModuleUpdateStatus.Ready"/> even if there are
/// errors in the code that will block the application of the updates. E.g. emit diagnostics can't be determined until
/// emit is actually performed. Therefore, this method only serves as an optimization to avoid unnecessary emit attempts,
/// but does not provide a definitive answer. Only <see cref="EmitSolutionUpdateAsync"/> can definitively determine whether
/// the update is valid or not.
/// </returns>
public ValueTask<bool> HasChangesAsync(Solution solution, SolutionActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken)
{
// GetStatusAsync is called outside of edit session when the debugger is determining
// whether a source file checksum matches the one in PDB.
// The debugger expects no changes in this case.
var editSession = _editSession;
if (editSession == null)
{
return default;
}
return editSession.HasChangesAsync(solution, solutionActiveStatementSpanProvider, sourceFilePath, cancellationToken);
}
public async ValueTask<(ManagedModuleUpdates Updates, ImmutableArray<DiagnosticData> Diagnostics)>
EmitSolutionUpdateAsync(Solution solution, SolutionActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken)
{
var editSession = _editSession;
if (editSession == null)
{
return (new(ManagedModuleUpdateStatus.None, ImmutableArray<ManagedModuleUpdate>.Empty), ImmutableArray<DiagnosticData>.Empty);
}
var solutionUpdate = await editSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false);
if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready)
{
editSession.StorePendingUpdate(solution, solutionUpdate);
}
// Note that we may return empty deltas if all updates have been deferred.
// The debugger will still call commit or discard on the update batch.
return (solutionUpdate.ModuleUpdates, ToDiagnosticData(solution, solutionUpdate.Diagnostics));
}
private static ImmutableArray<DiagnosticData> ToDiagnosticData(Solution solution, ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostics)> diagnosticsByProject)
{
using var _ = ArrayBuilder<DiagnosticData>.GetInstance(out var result);
foreach (var (projectId, diagnostics) in diagnosticsByProject)
{
var project = solution.GetRequiredProject(projectId);
foreach (var diagnostic in diagnostics)
{
var document = solution.GetDocument(diagnostic.Location.SourceTree);
var data = (document != null) ? DiagnosticData.Create(diagnostic, document) : DiagnosticData.Create(diagnostic, project);
result.Add(data);
}
}
return result.ToImmutable();
}
public void CommitSolutionUpdate()
{
var editSession = _editSession;
Contract.ThrowIfNull(editSession);
var pendingUpdate = editSession.RetrievePendingUpdate();
editSession.DebuggingSession.CommitSolutionUpdate(pendingUpdate);
editSession.ChangesApplied();
}
public void DiscardSolutionUpdate()
{
var editSession = _editSession;
Contract.ThrowIfNull(editSession);
var pendingUpdate = editSession.RetrievePendingUpdate();
foreach (var moduleReader in pendingUpdate.ModuleReaders)
{
moduleReader.Dispose();
}
}
public async ValueTask<ImmutableArray<ImmutableArray<(LinePositionSpan, ActiveStatementFlags)>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken)
{
var editSession = _editSession;
if (editSession == null)
{
return default;
}
var lastCommittedSolution = editSession.DebuggingSession.LastCommittedSolution;
var baseActiveStatements = await editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<ImmutableArray<(LinePositionSpan, ActiveStatementFlags)>>.GetInstance(out var spans);
foreach (var documentId in documentIds)
{
if (baseActiveStatements.DocumentMap.TryGetValue(documentId, out var documentActiveStatements))
{
var document = solution.GetDocument(documentId);
var (baseDocument, _) = await lastCommittedSolution.GetDocumentAndStateAsync(documentId, document, cancellationToken).ConfigureAwait(false);
if (baseDocument != null)
{
spans.Add(documentActiveStatements.SelectAsArray(s => (s.Span, s.Flags)));
continue;
}
}
// Document contains no active statements, or the document is not C#/VB document,
// it has been added, is out-of-sync or a design-time-only document.
spans.Add(ImmutableArray<(LinePositionSpan, ActiveStatementFlags)>.Empty);
}
return spans.ToImmutable();
}
public async ValueTask<ImmutableArray<(LinePositionSpan, ActiveStatementFlags)>> GetAdjustedActiveStatementSpansAsync(Document document, DocumentActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken)
{
var editSession = _editSession;
if (editSession == null)
{
return default;
}
if (!SupportsEditAndContinue(document.Project))
{
return default;
}
var lastCommittedSolution = editSession.DebuggingSession.LastCommittedSolution;
var (baseDocument, _) = await lastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false);
if (baseDocument == null)
{
return default;
}
var documentActiveStatementSpans = await activeStatementSpanProvider(cancellationToken).ConfigureAwait(false);
var activeStatements = await editSession.Analyses.GetActiveStatementsAsync(baseDocument, document, documentActiveStatementSpans, cancellationToken).ConfigureAwait(false);
if (activeStatements.IsDefault)
{
return default;
}
return activeStatements.SelectAsArray(s => (s.Span, s.Flags));
}
public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, SolutionActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken)
{
try
{
// It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so.
// We return null since there the concept of active statement only makes sense during break mode.
var editSession = _editSession;
if (editSession == null)
{
return null;
}
// TODO: Avoid enumerating active statements for unchanged documents.
// We would need to add a document path parameter to be able to find the document we need to check for changes.
// https://github.com/dotnet/roslyn/issues/24324
var baseActiveStatements = await editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement))
{
return null;
}
var primaryDocument = solution.GetDocument(baseActiveStatement.PrimaryDocumentId);
if (primaryDocument == null)
{
// The document has been deleted.
return null;
}
var (oldPrimaryDocument, _) = await editSession.DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(baseActiveStatement.PrimaryDocumentId, primaryDocument, cancellationToken).ConfigureAwait(false);
if (oldPrimaryDocument == null)
{
// Can't determine position of an active statement if the document is out-of-sync with loaded module debug information.
return null;
}
var activeStatementSpans = await activeStatementSpanProvider(primaryDocument.Id, cancellationToken).ConfigureAwait(false);
var currentActiveStatements = await editSession.Analyses.GetActiveStatementsAsync(oldPrimaryDocument, primaryDocument, activeStatementSpans, cancellationToken).ConfigureAwait(false);
if (currentActiveStatements.IsDefault)
{
// The document has syntax errors.
return null;
}
return currentActiveStatements[baseActiveStatement.PrimaryDocumentOrdinal].Span;
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e))
{
return null;
}
}
/// <summary>
/// Called by the debugger to determine whether an active statement is in an exception region,
/// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes.
/// If the debugger determines we can remap active statements, the application of changes proceeds.
/// </summary>
/// <returns>
/// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement
/// or the exception regions can't be determined.
/// </returns>
public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken)
{
try
{
var editSession = _editSession;
if (editSession == null)
{
return null;
}
// This method is only called when the EnC is about to apply changes, at which point all active statements and
// their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction
// the debugger is interested at this point while not calculating the others.
var baseActiveStatements = await editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement))
{
return null;
}
var baseExceptionRegions = (await editSession.GetBaseActiveExceptionRegionsAsync(solution, cancellationToken).ConfigureAwait(false))[baseActiveStatement.Ordinal];
// If the document is out-of-sync the exception regions can't be determined.
return baseExceptionRegions.Spans.IsDefault ? (bool?)null : baseExceptionRegions.IsActiveStatementCovered;
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e))
{
return null;
}
}
private static void ReportTelemetry(DebuggingSessionTelemetry.Data data)
{
// report telemetry (fire and forget):
_ = Task.Run(() => LogDebuggingSessionTelemetry(data, Logger.Log, LogAggregator.GetNextId));
}
// internal for testing
internal static void LogDebuggingSessionTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId)
{
const string SessionId = nameof(SessionId);
const string EditSessionId = nameof(EditSessionId);
var debugSessionId = getNextId();
log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map =>
{
map[SessionId] = debugSessionId;
map["SessionCount"] = debugSessionData.EditSessionData.Length;
map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount;
}));
foreach (var editSessionData in debugSessionData.EditSessionData)
{
var editSessionId = getNextId();
log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map =>
{
map[SessionId] = debugSessionId;
map[EditSessionId] = editSessionId;
map["HadCompilationErrors"] = editSessionData.HadCompilationErrors;
map["HadRudeEdits"] = editSessionData.HadRudeEdits;
map["HadValidChanges"] = editSessionData.HadValidChanges;
map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges;
map["RudeEditsCount"] = editSessionData.RudeEdits.Length;
map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length;
}));
foreach (var errorId in editSessionData.EmitErrorIds)
{
log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map =>
{
map[SessionId] = debugSessionId;
map[EditSessionId] = editSessionId;
map["ErrorId"] = errorId;
}));
}
foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits)
{
log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map =>
{
map[SessionId] = debugSessionId;
map[EditSessionId] = editSessionId;
map["RudeEditKind"] = editKind;
map["RudeEditSyntaxKind"] = syntaxKind;
map["RudeEditBlocking"] = editSessionData.HadRudeEdits;
}));
}
}
}
}
}
| 49.078669 | 246 | 0.638698 | [
"MIT"
] | CXuesong/roslyn | src/Features/Core/Portable/EditAndContinue/EditAndContinueWorkspaceService.cs | 32,443 | C# |
using System;
using System.Linq;
using System.ComponentModel;
using NLua;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Common.IEmulatorExtensions;
using BizHawk.Emulation.Cores.Nintendo.N64;
namespace BizHawk.Client.Common
{
[Description("A library for registering lua functions to emulator events.\n All events support multiple registered methods.\nAll registered event methods can be named and return a Guid when registered")]
public sealed class EventLuaLibrary : LuaLibraryBase
{
[OptionalService]
private IInputPollable InputPollableCore { get; set; }
[OptionalService]
private IDebuggable DebuggableCore { get; set; }
[RequiredService]
private IEmulator Emulator { get; set; }
private readonly LuaFunctionList _luaFunctions = new LuaFunctionList();
public EventLuaLibrary(Lua lua)
: base(lua) { }
public EventLuaLibrary(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { }
public override string Name => "event";
#region Events Library Helpers
public void CallExitEvent(Lua thread)
{
var exitCallbacks = _luaFunctions.Where(l => l.Lua == thread && l.Event == "OnExit");
foreach (var exitCallback in exitCallbacks)
{
exitCallback.Call();
}
}
public LuaFunctionList RegisteredFunctions => _luaFunctions;
public void CallSaveStateEvent(string name)
{
var lfs = _luaFunctions.Where(l => l.Event == "OnSavestateSave").ToList();
if (lfs.Any())
{
try
{
foreach (var lf in lfs)
{
lf.Call(name);
}
}
catch (Exception e)
{
Log(
"error running function attached by lua function event.onsavestate" +
"\nError message: " +
e.Message);
}
}
}
public void CallLoadStateEvent(string name)
{
var lfs = _luaFunctions.Where(l => l.Event == "OnSavestateLoad").ToList();
if (lfs.Any())
{
try
{
foreach (var lf in lfs)
{
lf.Call(name);
}
}
catch (Exception e)
{
Log(
"error running function attached by lua function event.onloadstate" +
"\nError message: " +
e.Message);
}
}
}
public void CallFrameBeforeEvent()
{
var lfs = _luaFunctions.Where(l => l.Event == "OnFrameStart").ToList();
if (lfs.Any())
{
try
{
foreach (var lf in lfs)
{
lf.Call();
}
}
catch (Exception e)
{
Log(
"error running function attached by lua function event.onframestart" +
"\nError message: " +
e.Message);
}
}
}
public void CallFrameAfterEvent()
{
var lfs = _luaFunctions.Where(l => l.Event == "OnFrameEnd").ToList();
if (lfs.Any())
{
try
{
foreach (var lf in lfs)
{
lf.Call();
}
}
catch (Exception e)
{
Log(
"error running function attached by lua function event.onframeend" +
"\nError message: " +
e.Message);
}
}
}
private bool N64CoreTypeDynarec()
{
//if ((Emulator as N64)?.GetSyncSettings().Core == N64SyncSettings.CoreType.Dynarec)
//{
// Log("N64 Error: Memory callbacks are not implemented for Dynamic Recompiler core type\nUse Interpreter or Pure Interpreter\n");
// return true;
//}
return false;
}
private void LogMemoryCallbacksNotImplemented()
{
Log($"{Emulator.Attributes().CoreName} does not implement memory callbacks");
}
private void LogMemoryExecuteCallbacksNotImplemented()
{
Log($"{Emulator.Attributes().CoreName} does not implement memory execute callbacks");
}
#endregion
[LuaMethod("onframeend", "Calls the given lua function at the end of each frame, after all emulation and drawing has completed. Note: this is the default behavior of lua scripts")]
public string OnFrameEnd(LuaFunction luaf, string name = null)
{
var nlf = new NamedLuaFunction(luaf, "OnFrameEnd", LogOutputCallback, CurrentThread, name);
_luaFunctions.Add(nlf);
return nlf.Guid.ToString();
}
[LuaMethod("onframestart", "Calls the given lua function at the beginning of each frame before any emulation and drawing occurs")]
public string OnFrameStart(LuaFunction luaf, string name = null)
{
var nlf = new NamedLuaFunction(luaf, "OnFrameStart", LogOutputCallback, CurrentThread, name);
_luaFunctions.Add(nlf);
return nlf.Guid.ToString();
}
[LuaMethod("oninputpoll", "Calls the given lua function after each time the emulator core polls for input")]
public string OnInputPoll(LuaFunction luaf, string name = null)
{
var nlf = new NamedLuaFunction(luaf, "OnInputPoll", LogOutputCallback, CurrentThread, name);
_luaFunctions.Add(nlf);
if (InputPollableCore != null)
{
try
{
InputPollableCore.InputCallbacks.Add(nlf.Callback);
return nlf.Guid.ToString();
}
catch (NotImplementedException)
{
LogNotImplemented();
return Guid.Empty.ToString();
}
}
LogNotImplemented();
return Guid.Empty.ToString();
}
private void LogNotImplemented()
{
Log($"Error: {Emulator.Attributes().CoreName} does not yet implement input polling callbacks");
}
[LuaMethod("onloadstate", "Fires after a state is loaded. Receives a lua function name, and registers it to the event immediately following a successful savestate event")]
public string OnLoadState(LuaFunction luaf, string name = null)
{
var nlf = new NamedLuaFunction(luaf, "OnSavestateLoad", LogOutputCallback, CurrentThread, name);
_luaFunctions.Add(nlf);
return nlf.Guid.ToString();
}
[LuaMethod("onmemoryexecute", "Fires after the given address is executed by the core")]
public string OnMemoryExecute(LuaFunction luaf, uint address, string name = null)
{
try
{
if (DebuggableCore != null && DebuggableCore.MemoryCallbacksAvailable() &&
DebuggableCore.MemoryCallbacks.ExecuteCallbacksAvailable)
{
if (N64CoreTypeDynarec())
{
return Guid.Empty.ToString();
}
var nlf = new NamedLuaFunction(luaf, "OnMemoryExecute", LogOutputCallback, CurrentThread, name);
_luaFunctions.Add(nlf);
DebuggableCore.MemoryCallbacks.Add(
new MemoryCallback(MemoryCallbackType.Execute, "Lua Hook", nlf.Callback, address, null));
return nlf.Guid.ToString();
}
}
catch (NotImplementedException)
{
LogMemoryExecuteCallbacksNotImplemented();
return Guid.Empty.ToString();
}
LogMemoryExecuteCallbacksNotImplemented();
return Guid.Empty.ToString();
}
[LuaMethod("onmemoryread", "Fires after the given address is read by the core. If no address is given, it will attach to every memory read")]
public string OnMemoryRead(LuaFunction luaf, uint? address = null, string name = null)
{
try
{
if (DebuggableCore != null && DebuggableCore.MemoryCallbacksAvailable())
{
if (N64CoreTypeDynarec())
{
return Guid.Empty.ToString();
}
var nlf = new NamedLuaFunction(luaf, "OnMemoryRead", LogOutputCallback, CurrentThread, name);
_luaFunctions.Add(nlf);
DebuggableCore.MemoryCallbacks.Add(
new MemoryCallback(MemoryCallbackType.Read, "Lua Hook", nlf.Callback, address, null));
return nlf.Guid.ToString();
}
}
catch (NotImplementedException)
{
LogMemoryCallbacksNotImplemented();
return Guid.Empty.ToString();
}
LogMemoryCallbacksNotImplemented();
return Guid.Empty.ToString();
}
[LuaMethod("onmemorywrite", "Fires after the given address is written by the core. If no address is given, it will attach to every memory write")]
public string OnMemoryWrite(LuaFunction luaf, uint? address = null, string name = null)
{
try
{
if (DebuggableCore != null && DebuggableCore.MemoryCallbacksAvailable())
{
if (N64CoreTypeDynarec())
{
return Guid.Empty.ToString();
}
var nlf = new NamedLuaFunction(luaf, "OnMemoryWrite", LogOutputCallback, CurrentThread, name);
_luaFunctions.Add(nlf);
DebuggableCore.MemoryCallbacks.Add(
new MemoryCallback(MemoryCallbackType.Write, "Lua Hook", nlf.Callback, address, null));
return nlf.Guid.ToString();
}
}
catch (NotImplementedException)
{
LogMemoryCallbacksNotImplemented();
return Guid.Empty.ToString();
}
LogMemoryCallbacksNotImplemented();
return Guid.Empty.ToString();
}
[LuaMethod("onsavestate", "Fires after a state is saved")]
public string OnSaveState(LuaFunction luaf, string name = null)
{
var nlf = new NamedLuaFunction(luaf, "OnSavestateSave", LogOutputCallback, CurrentThread, name);
_luaFunctions.Add(nlf);
return nlf.Guid.ToString();
}
[LuaMethod("onexit", "Fires after the calling script has stopped")]
public string OnExit(LuaFunction luaf, string name = null)
{
var nlf = new NamedLuaFunction(luaf, "OnExit", LogOutputCallback, CurrentThread, name);
_luaFunctions.Add(nlf);
return nlf.Guid.ToString();
}
[LuaMethod("unregisterbyid", "Removes the registered function that matches the guid. If a function is found and remove the function will return true. If unable to find a match, the function will return false.")]
public bool UnregisterById(string guid)
{
foreach (var nlf in _luaFunctions.Where(nlf => nlf.Guid.ToString() == guid.ToString()))
{
_luaFunctions.Remove(nlf);
return true;
}
return false;
}
[LuaMethod("unregisterbyname", "Removes the first registered function that matches Name. If a function is found and remove the function will return true. If unable to find a match, the function will return false.")]
public bool UnregisterByName(string name)
{
foreach (var nlf in _luaFunctions.Where(nlf => nlf.Name == name))
{
_luaFunctions.Remove(nlf);
return true;
}
return false;
}
}
}
| 28.299419 | 217 | 0.686492 | [
"MIT"
] | CognitiaAI/StreetFighterRL | emulator/Bizhawk/BizHawk-master/BizHawk.Client.Common/lua/EmuLuaLibrary.Events.cs | 9,737 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(VehicleStatisticsApi.Startup))]
namespace VehicleStatisticsApi
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
| 18.368421 | 61 | 0.690544 | [
"Apache-2.0"
] | wizzardz/vehicle-statistics-india | src/VehicleStatisticsApi/VehicleStatisticsApi/Startup.cs | 351 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Rnwood.Smtp4dev.Data;
using Rnwood.Smtp4dev.DbModel;
namespace Rnwood.Smtp4dev.Tests
{
internal class TestMessagesRepository : IMessagesRepository
{
public TestMessagesRepository(params Message[] messages)
{
Messages.AddRange(messages);
}
public List<DbModel.Message> Messages { get; } = new List<Message>();
public Task DeleteAllMessages()
{
Messages.Clear();
return Task.CompletedTask;
}
public Task DeleteMessage(Guid id)
{
Messages.RemoveAll(m => m.Id == id);
return Task.CompletedTask;
}
public IQueryable<Message> GetMessages(bool unTracked = true)
{
return Messages.AsQueryable();
}
public Task MarkMessageRead(Guid id)
{
Messages.FirstOrDefault(m => m.Id == id).IsUnread = false;
return Task.CompletedTask;
}
}
}
| 20.659091 | 71 | 0.722772 | [
"BSD-3-Clause"
] | smchristensen/smtp4dev | Rnwood.Smtp4dev.Tests/TestMessagesRepository.cs | 911 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.R_kvstore.Model.V20150101;
namespace Aliyun.Acs.R_kvstore.Transform.V20150101
{
public class VerifyPasswordResponseUnmarshaller
{
public static VerifyPasswordResponse Unmarshall(UnmarshallerContext context)
{
VerifyPasswordResponse verifyPasswordResponse = new VerifyPasswordResponse();
verifyPasswordResponse.HttpResponse = context.HttpResponse;
verifyPasswordResponse.RequestId = context.StringValue("VerifyPassword.RequestId");
return verifyPasswordResponse;
}
}
}
| 36 | 86 | 0.759028 | [
"Apache-2.0"
] | bitType/aliyun-openapi-net-sdk | aliyun-net-sdk-r-kvstore/R_kvstore/Transform/V20150101/VerifyPasswordResponseUnmarshaller.cs | 1,440 | C# |
using System;
using Microsoft.Azure.Search;
using Microsoft.Azure.Search.Models;
using Microsoft.Spatial;
using Newtonsoft.Json;
namespace Typeahead.Models
{
public partial class Hotel
{
[System.ComponentModel.DataAnnotations.Key]
[IsFilterable]
public string HotelId { get; set; }
[IsSearchable, IsSortable]
public string HotelName { get; set; }
[IsSearchable]
[Analyzer(AnalyzerName.AsString.EnLucene)]
public string Description { get; set; }
[IsSearchable]
[Analyzer(AnalyzerName.AsString.FrLucene)]
[JsonProperty("Description_fr")]
public string DescriptionFr { get; set; }
[IsSearchable, IsFilterable, IsSortable, IsFacetable]
public string Category { get; set; }
[IsSearchable, IsFilterable, IsFacetable]
public string[] Tags { get; set; }
[IsFilterable, IsSortable, IsFacetable]
public bool? ParkingIncluded { get; set; }
[IsFilterable, IsSortable, IsFacetable]
public DateTimeOffset? LastRenovationDate { get; set; }
[IsFilterable, IsSortable, IsFacetable]
public double? Rating { get; set; }
public Address Address { get; set; }
[IsFilterable, IsSortable]
public GeographyPoint Location { get; set; }
public Room[] Rooms { get; set; }
}
}
| 27.62 | 63 | 0.643736 | [
"MIT"
] | 2012952877/Azure-Cognitive-Search-Demo | 9 Reference/azure-search-dotnet-samples-master/create-first-app/v10/3-add-typeahead/Typeahead/Models/Hotel.cs | 1,383 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SetCharButtons : MonoBehaviour
{
public bool isSelect;
public SetCharButtons button1;
public SetCharButtons button2;
public SpriteRenderer sr1;
public SpriteRenderer sr2;
public SpriteRenderer sr3;
public SpriteRenderer sr4;
public void OnClick()
{
isSelect = true;
button1.isSelect = false;
button2.isSelect = false;
}
private void Update()
{
if(isSelect)
{
sr1.color = new Color(255, 255, 0);
sr2.color = new Color(255, 255, 0);
sr3.color = new Color(255, 255, 0);
sr4.color = new Color(255, 255, 0);
}
else
{
sr1.color = new Color(255, 255, 255);
sr2.color = new Color(255, 255, 255);
sr3.color = new Color(255, 255, 255);
sr4.color = new Color(255, 255, 255);
}
}
}
| 22.488889 | 49 | 0.572134 | [
"MIT"
] | WoobinMin/OSSProject | Assets/Script/2.CharSelScene/SetCharButtons.cs | 1,014 | C# |
/*
* SubSonic - http://subsonicproject.com
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/
namespace SubSonic
{
/// <summary>
///
/// </summary>
public class Sql2000Generator : ANSISqlGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="Sql2000Generator"/> class.
/// </summary>
/// <param name="query">The query.</param>
public Sql2000Generator(SqlQuery query)
: base(query) {}
}
} | 31.965517 | 83 | 0.655879 | [
"BSD-3-Clause"
] | BlackMael/SubSonic-2.0 | SubSonic/SqlQuery/SqlGenerators/Sql2000Generator.cs | 927 | C# |
namespace CFGToolkit.Lexer
{
public interface IMatch
{
string Value { get; set; }
bool Success { get; set; }
}
} | 15.777778 | 34 | 0.556338 | [
"MIT"
] | CFGToolkit/CFGToolkit.Lexer | CFGToolkit.Lexer/IMatch.cs | 144 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Options;
namespace TileServerCore.Controllers
{
[Route("api/[controller]")]
public class TilesController : Controller
{
private readonly AppSettings _appSettings;
public TilesController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}
// GET tiles/z/x/y
[HttpGet("{z}/{x}/{y}")]
public byte[] Get(int z, int x, int y)
{
Console.WriteLine($"Tile path: {_appSettings.TilePath}");
var connectionStringBuilder = new SqliteConnectionStringBuilder
{
DataSource = _appSettings.TilePath
};
using (var connection = new SqliteConnection(connectionStringBuilder.ToString()))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
var selectCommand = connection.CreateCommand();
selectCommand.Transaction = transaction;
//SQL injection not a concern b/c these are ints
selectCommand.CommandText = $"SELECT tile_data FROM `tiles` where zoom_level = {z} and tile_column = {x} and tile_row = {y}";
var tileData = (byte[]) selectCommand.ExecuteScalar();
return tileData;
}
}
}
}
}
| 32.673469 | 145 | 0.580262 | [
"Unlicense"
] | rgwood/tile-server-core | TileServerCore/Controllers/TilesController.cs | 1,603 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Cam.V20190116.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DetectStateResponse : AbstractModel
{
/// <summary>
/// 用户uin
/// </summary>
[JsonProperty("Uin")]
public string Uin{ get; set; }
/// <summary>
/// 名字
/// </summary>
[JsonProperty("Name")]
public string Name{ get; set; }
/// <summary>
/// 身份证号码
/// </summary>
[JsonProperty("Idcard")]
public string Idcard{ get; set; }
/// <summary>
/// 业务token
/// </summary>
[JsonProperty("BizToken")]
public string BizToken{ get; set; }
/// <summary>
/// ulr地址
/// </summary>
[JsonProperty("Url")]
public string Url{ get; set; }
/// <summary>
/// 规则id
/// </summary>
[JsonProperty("RuleId")]
public ulong? RuleId{ get; set; }
/// <summary>
/// 状态
/// </summary>
[JsonProperty("Status")]
public ulong? Status{ get; set; }
/// <summary>
/// 类型
/// </summary>
[JsonProperty("Type")]
public string Type{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "Uin", this.Uin);
this.SetParamSimple(map, prefix + "Name", this.Name);
this.SetParamSimple(map, prefix + "Idcard", this.Idcard);
this.SetParamSimple(map, prefix + "BizToken", this.BizToken);
this.SetParamSimple(map, prefix + "Url", this.Url);
this.SetParamSimple(map, prefix + "RuleId", this.RuleId);
this.SetParamSimple(map, prefix + "Status", this.Status);
this.SetParamSimple(map, prefix + "Type", this.Type);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 29.61 | 83 | 0.564674 | [
"Apache-2.0"
] | allenlooplee/tencentcloud-sdk-dotnet | TencentCloud/Cam/V20190116/Models/DetectStateResponse.cs | 3,057 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Reflection;
using Internal.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
public static partial class RuntimeHelpers
{
// The special dll name to be used for DllImport of QCalls
internal const string QCall = "QCall";
public delegate void TryCode(object? userData);
public delegate void CleanupCode(object? userData, bool exceptionThrown);
/// <summary>
/// Slices the specified array using the specified range.
/// </summary>
public static T[] GetSubArray<T>(T[] array, Range range)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
(int offset, int length) = range.GetOffsetAndLength(array.Length);
T[] dest;
if (typeof(T).IsValueType || typeof(T[]) == array.GetType())
{
// We know the type of the array to be exactly T[] or an array variance
// compatible value type substitution like int[] <-> uint[].
if (length == 0)
{
return Array.Empty<T>();
}
dest = new T[length];
}
else
{
// The array is actually a U[] where U:T. We'll make sure to create
// an array of the exact same backing type. The cast to T[] will
// never fail.
dest = Unsafe.As<T[]>(Array.CreateInstance(array.GetType().GetElementType()!, length));
}
// In either case, the newly-allocated array is the exact same type as the
// original incoming array. It's safe for us to Buffer.Memmove the contents
// from the source array to the destination array, otherwise the contents
// wouldn't have been valid for the source array in the first place.
Buffer.Memmove(
ref MemoryMarshal.GetArrayDataReference(dest),
ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), offset),
(uint)length);
return dest;
}
[Obsolete(Obsoletions.ConstrainedExecutionRegionMessage, DiagnosticId = Obsoletions.ConstrainedExecutionRegionDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
public static void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, object? userData)
{
if (code == null)
throw new ArgumentNullException(nameof(code));
if (backoutCode == null)
throw new ArgumentNullException(nameof(backoutCode));
bool exceptionThrown = true;
try
{
code(userData);
exceptionThrown = false;
}
finally
{
backoutCode(userData, exceptionThrown);
}
}
[Obsolete(Obsoletions.ConstrainedExecutionRegionMessage, DiagnosticId = Obsoletions.ConstrainedExecutionRegionDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
public static void PrepareContractedDelegate(Delegate d)
{
}
[Obsolete(Obsoletions.ConstrainedExecutionRegionMessage, DiagnosticId = Obsoletions.ConstrainedExecutionRegionDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
public static void ProbeForSufficientStack()
{
}
[Obsolete(Obsoletions.ConstrainedExecutionRegionMessage, DiagnosticId = Obsoletions.ConstrainedExecutionRegionDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
public static void PrepareConstrainedRegions()
{
}
[Obsolete(Obsoletions.ConstrainedExecutionRegionMessage, DiagnosticId = Obsoletions.ConstrainedExecutionRegionDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
public static void PrepareConstrainedRegionsNoOP()
{
}
internal static bool IsPrimitiveType(this CorElementType et)
// COR_ELEMENT_TYPE_I1,I2,I4,I8,U1,U2,U4,U8,R4,R8,I,U,CHAR,BOOLEAN
=> ((1 << (int)et) & 0b_0011_0000_0000_0011_1111_1111_1100) != 0;
/// <summary>Provide a fast way to access constant data stored in a module as a ReadOnlySpan{T}</summary>
/// <param name="fldHandle">A field handle that specifies the location of the data to be referred to by the ReadOnlySpan{T}. The Rva of the field must be aligned on a natural boundary of type T</param>
/// <returns>A ReadOnlySpan{T} of the data stored in the field</returns>
/// <exception cref="ArgumentException"><paramref name="fldHandle"/> does not refer to a field which is an Rva, is misaligned, or T is of an invalid type.</exception>
/// <remarks>This method is intended for compiler use rather than use directly in code. T must be one of byte, sbyte, char, short, ushort, int, long, ulong, float, or double.</remarks>
[Intrinsic]
public static unsafe ReadOnlySpan<T> CreateSpan<T>(RuntimeFieldHandle fldHandle) => new ReadOnlySpan<T>(GetSpanDataFrom(fldHandle, typeof(T).TypeHandle, out int length), length);
// The following intrinsics return true if input is a compile-time constant
// Feel free to add more overloads on demand
[Intrinsic]
internal static bool IsKnownConstant(string? t) => false;
[Intrinsic]
internal static bool IsKnownConstant(char t) => false;
}
}
| 43.212121 | 209 | 0.639902 | [
"MIT"
] | 333fred/runtime | src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs | 5,704 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KS.Foundation
{
/// <summary>
/// Long Extensions
/// </summary>
public static class LongExtensions
{
/// <summary>
/// The numbers percentage
/// </summary>
/// <param name="number">The number.</param>
/// <param name="percent">The percent.</param>
/// <returns>The result</returns>
public static decimal PercentageOf(this long number, int percent)
{
return (decimal)(number * percent / 100);
}
/// <summary>
/// The numbers percentage
/// </summary>
/// <param name="number">The number.</param>
/// <param name="percent">The percent.</param>
/// <returns>The result</returns>
public static decimal PercentageOf(this long number, float percent)
{
return (decimal)(number * percent / 100);
}
/// <summary>
/// The numbers percentage
/// </summary>
/// <param name="number">The number.</param>
/// <param name="percent">The percent.</param>
/// <returns>The result</returns>
public static decimal PercentageOf(this long number, double percent)
{
return (decimal)(number * percent / 100);
}
/// <summary>
/// The numbers percentage
/// </summary>
/// <param name="number">The number.</param>
/// <param name="percent">The percent.</param>
/// <returns>The result</returns>
public static decimal PercentageOf(this long number, decimal percent)
{
return (decimal)(number * percent / 100);
}
/// <summary>
/// The numbers percentage
/// </summary>
/// <param name="number">The number.</param>
/// <param name="percent">The percent.</param>
/// <returns>The result</returns>
public static decimal PercentageOf(this long number, long percent)
{
return (decimal)(number * percent / 100);
}
/// <summary>
/// Percentage of the number.
/// </summary>
/// <param name="percent">The percent</param>
/// <param name="number">The Number</param>
/// <returns>The result</returns>
public static decimal PercentOf(this long position, int total)
{
decimal result = 0;
if (position > 0 && total > 0)
result = (decimal)position / (decimal)total * 100;
return result;
}
/// <summary>
/// Percentage of the number.
/// </summary>
/// <param name="percent">The percent</param>
/// <param name="number">The Number</param>
/// <returns>The result</returns>
public static decimal PercentOf(this long position, float total)
{
decimal result = 0;
if (position > 0 && total > 0)
result = (decimal)((decimal)position / (decimal)total * 100);
return result;
}
/// <summary>
/// Percentage of the number.
/// </summary>
/// <param name="percent">The percent</param>
/// <param name="number">The Number</param>
/// <returns>The result</returns>
public static decimal PercentOf(this long position, double total)
{
decimal result = 0;
if (position > 0 && total > 0)
result = (decimal)((decimal)position / (decimal)total * 100);
return result;
}
/// <summary>
/// Percentage of the number.
/// </summary>
/// <param name="percent">The percent</param>
/// <param name="number">The Number</param>
/// <returns>The result</returns>
public static decimal PercentOf(this long position, decimal total)
{
decimal result = 0;
if (position > 0 && total > 0)
result = (decimal)position / (decimal)total * 100;
return result;
}
/// <summary>
/// Percentage of the number.
/// </summary>
/// <param name="percent">The percent</param>
/// <param name="number">The Number</param>
/// <returns>The result</returns>
public static decimal PercentOf(this long position, long total)
{
decimal result = 0;
if (position > 0 && total > 0)
result = (decimal)position / (decimal)total * 100;
return result;
}
}
}
| 29.985612 | 78 | 0.583973 | [
"MIT"
] | kroll-software/KS.Foundation | Extensions/LongExtensions.cs | 4,170 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace CalcSum
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.777778 | 43 | 0.66568 | [
"MIT"
] | DarshanKumarSivabalanS/PROG8560ContinuousIntegration | CalcSum/CalcSum/App.xaml.cs | 340 | C# |
/* Copyright 2010-2014 MongoDB 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 MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using Xunit;
namespace MongoDB.Bson.Tests.Serialization.Conventions
{
public class IgnoreIfDefaultConventionsTests
{
[Theory]
[InlineData(true)]
[InlineData(false)]
public void TestApply(bool value)
{
var subject = new IgnoreIfDefaultConvention(value);
var classMap = new BsonClassMap<TestClass>();
var memberMap = classMap.MapMember(x => x.Id);
subject.Apply(memberMap);
Assert.Equal(value, memberMap.IgnoreIfDefault);
}
private class TestClass
{
public ObjectId Id { get; set; }
}
}
} | 30.204545 | 74 | 0.682468 | [
"Apache-2.0"
] | KermitCoder/mongo-csharp-driver | tests/MongoDB.Bson.Tests/Serialization/Conventions/IgnoreIfDefaultConventionsTests.cs | 1,331 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SFA.DAS.Location.Domain.Entities;
using SFA.DAS.Location.Domain.Interfaces;
namespace SFA.DAS.Location.Data.Repository
{
public class LocationImportRepository : ILocationImportRepository
{
private readonly ILocationDataContext _dataContext;
public LocationImportRepository (ILocationDataContext dataContext)
{
_dataContext = dataContext;
}
public void DeleteAll()
{
_dataContext.LocationImports.RemoveRange(_dataContext.LocationImports);
_dataContext.SaveChanges();
}
public async Task InsertMany(IEnumerable<LocationImport> items)
{
await _dataContext.LocationImports.AddRangeAsync(items);
_dataContext.SaveChanges();
}
public async Task<IEnumerable<LocationImport>> GetAll()
{
var results = await _dataContext.LocationImports.ToListAsync();
return results;
}
}
} | 29.108108 | 83 | 0.677809 | [
"MIT"
] | SkillsFundingAgency/das-location-api | src/SFA.DAS.Location.Data/Repository/LocationImportRepository.cs | 1,077 | C# |
/*
* Copyright 2006-2016 zorba.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
using System.IO;
using org.zorbaxquery.api;
namespace ZorbaApplication
{
class Program
{
static string test(string query, string xml, string doc) {
InMemoryStore store = InMemoryStore.getInstance();
Zorba zorba = Zorba.getInstance(store);
XmlDataManager dataManager = zorba.getXmlDataManager();
Iterator docIter = dataManager.parseXML(xml);
docIter.open();
Item idoc = new Item();
docIter.next(idoc);
docIter.close();
docIter.Dispose();
DocumentManager docManager = dataManager.getDocumentManager();
docManager.put(doc, idoc);
XQuery xquery = zorba.compileQuery(query);
string result = xquery.execute();
xquery.destroy();
xquery.Dispose();
zorba.shutdown();
InMemoryStore.shutdown(store);
return result;
}
static string readFile(string file) {
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (StreamReader sr = File.OpenText(file)) {
string line = "";
while ( (line = sr.ReadLine()) != null) {
sb.AppendLine(line);
}
}
return sb.ToString();
}
static bool compareStrings(string a, string b) {
string[] aMult = a.Split('\n');
string[] bMult = b.Split('\n');
if (aMult.Length > bMult.Length) {
return false;
}
int i = 0;
foreach (string line in aMult) {
if (line.Equals(bMult[i++])) {
return false;
}
}
return true;
}
static void Main(string[] args)
{
System.Console.WriteLine("Running: XQuery execute - parsing XML");
string xml = readFile("books.xml");
string doc = "my_fake_books.xml";
string query = "doc('my_fake_books.xml')";
string testResult=readFile("test07.result");;
System.Console.WriteLine("XML: " + xml);
System.Console.WriteLine("Query: " + query);
string result;
try {
result = test(query, xml, doc);
} catch(Exception e) {
System.Console.WriteLine("Failed");
Console.WriteLine("{0} Exception caught.", e);
return;
}
System.Console.WriteLine("Expecting: " + testResult);
System.Console.WriteLine("Result: " + result);
if (compareStrings(result,testResult)) {
System.Console.WriteLine("Success");
} else {
System.Console.WriteLine("Failed");
}
}
}
}
| 31.963636 | 78 | 0.544084 | [
"Apache-2.0"
] | markun/zorba | swig/csharp/tests/test07.cs | 3,516 | C# |
using System.Collections.Generic;
using System.Linq;
namespace Models
{
public class UnitMemberResponse : Entity
{
/// The role of the person in this membership as part of the unit.
public Role Role { get; set; }
/// The permissions of the person in this membership as part of the unit. Defaults to 'viewer'.
public UnitPermissions Permissions { get; set; }
/// The ID of the person class. This can be null if the position is vacant.
public int? PersonId { get; set; }
/// The title/position of this membership.
public string Title { get; set; }
/// The percentage of time allocated to this position by this person (in case of split appointments).
public int Percentage { get; set; }
/// Notes about this person (for admins/reporting eyes only.)
public string Notes { get; set; }
/// The netid of the person related to this membership.
public string Netid { get => this.Person?.Netid; }
/// The person related to this membership.
public Person Person { get; set; }
/// The ID of the unit class.
public int UnitId { get; set; }
/// The unit related to this membership.
public UnitResponse Unit { get; set; }
/// The tools that can be used by the person in this position as part of this unit.
public List<MemberToolResponse> MemberTools { get; set; }
}
} | 46.967742 | 109 | 0.629808 | [
"BSD-3-Clause"
] | indiana-university/itpeople-functions-v2 | src/Models/DTO/UnitMemberResponse.cs | 1,456 | 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.BotService.Models.Api20180712
{
using static Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Extensions;
/// <summary>The parameters to provide for the Kik channel.</summary>
public partial class KikChannelProperties
{
/// <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.BotService.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json serialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.BotService.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.BotService.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <paramref name= "returnNow" />
/// output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <paramref name="returnNow" /> output
/// parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.IKikChannelProperties.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.IKikChannelProperties.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.BotService.Models.Api20180712.IKikChannelProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonObject json ? new KikChannelProperties(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonObject into a new instance of <see cref="KikChannelProperties" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonObject instance to deserialize from.</param>
internal KikChannelProperties(Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_userName = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonString>("userName"), out var __jsonUserName) ? (string)__jsonUserName : (string)UserName;}
{_apiKey = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonString>("apiKey"), out var __jsonApiKey) ? (string)__jsonApiKey : (string)ApiKey;}
{_isValidated = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonBoolean>("isValidated"), out var __jsonIsValidated) ? (bool?)__jsonIsValidated : IsValidated;}
{_isEnabled = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonBoolean>("isEnabled"), out var __jsonIsEnabled) ? (bool)__jsonIsEnabled : IsEnabled;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="KikChannelProperties" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.BotService.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.BotService.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="KikChannelProperties" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
AddIf( null != (((object)this._userName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonString(this._userName.ToString()) : null, "userName" ,container.Add );
AddIf( null != (((object)this._apiKey)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonString(this._apiKey.ToString()) : null, "apiKey" ,container.Add );
AddIf( null != this._isValidated ? (Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonBoolean((bool)this._isValidated) : null, "isValidated" ,container.Add );
AddIf( (Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.BotService.Runtime.Json.JsonBoolean(this._isEnabled), "isEnabled" ,container.Add );
AfterToJson(ref container);
return container;
}
}
} | 74.254386 | 276 | 0.696869 | [
"MIT"
] | imadan1996/azure-powershell | src/BotService/generated/api/Models/Api20180712/KikChannelProperties.json.cs | 8,352 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.ExcelApi
{
/// <summary>
/// Interface IWorkbookEvents
/// SupportByVersion Excel, 9,10,11,12,14,15,16
/// </summary>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
[EntityType(EntityType.IsInterface)]
public class IWorkbookEvents : COMObject
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(IWorkbookEvents);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public IWorkbookEvents(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public IWorkbookEvents(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IWorkbookEvents(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IWorkbookEvents(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IWorkbookEvents(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IWorkbookEvents(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IWorkbookEvents() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IWorkbookEvents(string progId) : base(progId)
{
}
#endregion
#region Properties
#endregion
#region Methods
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 Open()
{
return Factory.ExecuteInt32MethodGet(this, "Open");
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 Activate()
{
return Factory.ExecuteInt32MethodGet(this, "Activate");
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 Deactivate()
{
return Factory.ExecuteInt32MethodGet(this, "Deactivate");
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="cancel">bool cancel</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 BeforeClose(bool cancel)
{
return Factory.ExecuteInt32MethodGet(this, "BeforeClose", cancel);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="saveAsUI">bool saveAsUI</param>
/// <param name="cancel">bool cancel</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 BeforeSave(bool saveAsUI, bool cancel)
{
return Factory.ExecuteInt32MethodGet(this, "BeforeSave", saveAsUI, cancel);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="cancel">bool cancel</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 BeforePrint(bool cancel)
{
return Factory.ExecuteInt32MethodGet(this, "BeforePrint", cancel);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 NewSheet(object sh)
{
return Factory.ExecuteInt32MethodGet(this, "NewSheet", sh);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 AddinInstall()
{
return Factory.ExecuteInt32MethodGet(this, "AddinInstall");
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 AddinUninstall()
{
return Factory.ExecuteInt32MethodGet(this, "AddinUninstall");
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="wn">NetOffice.ExcelApi.Window wn</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 WindowResize(NetOffice.ExcelApi.Window wn)
{
return Factory.ExecuteInt32MethodGet(this, "WindowResize", wn);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="wn">NetOffice.ExcelApi.Window wn</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 WindowActivate(NetOffice.ExcelApi.Window wn)
{
return Factory.ExecuteInt32MethodGet(this, "WindowActivate", wn);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="wn">NetOffice.ExcelApi.Window wn</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 WindowDeactivate(NetOffice.ExcelApi.Window wn)
{
return Factory.ExecuteInt32MethodGet(this, "WindowDeactivate", wn);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
/// <param name="target">NetOffice.ExcelApi.Range target</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 SheetSelectionChange(object sh, NetOffice.ExcelApi.Range target)
{
return Factory.ExecuteInt32MethodGet(this, "SheetSelectionChange", sh, target);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
/// <param name="target">NetOffice.ExcelApi.Range target</param>
/// <param name="cancel">bool cancel</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 SheetBeforeDoubleClick(object sh, NetOffice.ExcelApi.Range target, bool cancel)
{
return Factory.ExecuteInt32MethodGet(this, "SheetBeforeDoubleClick", sh, target, cancel);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
/// <param name="target">NetOffice.ExcelApi.Range target</param>
/// <param name="cancel">bool cancel</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 SheetBeforeRightClick(object sh, NetOffice.ExcelApi.Range target, bool cancel)
{
return Factory.ExecuteInt32MethodGet(this, "SheetBeforeRightClick", sh, target, cancel);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 SheetActivate(object sh)
{
return Factory.ExecuteInt32MethodGet(this, "SheetActivate", sh);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 SheetDeactivate(object sh)
{
return Factory.ExecuteInt32MethodGet(this, "SheetDeactivate", sh);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 SheetCalculate(object sh)
{
return Factory.ExecuteInt32MethodGet(this, "SheetCalculate", sh);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
/// <param name="target">NetOffice.ExcelApi.Range target</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 SheetChange(object sh, NetOffice.ExcelApi.Range target)
{
return Factory.ExecuteInt32MethodGet(this, "SheetChange", sh, target);
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
/// <param name="target">NetOffice.ExcelApi.Hyperlink target</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public Int32 SheetFollowHyperlink(object sh, NetOffice.ExcelApi.Hyperlink target)
{
return Factory.ExecuteInt32MethodGet(this, "SheetFollowHyperlink", sh, target);
}
/// <summary>
/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
/// <param name="target">NetOffice.ExcelApi.PivotTable target</param>
[SupportByVersion("Excel", 10,11,12,14,15,16)]
public Int32 SheetPivotTableUpdate(object sh, NetOffice.ExcelApi.PivotTable target)
{
return Factory.ExecuteInt32MethodGet(this, "SheetPivotTableUpdate", sh, target);
}
/// <summary>
/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="target">NetOffice.ExcelApi.PivotTable target</param>
[SupportByVersion("Excel", 10,11,12,14,15,16)]
public Int32 PivotTableCloseConnection(NetOffice.ExcelApi.PivotTable target)
{
return Factory.ExecuteInt32MethodGet(this, "PivotTableCloseConnection", target);
}
/// <summary>
/// SupportByVersion Excel 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="target">NetOffice.ExcelApi.PivotTable target</param>
[SupportByVersion("Excel", 10,11,12,14,15,16)]
public Int32 PivotTableOpenConnection(NetOffice.ExcelApi.PivotTable target)
{
return Factory.ExecuteInt32MethodGet(this, "PivotTableOpenConnection", target);
}
/// <summary>
/// SupportByVersion Excel 11, 12, 14, 15, 16
/// </summary>
/// <param name="syncEventType">NetOffice.OfficeApi.Enums.MsoSyncEventType syncEventType</param>
[SupportByVersion("Excel", 11,12,14,15,16)]
public Int32 Sync(NetOffice.OfficeApi.Enums.MsoSyncEventType syncEventType)
{
return Factory.ExecuteInt32MethodGet(this, "Sync", syncEventType);
}
/// <summary>
/// SupportByVersion Excel 11, 12, 14, 15, 16
/// </summary>
/// <param name="map">NetOffice.ExcelApi.XmlMap map</param>
/// <param name="url">string url</param>
/// <param name="isRefresh">bool isRefresh</param>
/// <param name="cancel">bool cancel</param>
[SupportByVersion("Excel", 11,12,14,15,16)]
public Int32 BeforeXmlImport(NetOffice.ExcelApi.XmlMap map, string url, bool isRefresh, bool cancel)
{
return Factory.ExecuteInt32MethodGet(this, "BeforeXmlImport", map, url, isRefresh, cancel);
}
/// <summary>
/// SupportByVersion Excel 11, 12, 14, 15, 16
/// </summary>
/// <param name="map">NetOffice.ExcelApi.XmlMap map</param>
/// <param name="isRefresh">bool isRefresh</param>
/// <param name="result">NetOffice.ExcelApi.Enums.XlXmlImportResult result</param>
[SupportByVersion("Excel", 11,12,14,15,16)]
public Int32 AfterXmlImport(NetOffice.ExcelApi.XmlMap map, bool isRefresh, NetOffice.ExcelApi.Enums.XlXmlImportResult result)
{
return Factory.ExecuteInt32MethodGet(this, "AfterXmlImport", map, isRefresh, result);
}
/// <summary>
/// SupportByVersion Excel 11, 12, 14, 15, 16
/// </summary>
/// <param name="map">NetOffice.ExcelApi.XmlMap map</param>
/// <param name="url">string url</param>
/// <param name="cancel">bool cancel</param>
[SupportByVersion("Excel", 11,12,14,15,16)]
public Int32 BeforeXmlExport(NetOffice.ExcelApi.XmlMap map, string url, bool cancel)
{
return Factory.ExecuteInt32MethodGet(this, "BeforeXmlExport", map, url, cancel);
}
/// <summary>
/// SupportByVersion Excel 11, 12, 14, 15, 16
/// </summary>
/// <param name="map">NetOffice.ExcelApi.XmlMap map</param>
/// <param name="url">string url</param>
/// <param name="result">NetOffice.ExcelApi.Enums.XlXmlExportResult result</param>
[SupportByVersion("Excel", 11,12,14,15,16)]
public Int32 AfterXmlExport(NetOffice.ExcelApi.XmlMap map, string url, NetOffice.ExcelApi.Enums.XlXmlExportResult result)
{
return Factory.ExecuteInt32MethodGet(this, "AfterXmlExport", map, url, result);
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <param name="description">string description</param>
/// <param name="sheet">string sheet</param>
/// <param name="success">bool success</param>
[SupportByVersion("Excel", 12,14,15,16)]
public Int32 RowsetComplete(string description, string sheet, bool success)
{
return Factory.ExecuteInt32MethodGet(this, "RowsetComplete", description, sheet, success);
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
/// <param name="targetPivotTable">NetOffice.ExcelApi.PivotTable targetPivotTable</param>
/// <param name="targetRange">NetOffice.ExcelApi.Range targetRange</param>
[SupportByVersion("Excel", 14,15,16)]
public Int32 SheetPivotTableAfterValueChange(object sh, NetOffice.ExcelApi.PivotTable targetPivotTable, NetOffice.ExcelApi.Range targetRange)
{
return Factory.ExecuteInt32MethodGet(this, "SheetPivotTableAfterValueChange", sh, targetPivotTable, targetRange);
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
/// <param name="targetPivotTable">NetOffice.ExcelApi.PivotTable targetPivotTable</param>
/// <param name="valueChangeStart">Int32 valueChangeStart</param>
/// <param name="valueChangeEnd">Int32 valueChangeEnd</param>
/// <param name="cancel">bool cancel</param>
[SupportByVersion("Excel", 14,15,16)]
public Int32 SheetPivotTableBeforeAllocateChanges(object sh, NetOffice.ExcelApi.PivotTable targetPivotTable, Int32 valueChangeStart, Int32 valueChangeEnd, bool cancel)
{
return Factory.ExecuteInt32MethodGet(this, "SheetPivotTableBeforeAllocateChanges", new object[]{ sh, targetPivotTable, valueChangeStart, valueChangeEnd, cancel });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
/// <param name="targetPivotTable">NetOffice.ExcelApi.PivotTable targetPivotTable</param>
/// <param name="valueChangeStart">Int32 valueChangeStart</param>
/// <param name="valueChangeEnd">Int32 valueChangeEnd</param>
/// <param name="cancel">bool cancel</param>
[SupportByVersion("Excel", 14,15,16)]
public Int32 SheetPivotTableBeforeCommitChanges(object sh, NetOffice.ExcelApi.PivotTable targetPivotTable, Int32 valueChangeStart, Int32 valueChangeEnd, bool cancel)
{
return Factory.ExecuteInt32MethodGet(this, "SheetPivotTableBeforeCommitChanges", new object[]{ sh, targetPivotTable, valueChangeStart, valueChangeEnd, cancel });
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
/// <param name="targetPivotTable">NetOffice.ExcelApi.PivotTable targetPivotTable</param>
/// <param name="valueChangeStart">Int32 valueChangeStart</param>
/// <param name="valueChangeEnd">Int32 valueChangeEnd</param>
[SupportByVersion("Excel", 14,15,16)]
public Int32 SheetPivotTableBeforeDiscardChanges(object sh, NetOffice.ExcelApi.PivotTable targetPivotTable, Int32 valueChangeStart, Int32 valueChangeEnd)
{
return Factory.ExecuteInt32MethodGet(this, "SheetPivotTableBeforeDiscardChanges", sh, targetPivotTable, valueChangeStart, valueChangeEnd);
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="sh">object sh</param>
/// <param name="target">NetOffice.ExcelApi.PivotTable target</param>
[SupportByVersion("Excel", 14,15,16)]
public Int32 SheetPivotTableChangeSync(object sh, NetOffice.ExcelApi.PivotTable target)
{
return Factory.ExecuteInt32MethodGet(this, "SheetPivotTableChangeSync", sh, target);
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="success">bool success</param>
[SupportByVersion("Excel", 14,15,16)]
public Int32 AfterSave(bool success)
{
return Factory.ExecuteInt32MethodGet(this, "AfterSave", success);
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="ch">NetOffice.ExcelApi.Chart ch</param>
[SupportByVersion("Excel", 14,15,16)]
public Int32 NewChart(NetOffice.ExcelApi.Chart ch)
{
return Factory.ExecuteInt32MethodGet(this, "NewChart", ch);
}
/// <summary>
/// SupportByVersion Excel 15,16
/// </summary>
/// <param name="sh">object sh</param>
[SupportByVersion("Excel", 15, 16)]
public Int32 SheetLensGalleryRenderComplete(object sh)
{
return Factory.ExecuteInt32MethodGet(this, "SheetLensGalleryRenderComplete", sh);
}
/// <summary>
/// SupportByVersion Excel 15,16
/// </summary>
/// <param name="sh">object sh</param>
/// <param name="target">NetOffice.ExcelApi.TableObject target</param>
[SupportByVersion("Excel", 15, 16)]
public Int32 SheetTableUpdate(object sh, NetOffice.ExcelApi.TableObject target)
{
return Factory.ExecuteInt32MethodGet(this, "SheetTableUpdate", sh, target);
}
/// <summary>
/// SupportByVersion Excel 15,16
/// </summary>
/// <param name="changes">NetOffice.ExcelApi.ModelChanges changes</param>
[SupportByVersion("Excel", 15, 16)]
public Int32 ModelChange(NetOffice.ExcelApi.ModelChanges changes)
{
return Factory.ExecuteInt32MethodGet(this, "ModelChange", changes);
}
/// <summary>
/// SupportByVersion Excel 15,16
/// </summary>
/// <param name="sh">object sh</param>
[SupportByVersion("Excel", 15, 16)]
public Int32 SheetBeforeDelete(object sh)
{
return Factory.ExecuteInt32MethodGet(this, "SheetBeforeDelete", sh);
}
#endregion
#pragma warning restore
}
}
| 35.744991 | 170 | 0.691602 | [
"MIT"
] | DominikPalo/NetOffice | Source/Excel/Interfaces/IWorkbookEvents.cs | 19,626 | C# |
using Dalamud.Game.Text.SeStringHandling;
namespace PlayerTags.GameInterface.ContextMenus
{
/// <summary>
/// An item in a context menu that with a specific game action.
/// </summary>
public class GameContextMenuItem : ContextMenuItem
{
/// <summary>
/// The game action that will be handled when the item is selected.
/// </summary>
public byte SelectedAction { get; }
/// <summary>
/// Initializes a new instance of the <see cref="GameContextMenuItem"/> class.
/// </summary>
/// <param name="name">The name of the item.</param>
/// <param name="selectedAction">The game action that will be handled when the item is selected.</param>
public GameContextMenuItem(SeString name, byte selectedAction)
: base(name)
{
SelectedAction = selectedAction;
}
public override int GetHashCode()
{
unchecked
{
int hash = base.GetHashCode();
hash = hash * 23 + SelectedAction;
return hash;
}
}
}
} | 31.666667 | 112 | 0.568421 | [
"MIT"
] | r00telement/PlayerTags | PlayerTags/GameInterface/ContextMenus/GameContextMenuItem.cs | 1,142 | 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;
using System.Collections.Generic;
using System.Text;
using Internal.ReadyToRunConstants;
namespace ILCompiler.Reflection.ReadyToRun
{
/// <summary>
/// based on <a href="https://github.com/dotnet/coreclr/blob/master/src/inc/readytorun.h">src/inc/readytorun.h</a> READYTORUN_HEADER
/// </summary>
public class ReadyToRunHeader
{
/// <summary>
/// The expected signature of a ReadyToRun header
/// </summary>
public const uint READYTORUN_SIGNATURE = 0x00525452; // 'RTR'
/// <summary>
/// RVA to the beginning of the ReadyToRun header
/// </summary>
public int RelativeVirtualAddress { get; set; }
/// <summary>
/// Size of the ReadyToRun header
/// </summary>
public int Size { get; set; }
/// <summary>
/// Signature of the header in string and hex formats
/// </summary>
public string SignatureString { get; set; }
public uint Signature { get; set; }
/// <summary>
/// The ReadyToRun version
/// </summary>
public ushort MajorVersion { get; set; }
public ushort MinorVersion { get; set; }
/// <summary>
/// Flags in the header
/// eg. PLATFORM_NEUTRAL_SOURCE, SKIP_TYPE_VALIDATION
/// </summary>
public uint Flags { get; set; }
/// <summary>
/// The ReadyToRun section RVAs and sizes
/// </summary>
public IDictionary<ReadyToRunSection.SectionType, ReadyToRunSection> Sections { get; }
public ReadyToRunHeader() { }
/// <summary>
/// Initializes the fields of the R2RHeader
/// </summary>
/// <param name="image">PE image</param>
/// <param name="rva">Relative virtual address of the ReadyToRun header</param>
/// <param name="curOffset">Index in the image byte array to the start of the ReadyToRun header</param>
/// <exception cref="BadImageFormatException">The signature must be 0x00525452</exception>
public ReadyToRunHeader(byte[] image, int rva, int curOffset)
{
RelativeVirtualAddress = rva;
int startOffset = curOffset;
byte[] signature = new byte[sizeof(uint) - 1]; // -1 removes the null character at the end of the cstring
Array.Copy(image, curOffset, signature, 0, sizeof(uint) - 1);
SignatureString = Encoding.UTF8.GetString(signature);
Signature = NativeReader.ReadUInt32(image, ref curOffset);
if (Signature != READYTORUN_SIGNATURE)
{
throw new System.BadImageFormatException("Incorrect R2R header signature: " + SignatureString);
}
MajorVersion = NativeReader.ReadUInt16(image, ref curOffset);
MinorVersion = NativeReader.ReadUInt16(image, ref curOffset);
Flags = NativeReader.ReadUInt32(image, ref curOffset);
int nSections = NativeReader.ReadInt32(image, ref curOffset);
Sections = new Dictionary<ReadyToRunSection.SectionType, ReadyToRunSection>();
for (int i = 0; i < nSections; i++)
{
int type = NativeReader.ReadInt32(image, ref curOffset);
var sectionType = (ReadyToRunSection.SectionType)type;
if (!Enum.IsDefined(typeof(ReadyToRunSection.SectionType), type))
{
// TODO (refactoring) - what should we do?
// R2RDump.WriteWarning("Invalid ReadyToRun section type");
}
Sections[sectionType] = new ReadyToRunSection(sectionType,
NativeReader.ReadInt32(image, ref curOffset),
NativeReader.ReadInt32(image, ref curOffset));
}
Size = curOffset - startOffset;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine($"Signature: 0x{Signature:X8} ({SignatureString})");
sb.AppendLine($"RelativeVirtualAddress: 0x{RelativeVirtualAddress:X8}");
if (Signature == READYTORUN_SIGNATURE)
{
sb.AppendLine($"Size: {Size} bytes");
sb.AppendLine($"MajorVersion: 0x{MajorVersion:X4}");
sb.AppendLine($"MinorVersion: 0x{MinorVersion:X4}");
sb.AppendLine($"Flags: 0x{Flags:X8}");
foreach (ReadyToRunFlags flag in Enum.GetValues(typeof(ReadyToRunFlags)))
{
if ((Flags & (uint)flag) != 0)
{
sb.AppendLine($" - {Enum.GetName(typeof(ReadyToRunFlags), flag)}");
}
}
}
return sb.ToString();
}
}
}
| 40.304 | 136 | 0.58416 | [
"MIT"
] | Davilink/runtime | src/coreclr/src/tools/crossgen2/ILCompiler.Reflection.ReadyToRun/ReadyToRunHeader.cs | 5,040 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Model\EntityType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type Android General Device Configuration.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class AndroidGeneralDeviceConfiguration : DeviceConfiguration
{
/// <summary>
/// Gets or sets apps block clipboard sharing.
/// Indicates whether or not to block clipboard sharing to copy and paste between applications.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "appsBlockClipboardSharing", Required = Newtonsoft.Json.Required.Default)]
public bool? AppsBlockClipboardSharing { get; set; }
/// <summary>
/// Gets or sets apps block copy paste.
/// Indicates whether or not to block copy and paste within applications.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "appsBlockCopyPaste", Required = Newtonsoft.Json.Required.Default)]
public bool? AppsBlockCopyPaste { get; set; }
/// <summary>
/// Gets or sets apps block you tube.
/// Indicates whether or not to block the YouTube app.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "appsBlockYouTube", Required = Newtonsoft.Json.Required.Default)]
public bool? AppsBlockYouTube { get; set; }
/// <summary>
/// Gets or sets bluetooth blocked.
/// Indicates whether or not to block Bluetooth.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "bluetoothBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? BluetoothBlocked { get; set; }
/// <summary>
/// Gets or sets camera blocked.
/// Indicates whether or not to block the use of the camera.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "cameraBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? CameraBlocked { get; set; }
/// <summary>
/// Gets or sets cellular block data roaming.
/// Indicates whether or not to block data roaming.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "cellularBlockDataRoaming", Required = Newtonsoft.Json.Required.Default)]
public bool? CellularBlockDataRoaming { get; set; }
/// <summary>
/// Gets or sets cellular block messaging.
/// Indicates whether or not to block SMS/MMS messaging.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "cellularBlockMessaging", Required = Newtonsoft.Json.Required.Default)]
public bool? CellularBlockMessaging { get; set; }
/// <summary>
/// Gets or sets cellular block voice roaming.
/// Indicates whether or not to block voice roaming.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "cellularBlockVoiceRoaming", Required = Newtonsoft.Json.Required.Default)]
public bool? CellularBlockVoiceRoaming { get; set; }
/// <summary>
/// Gets or sets cellular block wi fi tethering.
/// Indicates whether or not to block syncing Wi-Fi tethering.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "cellularBlockWiFiTethering", Required = Newtonsoft.Json.Required.Default)]
public bool? CellularBlockWiFiTethering { get; set; }
/// <summary>
/// Gets or sets compliant apps list.
/// List of apps in the compliance (either allow list or block list, controlled by CompliantAppListType). This collection can contain a maximum of 10000 elements.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "compliantAppsList", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<AppListItem> CompliantAppsList { get; set; }
/// <summary>
/// Gets or sets compliant app list type.
/// Type of list that is in the CompliantAppsList. Possible values are: none, appsInListCompliant, appsNotInListCompliant.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "compliantAppListType", Required = Newtonsoft.Json.Required.Default)]
public AppListType? CompliantAppListType { get; set; }
/// <summary>
/// Gets or sets diagnostic data block submission.
/// Indicates whether or not to block diagnostic data submission.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "diagnosticDataBlockSubmission", Required = Newtonsoft.Json.Required.Default)]
public bool? DiagnosticDataBlockSubmission { get; set; }
/// <summary>
/// Gets or sets location services blocked.
/// Indicates whether or not to block location services.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "locationServicesBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? LocationServicesBlocked { get; set; }
/// <summary>
/// Gets or sets google account block auto sync.
/// Indicates whether or not to block Google account auto sync.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "googleAccountBlockAutoSync", Required = Newtonsoft.Json.Required.Default)]
public bool? GoogleAccountBlockAutoSync { get; set; }
/// <summary>
/// Gets or sets google play store blocked.
/// Indicates whether or not to block the Google Play store.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "googlePlayStoreBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? GooglePlayStoreBlocked { get; set; }
/// <summary>
/// Gets or sets kiosk mode block sleep button.
/// Indicates whether or not to block the screen sleep button while in Kiosk Mode.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "kioskModeBlockSleepButton", Required = Newtonsoft.Json.Required.Default)]
public bool? KioskModeBlockSleepButton { get; set; }
/// <summary>
/// Gets or sets kiosk mode block volume buttons.
/// Indicates whether or not to block the volume buttons while in Kiosk Mode.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "kioskModeBlockVolumeButtons", Required = Newtonsoft.Json.Required.Default)]
public bool? KioskModeBlockVolumeButtons { get; set; }
/// <summary>
/// Gets or sets kiosk mode apps.
/// A list of apps that will be allowed to run when the device is in Kiosk Mode. This collection can contain a maximum of 500 elements.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "kioskModeApps", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<AppListItem> KioskModeApps { get; set; }
/// <summary>
/// Gets or sets nfc blocked.
/// Indicates whether or not to block Near-Field Communication.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "nfcBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? NfcBlocked { get; set; }
/// <summary>
/// Gets or sets password block fingerprint unlock.
/// Indicates whether or not to block fingerprint unlock.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "passwordBlockFingerprintUnlock", Required = Newtonsoft.Json.Required.Default)]
public bool? PasswordBlockFingerprintUnlock { get; set; }
/// <summary>
/// Gets or sets password block trust agents.
/// Indicates whether or not to block Smart Lock and other trust agents.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "passwordBlockTrustAgents", Required = Newtonsoft.Json.Required.Default)]
public bool? PasswordBlockTrustAgents { get; set; }
/// <summary>
/// Gets or sets password expiration days.
/// Number of days before the password expires. Valid values 1 to 365
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "passwordExpirationDays", Required = Newtonsoft.Json.Required.Default)]
public Int32? PasswordExpirationDays { get; set; }
/// <summary>
/// Gets or sets password minimum length.
/// Minimum length of passwords. Valid values 4 to 16
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "passwordMinimumLength", Required = Newtonsoft.Json.Required.Default)]
public Int32? PasswordMinimumLength { get; set; }
/// <summary>
/// Gets or sets password minutes of inactivity before screen timeout.
/// Minutes of inactivity before the screen times out.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "passwordMinutesOfInactivityBeforeScreenTimeout", Required = Newtonsoft.Json.Required.Default)]
public Int32? PasswordMinutesOfInactivityBeforeScreenTimeout { get; set; }
/// <summary>
/// Gets or sets password previous password block count.
/// Number of previous passwords to block. Valid values 0 to 24
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "passwordPreviousPasswordBlockCount", Required = Newtonsoft.Json.Required.Default)]
public Int32? PasswordPreviousPasswordBlockCount { get; set; }
/// <summary>
/// Gets or sets password sign in failure count before factory reset.
/// Number of sign in failures allowed before factory reset. Valid values 1 to 16
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "passwordSignInFailureCountBeforeFactoryReset", Required = Newtonsoft.Json.Required.Default)]
public Int32? PasswordSignInFailureCountBeforeFactoryReset { get; set; }
/// <summary>
/// Gets or sets password required type.
/// Type of password that is required. Possible values are: deviceDefault, alphabetic, alphanumeric, alphanumericWithSymbols, lowSecurityBiometric, numeric, numericComplex, any.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "passwordRequiredType", Required = Newtonsoft.Json.Required.Default)]
public AndroidRequiredPasswordType? PasswordRequiredType { get; set; }
/// <summary>
/// Gets or sets password required.
/// Indicates whether or not to require a password.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "passwordRequired", Required = Newtonsoft.Json.Required.Default)]
public bool? PasswordRequired { get; set; }
/// <summary>
/// Gets or sets power off blocked.
/// Indicates whether or not to block powering off the device.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "powerOffBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? PowerOffBlocked { get; set; }
/// <summary>
/// Gets or sets factory reset blocked.
/// Indicates whether or not to block user performing a factory reset.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "factoryResetBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? FactoryResetBlocked { get; set; }
/// <summary>
/// Gets or sets screen capture blocked.
/// Indicates whether or not to block screenshots.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "screenCaptureBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? ScreenCaptureBlocked { get; set; }
/// <summary>
/// Gets or sets device sharing allowed.
/// Indicates whether or not to allow device sharing mode.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "deviceSharingAllowed", Required = Newtonsoft.Json.Required.Default)]
public bool? DeviceSharingAllowed { get; set; }
/// <summary>
/// Gets or sets storage block google backup.
/// Indicates whether or not to block Google Backup.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "storageBlockGoogleBackup", Required = Newtonsoft.Json.Required.Default)]
public bool? StorageBlockGoogleBackup { get; set; }
/// <summary>
/// Gets or sets storage block removable storage.
/// Indicates whether or not to block removable storage usage.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "storageBlockRemovableStorage", Required = Newtonsoft.Json.Required.Default)]
public bool? StorageBlockRemovableStorage { get; set; }
/// <summary>
/// Gets or sets storage require device encryption.
/// Indicates whether or not to require device encryption.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "storageRequireDeviceEncryption", Required = Newtonsoft.Json.Required.Default)]
public bool? StorageRequireDeviceEncryption { get; set; }
/// <summary>
/// Gets or sets storage require removable storage encryption.
/// Indicates whether or not to require removable storage encryption.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "storageRequireRemovableStorageEncryption", Required = Newtonsoft.Json.Required.Default)]
public bool? StorageRequireRemovableStorageEncryption { get; set; }
/// <summary>
/// Gets or sets voice assistant blocked.
/// Indicates whether or not to block the use of the Voice Assistant.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "voiceAssistantBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? VoiceAssistantBlocked { get; set; }
/// <summary>
/// Gets or sets voice dialing blocked.
/// Indicates whether or not to block voice dialing.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "voiceDialingBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? VoiceDialingBlocked { get; set; }
/// <summary>
/// Gets or sets web browser block popups.
/// Indicates whether or not to block popups within the web browser.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "webBrowserBlockPopups", Required = Newtonsoft.Json.Required.Default)]
public bool? WebBrowserBlockPopups { get; set; }
/// <summary>
/// Gets or sets web browser block autofill.
/// Indicates whether or not to block the web browser's auto fill feature.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "webBrowserBlockAutofill", Required = Newtonsoft.Json.Required.Default)]
public bool? WebBrowserBlockAutofill { get; set; }
/// <summary>
/// Gets or sets web browser block java script.
/// Indicates whether or not to block JavaScript within the web browser.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "webBrowserBlockJavaScript", Required = Newtonsoft.Json.Required.Default)]
public bool? WebBrowserBlockJavaScript { get; set; }
/// <summary>
/// Gets or sets web browser blocked.
/// Indicates whether or not to block the web browser.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "webBrowserBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? WebBrowserBlocked { get; set; }
/// <summary>
/// Gets or sets web browser cookie settings.
/// Cookie settings within the web browser. Possible values are: browserDefault, blockAlways, allowCurrentWebSite, allowFromWebsitesVisited, allowAlways.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "webBrowserCookieSettings", Required = Newtonsoft.Json.Required.Default)]
public WebBrowserCookieSettings? WebBrowserCookieSettings { get; set; }
/// <summary>
/// Gets or sets wi fi blocked.
/// Indicates whether or not to block syncing Wi-Fi.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "wiFiBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? WiFiBlocked { get; set; }
/// <summary>
/// Gets or sets apps install allow list.
/// List of apps which can be installed on the KNOX device. This collection can contain a maximum of 500 elements.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "appsInstallAllowList", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<AppListItem> AppsInstallAllowList { get; set; }
/// <summary>
/// Gets or sets apps launch block list.
/// List of apps which are blocked from being launched on the KNOX device. This collection can contain a maximum of 500 elements.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "appsLaunchBlockList", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<AppListItem> AppsLaunchBlockList { get; set; }
/// <summary>
/// Gets or sets apps hide list.
/// List of apps to be hidden on the KNOX device. This collection can contain a maximum of 500 elements.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "appsHideList", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<AppListItem> AppsHideList { get; set; }
/// <summary>
/// Gets or sets security require verify apps.
/// Require the Android Verify apps feature is turned on.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "securityRequireVerifyApps", Required = Newtonsoft.Json.Required.Default)]
public bool? SecurityRequireVerifyApps { get; set; }
}
}
| 55.752747 | 185 | 0.667242 | [
"MIT"
] | peombwa/msgraph-sdk-dotnet | src/Microsoft.Graph/Models/Generated/AndroidGeneralDeviceConfiguration.cs | 20,294 | C# |
/**
Copyright 2019 Centrify Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Net;
namespace CentrifyCLI
{
/// <summary>The Centrify-specific logic and knowledge.</summary>
class Runner
{
// Constants
private const string FAILED = "FAILED: ";
public static readonly TimeSpan SWAGGER_REFRESH = TimeSpan.FromDays(15);
/// <summary>Result codes for REST calls</summary>
public enum ResultCode { Success, Redirected, Unauthorized, NotFound, Exception, Failed, Timeout};
/// <summary>Centrify service URL.</summary>
private string m_url ="";
/// <summary>List of APIs for the drop-down/easy reference.<para/>
/// These each have a structure of Group/Api/Path/Reference/Sample.</summary>
private JObject m_apiCalls = new JObject();
/// <summary>Use the one restUpdater for the entire short session</summary>
private RestUpdater m_restUpdater = new RestUpdater();
/// <summary>Record that can be stored as a server profile.</summary>
[Serializable]
public class ServerProfile
{
/// <summary>What to call this connection.</summary>
public string NickName;
/// <summary>Tenant URL</summary>
public string URL;
/// <summary>OAuth application id</summary>
public string OAuthAppId;
/// <summary>User name for authentication</summary>
public string UserName;
/// <summary>User password for authentication</summary>
public string Password;
/// <summary>OAuth token</summary>
[JsonIgnore]
public string OAuthToken;
/// <summary>Machine Scope to use when using DMC</summary>
public string MachineScope;
public override string ToString()
{
string name = (String.IsNullOrEmpty(NickName) ? "-default-" : NickName);
return $"Profile {name}: URL: '{URL}' AppId: '{OAuthAppId}' User: '{UserName}' MachineScope: '{MachineScope}'";
}
}
/// <summary>Available server profiles, by name</summary>
public Dictionary<string, ServerProfile> ServerList { get; private set; } = new Dictionary<string, ServerProfile>();
/// <summary>Parse contents from a REST response into JObject, handling errors.</summary>
private JObject ParseContentsToJObject(string contents)
{
if (string.IsNullOrWhiteSpace(contents))
{
return null;
}
JObject result = null;
try
{
result = JObject.Parse(contents);
}
catch (Exception e)
{
result = new JObject()
{
{ "success", false },
{ "contents", contents },
{ "exception", e.Message },
};
}
return result;
}
// Roughly: http://stackoverflow.com/questions/3404421/password-masking-console-application
public static string ReadMaskedPassword(bool prompt)
{
ConsoleKeyInfo key;
string password = null;
if (prompt) Console.Write("Password: ");
do
{
// Read a character without echoing it
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
password += key.KeyChar;
Console.Write("*");
}
else
{
if (key.Key == ConsoleKey.Backspace && password != null && password.Length > 0)
{
password = password.Substring(0, password.Length - 1);
Console.Write("\b \b");
}
}
} while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
return password;
}
/// <summary>Authenticate the user via username/password/etc.<para/>
/// OAuth token is the preferred method of authenication; this exists for ease of use</summary>
/// <param name="config">Contains config info, including profile to use</param>
/// <param name="timeout">Timeout is milliserconds for REST calls</param>
/// <returns>Tuple of success or failure reason and message or results.</returns>
public Tuple<ResultCode, string> Authenticate(CentrifyCliConfig config, int timeout)
{
ServerProfile profile = config.Profile;
try
{
if (string.IsNullOrWhiteSpace(profile.UserName))
{
return new Tuple<ResultCode, string>(ResultCode.NotFound, $"No user in config to authenticate.");
}
InitializeClient(profile.URL);
// Do StartAuthentication
string endpoint = "/Security/StartAuthentication";
Dictionary<string, string> args = new Dictionary<string, string>()
{
{ "User", profile.UserName },
{ "Version", "1.0" }
};
var authTask = PlaceCall(endpoint, JsonConvert.SerializeObject(args));
if (!authTask.Wait(timeout))
{
return new Tuple<ResultCode, string>(ResultCode.Timeout, $"Request timed out ({endpoint}).");
}
Tuple<Runner.ResultCode, string> callResult = authTask.Result;
if (callResult.Item1 != ResultCode.Success)
{
return new Tuple<ResultCode, string>(ResultCode.Failed, MakeFailResult(callResult.Item2, $"Authentication request failed ({endpoint}): {callResult.Item1}"));
}
// Remember session and tenant
JObject resultSet = ParseContentsToJObject(callResult.Item2);
if (!TryGetJObjectValue(resultSet, "Result", out JObject results))
{
throw new ArgumentException($"Authentication results have no 'result' property ({endpoint}):\n{ResultToString(resultSet)}", "Result");
}
if (TryGetJObjectValue(results, "Redirect", out string redirect))
{
Ccli.ConditionalWrite($"Authentication is redirected, use the prefered URL: {redirect}", config.Silent);
return new Tuple<ResultCode, string>(ResultCode.Redirected, redirect);
}
if (!TryGetJObjectValue(results, "SessionId", out string sessionId))
{
throw new ArgumentException($"Authentication results are missing 'SessionId' ({endpoint}): {ResultToString(results)}", "SessionId");
}
if (!TryGetJObjectValue(results, "TenantId", out string tenantId))
{
throw new ArgumentException($"Authentication results are missing 'TenantId' ({endpoint}): {ResultToString(results)}", "TenantId");
}
if (!TryGetJObjectValue(results, "Challenges", out JToken challenges))
{
throw new ArgumentException($"Authentication results are missing 'Challenges' ({endpoint}): {ResultToString(results)}", "Challenges");
}
// If pw was supplied, and is one of the first mechs, use what was supplied automagically
int passwordMechIdx = -1;
if (profile.Password != null)
{
// Present the option(s) to the user
for (int mechIdx = 0; mechIdx < challenges[0]["Mechanisms"].Children().Count() && passwordMechIdx == -1; mechIdx++)
{
if (challenges[0]["Mechanisms"][mechIdx]["Name"].Value<string>() == "UP")
{
passwordMechIdx = mechIdx;
}
}
}
// Need to satisfy at least 1 challenge in each collection:
for (int x = 0; x < challenges.Children().Count(); x++)
{
int optionSelect = -1;
// If passwordMechIdx is set, we should auto-fill password first, do it
if (passwordMechIdx == -1)
{
// Present the option(s) to the user
for (int mechIdx = 0; mechIdx < challenges[x]["Mechanisms"].Children().Count(); mechIdx++)
{
Console.WriteLine("Option {0}: {1}", mechIdx, MechToDescription(challenges[x]["Mechanisms"][mechIdx]));
}
if (challenges[x]["Mechanisms"].Children().Count() == 1)
{
optionSelect = 0;
}
else
{
while (optionSelect < 0 || optionSelect > challenges[x]["Mechanisms"].Children().Count())
{
Console.Write("Select option and press enter: ");
string optEntered = Console.ReadLine();
int.TryParse(optEntered, out optionSelect);
}
}
}
else
{
optionSelect = passwordMechIdx;
passwordMechIdx = -1;
}
try
{
var newChallenges = AdvanceForMech(timeout, tenantId, sessionId, challenges[x]["Mechanisms"][optionSelect], profile);
if(newChallenges != null)
{
challenges = newChallenges;
x = -1;
}
}
catch (Exception ex)
{
return new Tuple<ResultCode, string>(ResultCode.Failed, ex.Message);
}
}
}
catch (Exception e)
{
Exception i = e;
string allMessages = "";
// De-dup; sometimes they double up.
while (i != null)
{
if (!allMessages.Contains(i.Message)) allMessages += i.Message + " " + Environment.NewLine;
i = i.InnerException;
}
return new Tuple<ResultCode, string>(ResultCode.Exception, allMessages);
}
m_url = profile.URL;
return new Tuple<ResultCode, string>(ResultCode.Success, "");
}
private dynamic AdvanceForMech(int timeout, string tenantId, string sessionId, dynamic mech, ServerProfile profile)
{
Dictionary<string, dynamic> advanceArgs = new Dictionary<string, dynamic>();
advanceArgs["TenantId"] = tenantId;
advanceArgs["SessionId"] = sessionId;
advanceArgs["MechanismId"] = mech["MechanismId"];
advanceArgs["PersistentLogin"] = false;
bool autoFillPassword = (mech["Name"] == "UP" && profile.Password != null);
// Write prompt (unless auto-filling)
if (!autoFillPassword)
{
Console.Write(MechToPrompt(mech));
}
// Read or poll for response. For StartTextOob we simplify and require user to enter the response, rather
// than simultaenously prompting and polling, though this can be done as well.
string answerType = mech["AnswerType"];
switch (answerType)
{
case "Text":
case "StartTextOob":
{
if (answerType == "StartTextOob")
{
// First we start oob, to get the mech activated
advanceArgs["Action"] = "StartOOB";
if(!PlaceCall("/security/advanceauthentication", JsonConvert.SerializeObject(advanceArgs)).Wait(timeout))
{
throw new ApplicationException("Request timed out (/security/advanceauthentication)");
}
}
// Now prompt for the value to submit and do so
string promptResponse = null;
if (autoFillPassword)
{
promptResponse = profile.Password;
}
else
{
promptResponse = ReadMaskedPassword(false);
}
advanceArgs["Answer"] = promptResponse;
advanceArgs["Action"] = "Answer";
var result = SimpleCall(timeout, "/security/advanceauthentication", advanceArgs);
if(result["Result"]["Summary"] == "NewPackage")//-V3080
{
return result["Result"]["Challenges"];
}
if (!(result["Result"]["Summary"] == "StartNextChallenge" ||
result["Result"]["Summary"] == "LoginSuccess"))
{
throw new ApplicationException(result["Message"]);
}
}
break;
case "StartOob":
// Pure out of band mech, simply poll until complete or fail
advanceArgs["Action"] = "StartOOB";
SimpleCall(timeout, "/security/advanceauthentication", advanceArgs);
// Poll
advanceArgs["Action"] = "Poll";
dynamic pollResult = null;
do
{
Console.Write(".");
pollResult = SimpleCall(timeout, "/security/advanceauthentication", advanceArgs);
System.Threading.Thread.Sleep(1000);
} while (pollResult["Result"]["Summary"] == "OobPending");//-V3080
// We are done polling, did it work ?
if (pollResult["Result"]["Summary"] == "NewPackage")
{
return pollResult["Result"]["Challenges"];
}
if (!(pollResult["Result"]["Summary"] == "StartNextChallenge" ||
pollResult["Result"]["Summary"] == "LoginSuccess"))
{
throw new ApplicationException(pollResult["Message"]);
}
break;
}
return null;
}
public const string OneTimePassCode = "OTP";
public const string OathPassCode = "OATH";
public const string PhoneFactor = "PF";
public const string Sms = "SMS";
public const string Email = "EMAIL";
public const string PasswordReset = "RESET";
public const string SecurityQuestion = "SQ";
private static string MechToDescription(dynamic mech)
{
string mechName = mech["Name"];
try
{
return mech["PromptSelectMech"];
}
catch { /* Doesn't support this property */ }
switch (mechName)
{
case "UP":
return "Password";
case "SMS":
return string.Format("SMS to number ending in {0}", mech["PartialDeviceAddress"]);
case "EMAIL":
return string.Format("Email to address ending with {0}", mech["PartialAddress"]);
case "PF":
return string.Format("Phone call to number ending with {0}", mech["PartialPhoneNumber"]);
case "OATH":
return string.Format("OATH compatible client");
case "SQ":
return string.Format("Security Question");
default:
return mechName;
}
}
private static string MechToPrompt(dynamic mech)
{
string mechName = mech["Name"];
try
{
string servicePrompt = mech["PromptMechChosen"];
if(!string.IsNullOrEmpty(servicePrompt))
{
if (!servicePrompt.EndsWith(":"))
{
return servicePrompt + ": ";
}
else
{
return servicePrompt + " ";
}
}
}
catch { /* Doesn't support this property */ }
switch (mechName)
{
case "UP":
return "Password: ";
case "SMS":
return string.Format("Enter the code sent via SMS to number ending in {0}: ", mech["PartialDeviceAddress"]);
case "EMAIL":
return string.Format("Please click or open the link sent to the email to address ending with {0}.", mech["PartialAddress"]);
case "PF":
return string.Format("Calling number ending with {0}, please follow the spoken prompt.", mech["PartialPhoneNumber"]);
case "OATH":
return string.Format("Enter your current OATH code: ");
case "SQ":
return string.Format("Enter the response to your secret question: ");
default:
return mechName;
}
}
/// <summary>Call the rest endpoint with the JSON.<para/>
/// Authentication has already set the URL.</summary>
/// <param name="endpoint">Path to REST call, starts with a slash.</param>
/// <param name="json">Json payload</param>
/// <returns>Task with the result code and payload of the REST call</returns>
public async Task<Tuple<ResultCode, string>> PlaceCall(string endpoint, string json)
{
RestUpdater.RESTCall restCall = new RestUpdater.RESTCall()
{
Endpoint = endpoint,
JsonTemplate = json
};
HttpResponseMessage response = null;
try
{
response = await m_restUpdater.NewRequestAsync(m_url, restCall);
}
catch (System.Threading.Tasks.TaskCanceledException)
{
return new Tuple<ResultCode, string>(ResultCode.Timeout, $"Request timed out or canceled ({endpoint}).");
}
HttpStatusCode statusCode = response.StatusCode;
string contents = await response.Content.ReadAsStringAsync();
switch (statusCode)
{
case HttpStatusCode.OK:
return new Tuple<ResultCode, string>(ResultCode.Success, contents);
case HttpStatusCode.Unauthorized:
return new Tuple<ResultCode, string>(ResultCode.Unauthorized, $"Access to {endpoint} not allowed.");
case HttpStatusCode.NotFound:
return new Tuple<ResultCode, string>(ResultCode.NotFound, $"Endpoint {endpoint} not found.");
default:
return new Tuple<ResultCode, string>(ResultCode.Failed, $"Unexpected response status from {endpoint}: {statusCode} - {contents}");
}
}
// Wraps PlaceCall to simplify calling pattern:
// Throws exception on API fail or timeout (see ex.Message)
// Returns Result object as simple Dictionary
public dynamic SimpleCall(int timeout, string endpoint, object args)
{
var call = PlaceCall(endpoint, JsonConvert.SerializeObject(args));
if (!call.Wait(timeout))
{
throw new ApplicationException($"Request timed out ({endpoint})");
}
var callResult = call.Result;
if (callResult.Item1 != ResultCode.Success)
{
throw new ApplicationException(MakeFailResult(callResult.Item2, $"API call failed ({endpoint}): {callResult.Item1}"));
}
return ParseContentsToJObject(callResult.Item2);
}
/// <summary>Returns the path to a user file.</summary>
/// <param name="fileName">filename to generate path for</param>
/// <returns>Platform appropriate path string from the environmental settings</returns>
public static string GetUserFilePath(string filename)
{
string userDir = null;
if ((Environment.OSVersion.Platform == PlatformID.Unix) || (Environment.OSVersion.Platform == PlatformID.MacOSX))
{
userDir = Environment.GetEnvironmentVariable("HOME") + "/";
}
else
{
userDir = Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%") + "\\";
}
return userDir + filename;
}
/// <summary>Load server profiles.</summary>
/// <param name="fileName">File to load server profiles from</param>
/// <param name="silent">Process logging disabled</param>
/// <returns>Number of profiles loaded</returns>
public int LoadServerList(string fileName, bool silent)
{
if (File.Exists(fileName))
{
try
{
string importJson = System.IO.File.ReadAllText(fileName);
ServerList = JsonConvert.DeserializeObject<Dictionary<string, ServerProfile>>(importJson);
}
catch (Exception e)
{
Ccli.ConditionalWrite($"Error parsing Server Profiles from {fileName}: {e.Message}", silent);
return -1;
}
}
return ServerList.Count;
}
/// <summary>Save configured server profiles.</summary>
/// <param name="fileName">File to save server profiles to</param>
/// <returns></returns>
public void SaveServerList(string fileName)
{
using (StreamWriter sw = new StreamWriter(fileName))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(sw, ServerList);
}
}
/// <summary>Get latest swagger definitions from cloud.</summary>
/// <param name="config">Contains config info, including profile to use</param>
/// <returns>Success or failure</returns>
public bool GetSwagger(CentrifyCliConfig config)
{
try
{
Ccli.ConditionalWrite($"Fetching latest swagger definitions from cloud.", config.Silent);
// Doesn't require auth
InitializeClient(config.Profile.URL);
var runTask = PlaceCall("/vfslow/lib/api/swagger.json", "");
runTask.Wait();
Tuple<Runner.ResultCode, string> callResult = runTask.Result;
if (callResult.Item1 == Runner.ResultCode.Success)
{
// Write item2 to swagger.json file. There's no JSON to process.
using (StreamWriter file = File.CreateText(config.SwaggerDirectory))
{
file.Write(callResult.Item2);
}
return true;
}
else
{
Ccli.WriteErrorText($"Error fetching swagger definitions from cloud: {callResult}");
}
}
catch (Exception e)
{
Ccli.WriteErrorText($"Exception fetching swagger definitions from cloud: {e.Message}");
}
return false;
}
/// <summary>Loads the swagger.json file from, typically, depot2\Cloud\Lib\Api\swagger.json
/// Builds API Resource from it.</summary>
/// <param name="config">Contains config info, including profile to use</param>
/// <returns>Success or failure</returns>
public bool LoadSwagger(CentrifyCliConfig config)
{
string swaggerPath = config.SwaggerDirectory;
if (String.IsNullOrEmpty(swaggerPath))
{
Ccli.WriteErrorText("No swagger path defined in config.");
return false;
}
Ccli.ConditionalWrite($"Loading swagger definitions from {swaggerPath}", config.Silent);
bool exists = File.Exists(swaggerPath);
if ((!exists) || (File.GetCreationTimeUtc(swaggerPath) < (DateTime.UtcNow - SWAGGER_REFRESH)))
{
// Fetch from cloud if no swagger or swagger is 'old'
if (!GetSwagger(config))
{
if (exists)
{
Ccli.ConditionalWrite($"Using existing swagger defintiions.", config.Silent);
}
else
{
Ccli.WriteErrorText($"No swagger definitions available from cloud.");
return false;
}
}
}
JObject swagSet = null;
try
{
using (StreamReader file = File.OpenText(swaggerPath))
using (JsonTextReader reader = new JsonTextReader(file))
{
swagSet = (JObject)JToken.ReadFrom(reader);
}
}
catch (Exception e)
{
Ccli.WriteErrorText($"Error loading swagger definitions from {swaggerPath}: {e.Message}");
return false;
}
JArray calls = new JArray();
foreach (JProperty path in swagSet["paths"])
{
JProperty restPath = new JProperty("path", (string)path.Name);
JProperty group = new JProperty("group", (string)path.First["post"]["tags"].First);
string[] pathBits = ((string)path.Name).Split(new char[] { '/' });
JProperty desc = new JProperty("api", pathBits[pathBits.Length - 1]);
JProperty reference = new JProperty("reference", (string)path.First["post"]["summary"]);
string parameters = "{";
int paramCount = 0;
JToken pathParams = path.First["post"]["parameters"].First;
if (pathParams != null)
{
try
{
foreach (JProperty prop in pathParams["schema"]["properties"])
{
if (paramCount++ > 0)
{
parameters += ",\n";
}
parameters += " \"" + (string)prop.Name + "\": \"\"";
}
}
catch
{
try
{
foreach (JToken tok in pathParams.First)
{
if (tok is JProperty prop)
{
if (paramCount++ > 0)
{
parameters += ",\n";
}
parameters += " \"" + (string)prop + "\": \"\"";
}
}
}
catch (Exception e)
{
Ccli.WriteErrorText($"Error parsing swagger properties from {swaggerPath}: {e.Message}");
return false;
};
}
}
if (paramCount > 0)
{
parameters += "\n";
}
parameters += "}";
JProperty sample = new JProperty("sample", parameters);
JObject thisCall = new JObject
{
restPath, // path == REST endpoint
sample, // parameters
group, // Grouping of calls
reference, // Reference (not really API, misnamed)
desc // Name of call
};
calls.Add(thisCall);
}
m_apiCalls = new JObject();
JProperty callWrapper = new JProperty("apis", calls);
m_apiCalls.Add(callWrapper);
return true;
}
/// <summary>Locate the specified API. Could put in dict instead, but this is fine for current numbers.</summary>
/// <param name="groupAndName"></param>
/// <returns>API group object</returns>
public JObject FindAPI(string groupAndName)
{
foreach (JObject jo in m_apiCalls["apis"])
{
if ((jo["group"] + ":" + jo["api"]).CompareTo(groupAndName) == 0)
{
return jo;
}
}
return null;
}
/// <summary>JObject to string</summary>
/// <param name="jo">JObject</param>
/// <returns>String version of JObject</returns>
private String ApiJObjectToString(JObject jo)
{
StringBuilder sb = new StringBuilder();
return sb.Append(jo["path"] + ": " + jo["reference"] + "\n")
.Append(jo["sample"].ToString().Replace("{", "{\n").Replace("\\n", "\n")).Append("\n\n").ToString();
}
/// <summary>List all APIs.</summary>
/// <returns>API list</returns>
public string ListAPIs()
{
StringBuilder sb = new StringBuilder();
SortedSet<string> report = new SortedSet<string>();
foreach (JObject jo in m_apiCalls["apis"])
{
report.Add(ApiJObjectToString(jo));
}
foreach (string s in report)
{
sb.Append(s);
}
return sb.ToString();
}
/// <summary>Returns APIs with the specified substring in their path or summary or tag</summary>
/// <param name="subset"></param>
/// <returns>API list</returns>
public string FindAPIMatch(string subset)
{
SortedSet<string> report = new SortedSet<string>();
foreach (JObject jo in m_apiCalls["apis"])
{
if ((jo["group"].ToString().Contains(subset, StringComparison.InvariantCultureIgnoreCase))
|| (jo["path"].ToString().Contains(subset, StringComparison.InvariantCultureIgnoreCase))
|| (jo["reference"].ToString().Contains(subset, StringComparison.InvariantCultureIgnoreCase))
|| (jo["api"].ToString().Contains(subset, StringComparison.InvariantCultureIgnoreCase))
)
{
report.Add(ApiJObjectToString(jo));
}
}
StringBuilder sb = new StringBuilder();
foreach (string s in report)
{
sb.Append(s);
}
return sb.ToString();
}
/// <summary>REST result (JObject) to string</summary>
/// <param name="result">JObject result</param>
/// <returns>String version of result</returns>
private static string ResultToString(JObject result)
{
if (result == null)
{
return string.Empty;
}
List<string> propNames = result.Properties().Select(prop => prop.Name).ToList();
foreach (string propName in propNames)
{
// Never remove "Result", always remove "IsSoftError" or null values
switch (propName)
{
case "Result":
break;
case "IsSoftError":
result.Remove(propName);
break;
default:
JToken val = result[propName];
if ((val == null) ||
(val.Type == JTokenType.Array && !val.HasValues) ||
(val.Type == JTokenType.Object && !val.HasValues) ||
(val.Type == JTokenType.String && String.IsNullOrEmpty(val.ToString())) ||
(val.Type == JTokenType.Null))
{
result.Remove(propName);
}
break;
}
}
return JsonConvert.SerializeObject(result, Formatting.Indented);
}
/// <summary>Finds nodes matching the string. </summary>
static List<string> FindNodes(JToken node, string target)
{
List<string> returns = new List<string>();
if (node.Type == JTokenType.Object)
{
foreach (JProperty child in node.Children<JProperty>())
{
if (child.Name == target)
returns.Add(child.Value.ToString());
returns.AddRange(FindNodes(child.Value, target));
}
}
else if (node.Type == JTokenType.Array)
{
foreach (JToken child in node.Children())
{
returns.AddRange(FindNodes(child, target));
}
}
return returns;
}
/// <summary>Fetch value of key from JObject, if key exists</summary>
/// <param name="obj">JObject</param>
/// <param name="key">Key name</param>
/// <param name="value">(out) Key value</param>
/// <returns>Value of key, or default value if key is not present</returns>
private bool TryGetJObjectValue<T>(JObject obj, string key, out T value)
{
if ((obj != null) && obj.TryGetValue(key, out JToken token))
{
value = token.ToObject<T>();
return true;
}
else
{
value = default(T);
return false;
}
}
/// <summary>Parses the output and returns success or failure and the string to write to the console.</summary>
/// <param name="restResults"></param>
/// <param name="extract">Variable to extract. If not specified, print the whole thing.</param>
/// <returns></returns>
public Tuple<bool, string> ParseResults(string restResults, string extract)
{
JObject resultSet;
try
{
resultSet = ParseContentsToJObject(restResults);
if (!TryGetJObjectValue(resultSet, "success", out bool success))
{
throw new ArgumentException($"Results are missing 'success': {ResultToString(resultSet)}", "success");
}
if (String.IsNullOrEmpty(extract))
return new Tuple<bool, string>(success, ResultToString(resultSet));
// else Just return the one value
List<string> returns = FindNodes(resultSet, extract);//-V3080
if (returns.Count == 0)
return new Tuple<bool, string>(success, "");
return new Tuple<bool, string>(success, string.Join("\n", returns));
}
catch (Exception e)
{
return new Tuple<bool, string>(false, MakeFailResult(restResults, "REST results could not be parsed.", e.Message));
}
}
/// <summary>Generate a failure result fpr a REST call.</summary>
/// <param name="result">JToken result</param>
/// <param name="message">Optional error message string</param>
/// <param name="exception">Optional exception string</param>
/// <returns>rResult string</returns>
public static string MakeFailResult(JToken result, string message = null, string exception = null)
{
JObject failResult = new JObject
{
["success"] = false,
["Message"] = (message != null ? FAILED + message : null),
["Exception"] = exception
};
return ResultToString(failResult);
}
/// <summary>generate a stromng of random characters.</summary>
/// <param name="chars">Number of characters</param>
/// <returns>Random string</returns>
public static string RandomString(int chars)
{
Random r = new Random();
string random = "";
for (int i = 0; i < chars; i++)
{
int x = r.Next(62);
random += (char)(x < 26?(char)(x+'a'):x<52?(char)(x-26+'A'):(char)x-52+'0');
}
return random;
}
/// <summary>Centrify-specific OAuth2 Token request</summary>
/// <param name="config">Contains config info, including profile to use</param>
/// <param name="timeout">Timeout is milliserconds for REST calls</param>
/// <returns>Tuple of success and either token or error message.</returns>
public async Task<Tuple<ResultCode, string>> OAuth2_GenerateTokenRequest(CentrifyCliConfig config, int timeout)
{
ServerProfile profile = config.Profile;
string TokenEndpoint = "/oauth2/token/" + profile.OAuthAppId;
if(profile.Password == null && !config.Silent)
{
Console.Write($"Enter password for {profile.UserName}: ");
profile.Password = ReadMaskedPassword(false);
}
string queryParams = $"grant_type=client_credentials&response_type=code&state={RandomString(15)}&scope=ccli&client_id={profile.UserName}&client_secret={profile.Password}";
try
{
Ccli.ConditionalWrite($"Requesting token for {profile.UserName}.", config.Silent);
InitializeClient(profile.URL);
Task<HttpResponseMessage> response = m_restUpdater.NewRequestAsync(profile.URL+ TokenEndpoint, queryParams);
if (!response.Wait(timeout))
{
return new Tuple<ResultCode, string>(ResultCode.Timeout, "Request for token timed out.");
}
HttpStatusCode statusCode = response.Result.StatusCode;
string contents = await response.Result.Content.ReadAsStringAsync();
JObject resultSet = ParseContentsToJObject(contents);
if (response.Result.StatusCode != HttpStatusCode.OK)
{
return new Tuple<ResultCode, string>(ResultCode.Failed, $"Token request failed/denied: {statusCode}, {ResultToString(resultSet)}");
}
if (!TryGetJObjectValue(resultSet, "access_token", out string accessToken))
{
throw new ArgumentException($"Token response is missing 'access_token': {ResultToString(resultSet)}", "access_token");
}
return new Tuple<ResultCode, string>(ResultCode.Success, accessToken);
}
catch (Exception ex)
{
return new Tuple<ResultCode, string>(ResultCode.Exception, ex.Message);
}
}
/// <summary>Accepts either the token or the entire response string, parses out the token.</summary>
/// <param name="response"></param>
/// <returns>Parsed token</returns>
public static string ParseToken(string response)
{
string tokenFlag = "access_token";
if (!response.Contains(tokenFlag))
{
return response;
}
string[] keys = response.Split(new char[]{ '&' });
// Length includes "="
return keys.First(k => k.StartsWith(tokenFlag)).Substring(tokenFlag.Length + 1);
}
/// <summary>Initialize a new rest client.</summary>
/// <param name="url">Cloud URL</param>
/// <returns></returns>
public void InitializeClient(string url)
{
if (string.IsNullOrWhiteSpace(url))
{
throw new ArgumentException("You must specify a Cloud url with the -url argument, or save config with the url set via ‘ccli -url https://<yoururl> saveconfig’");
}
// Validate URL
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult) || (uriResult.Scheme != Uri.UriSchemeHttps))
{
throw new ArgumentException($"Cloud URL is invalid (must start with 'https://'): '{url}'");
}
m_restUpdater.NewClient();
m_url = url;
}
/// <summary>Initialize a new rest client.</summary>
/// <param name="url">Cloud URL</param>
/// <param name="token">)Auth token</param>
/// <returns></returns>
public void InitializeClient(string url, string token)
{
InitializeClient(url);
m_restUpdater.AuthValue = token;
}
}
}
| 43.504416 | 184 | 0.48659 | [
"Apache-2.0"
] | ankitchandra18/centrifycli | Runner.cs | 44,337 | C# |
using Microsoft.CodeAnalysis;
using ScriptCs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace OmniSharp.ScriptCs.Extensions
{
internal static class ScriptcsExtensions
{
private static readonly string BaseAssemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
internal static IEnumerable<MetadataReference> MakeMetadataReferences(this ScriptServices scriptServices, IEnumerable<string> referencesPaths)
{
var listOfReferences = new List<MetadataReference>();
foreach (var importedReference in referencesPaths.Where(x => !x.ToLowerInvariant().Contains("scriptcs.contracts")))
{
if (scriptServices.FileSystem.IsPathRooted(importedReference))
{
if (scriptServices.FileSystem.FileExists(importedReference))
listOfReferences.Add(MetadataReference.CreateFromFile(importedReference));
}
else
{
listOfReferences.Add(MetadataReference.CreateFromFile(Path.Combine(BaseAssemblyPath, importedReference.ToLower().EndsWith(".dll") ? importedReference : importedReference + ".dll")));
}
}
return listOfReferences;
}
}
}
| 39 | 202 | 0.665934 | [
"MIT"
] | aignas/omnisharp-roslyn | src/OmniSharp.ScriptCs/Extensions/ScriptcsExtensions.cs | 1,367 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using AutoMapper;
using Umbraco.Core;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Services;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Models.Mapping;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Http.Controllers;
using Examine;
using Umbraco.Web.WebApi.Binders;
using Umbraco.Web.WebApi.Filters;
using Constants = Umbraco.Core.Constants;
using Umbraco.Core.Configuration;
using Umbraco.Web.UI;
using Notification = Umbraco.Web.Models.ContentEditing.Notification;
using Umbraco.Core.Persistence;
namespace Umbraco.Web.Editors
{
/// <remarks>
/// This controller is decorated with the UmbracoApplicationAuthorizeAttribute which means that any user requesting
/// access to ALL of the methods on this controller will need access to the media application.
/// </remarks>
[PluginController("UmbracoApi")]
[UmbracoApplicationAuthorize(Constants.Applications.Media)]
[MediaControllerControllerConfiguration]
public class MediaController : ContentControllerBase
{
/// <summary>
/// Configures this controller with a custom action selector
/// </summary>
private class MediaControllerControllerConfigurationAttribute : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
{
controllerSettings.Services.Replace(typeof(IHttpActionSelector), new ParameterSwapControllerActionSelector(
new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetById", "id", typeof(int), typeof(Guid), typeof(Udi)),
new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetChildren", "id", typeof(int), typeof(Guid), typeof(Udi), typeof(string))));
}
}
/// <summary>
/// Constructor
/// </summary>
public MediaController()
: this(UmbracoContext.Current)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="umbracoContext"></param>
public MediaController(UmbracoContext umbracoContext)
: base(umbracoContext)
{
}
/// <summary>
/// Gets an empty content item for the
/// </summary>
/// <param name="contentTypeAlias"></param>
/// <param name="parentId"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
public MediaItemDisplay GetEmpty(string contentTypeAlias, int parentId)
{
var contentType = Services.ContentTypeService.GetMediaType(contentTypeAlias);
if (contentType == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
var emptyContent = Services.MediaService.CreateMedia("", parentId, contentType.Alias, UmbracoUser.Id);
var mapped = Mapper.Map<IMedia, MediaItemDisplay>(emptyContent);
//remove this tab if it exists: umbContainerView
var containerTab = mapped.Tabs.FirstOrDefault(x => x.Alias == Constants.Conventions.PropertyGroups.ListViewGroupName);
mapped.Tabs = mapped.Tabs.Except(new[] { containerTab });
return mapped;
}
/// <summary>
/// Returns an item to be used to display the recycle bin for media
/// </summary>
/// <returns></returns>
public ContentItemDisplay GetRecycleBin()
{
var display = new ContentItemDisplay
{
Id = Constants.System.RecycleBinMedia,
Alias = "recycleBin",
ParentId = -1,
Name = Services.TextService.Localize("general/recycleBin"),
ContentTypeAlias = "recycleBin",
CreateDate = DateTime.Now,
IsContainer = true,
Path = "-1," + Constants.System.RecycleBinMedia
};
TabsAndPropertiesResolver.AddListView(display, "media", Services.DataTypeService, Services.TextService);
return display;
}
/// <summary>
/// Gets the media item by id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[EnsureUserPermissionForMedia("id")]
public MediaItemDisplay GetById(int id)
{
var foundContent = GetObjectFromRequest(() => Services.MediaService.GetById(id));
if (foundContent == null)
{
HandleContentNotFound(id);
//HandleContentNotFound will throw an exception
return null;
}
return Mapper.Map<IMedia, MediaItemDisplay>(foundContent);
}
/// <summary>
/// Gets the media item by id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[EnsureUserPermissionForMedia("id")]
public MediaItemDisplay GetById(Guid id)
{
var foundContent = GetObjectFromRequest(() => Services.MediaService.GetById(id));
if (foundContent == null)
{
HandleContentNotFound(id);
//HandleContentNotFound will throw an exception
return null;
}
return Mapper.Map<IMedia, MediaItemDisplay>(foundContent);
}
/// <summary>
/// Gets the media item by id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[EnsureUserPermissionForMedia("id")]
public MediaItemDisplay GetById(Udi id)
{
var guidUdi = id as GuidUdi;
if (guidUdi != null)
{
return GetById(guidUdi.Guid);
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
/// <summary>
/// Return media for the specified ids
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[FilterAllowedOutgoingMedia(typeof(IEnumerable<MediaItemDisplay>))]
public IEnumerable<MediaItemDisplay> GetByIds([FromUri]int[] ids)
{
var foundMedia = Services.MediaService.GetByIds(ids);
return foundMedia.Select(Mapper.Map<IMedia, MediaItemDisplay>);
}
/// <summary>
/// Returns media items known to be of a "Folder" type
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[Obsolete("This is no longer used and shouldn't be because it performs poorly when there are a lot of media items")]
[FilterAllowedOutgoingMedia(typeof(IEnumerable<ContentItemBasic<ContentPropertyBasic, IMedia>>))]
public IEnumerable<ContentItemBasic<ContentPropertyBasic, IMedia>> GetChildFolders(int id = -1)
{
//we are only allowing a max of 500 to be returned here, if more is required it needs to be paged
var result = GetChildFolders(id, 1, 500);
return result.Items;
}
/// <summary>
/// Returns a paged result of media items known to be of a "Folder" type
/// </summary>
/// <param name="id"></param>
/// <param name="pageNumber"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
public PagedResult<ContentItemBasic<ContentPropertyBasic, IMedia>> GetChildFolders(int id, int pageNumber, int pageSize)
{
//Suggested convention for folder mediatypes - we can make this more or less complicated as long as we document it...
//if you create a media type, which has an alias that ends with ...Folder then its a folder: ex: "secureFolder", "bannerFolder", "Folder"
var folderTypes = Services.ContentTypeService
.GetAllMediaTypes()
.Where(x => x.Alias.EndsWith("Folder"))
.Select(x => x.Id)
.ToArray();
if (folderTypes.Length == 0)
{
return new PagedResult<ContentItemBasic<ContentPropertyBasic, IMedia>>(0, pageNumber, pageSize);
}
long total;
var children = Services.MediaService.GetPagedChildren(id, pageNumber - 1, pageSize, out total, "Name", Direction.Ascending, true, null, folderTypes.ToArray());
return new PagedResult<ContentItemBasic<ContentPropertyBasic, IMedia>>(total, pageNumber, pageSize)
{
Items = children.Select(Mapper.Map<IMedia, ContentItemBasic<ContentPropertyBasic, IMedia>>)
};
}
/// <summary>
/// Returns the root media objects
/// </summary>
[FilterAllowedOutgoingMedia(typeof(IEnumerable<ContentItemBasic<ContentPropertyBasic, IMedia>>))]
public IEnumerable<ContentItemBasic<ContentPropertyBasic, IMedia>> GetRootMedia()
{
//TODO: Add permissions check!
return Services.MediaService.GetRootMedia()
.Select(Mapper.Map<IMedia, ContentItemBasic<ContentPropertyBasic, IMedia>>);
}
#region GetChildren
/// <summary>
/// Returns the child media objects - using the entity INT id
/// </summary>
[FilterAllowedOutgoingMedia(typeof(IEnumerable<ContentItemBasic<ContentPropertyBasic, IMedia>>), "Items")]
public PagedResult<ContentItemBasic<ContentPropertyBasic, IMedia>> GetChildren(int id,
int pageNumber = 0,
int pageSize = 0,
string orderBy = "SortOrder",
Direction orderDirection = Direction.Ascending,
bool orderBySystemField = true,
string filter = "")
{
long totalChildren;
IMedia[] children;
if (pageNumber > 0 && pageSize > 0)
{
children = Services.MediaService
.GetPagedChildren(id, (pageNumber - 1), pageSize, out totalChildren
, orderBy, orderDirection, orderBySystemField, filter).ToArray();
}
else
{
children = Services.MediaService.GetChildren(id).ToArray();
totalChildren = children.Length;
}
if (totalChildren == 0)
{
return new PagedResult<ContentItemBasic<ContentPropertyBasic, IMedia>>(0, 0, 0);
}
var pagedResult = new PagedResult<ContentItemBasic<ContentPropertyBasic, IMedia>>(totalChildren, pageNumber, pageSize);
pagedResult.Items = children
.Select(Mapper.Map<IMedia, ContentItemBasic<ContentPropertyBasic, IMedia>>);
return pagedResult;
}
/// <summary>
/// Returns the child media objects - using the entity GUID id
/// </summary>
/// <param name="id"></param>
/// <param name="pageNumber"></param>
/// <param name="pageSize"></param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="orderBySystemField"></param>
/// <param name="filter"></param>
/// <returns></returns>
[FilterAllowedOutgoingMedia(typeof(IEnumerable<ContentItemBasic<ContentPropertyBasic, IMedia>>), "Items")]
public PagedResult<ContentItemBasic<ContentPropertyBasic, IMedia>> GetChildren(Guid id,
int pageNumber = 0,
int pageSize = 0,
string orderBy = "SortOrder",
Direction orderDirection = Direction.Ascending,
bool orderBySystemField = true,
string filter = "")
{
var entity = Services.EntityService.GetByKey(id);
if (entity != null)
{
return GetChildren(entity.Id, pageNumber, pageSize, orderBy, orderDirection, orderBySystemField, filter);
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
/// <summary>
/// Returns the child media objects - using the entity UDI id
/// </summary>
/// <param name="id"></param>
/// <param name="pageNumber"></param>
/// <param name="pageSize"></param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="orderBySystemField"></param>
/// <param name="filter"></param>
/// <returns></returns>
[FilterAllowedOutgoingMedia(typeof(IEnumerable<ContentItemBasic<ContentPropertyBasic, IMedia>>), "Items")]
public PagedResult<ContentItemBasic<ContentPropertyBasic, IMedia>> GetChildren(Udi id,
int pageNumber = 0,
int pageSize = 0,
string orderBy = "SortOrder",
Direction orderDirection = Direction.Ascending,
bool orderBySystemField = true,
string filter = "")
{
var guidUdi = id as GuidUdi;
if (guidUdi != null)
{
var entity = Services.EntityService.GetByKey(guidUdi.Guid);
if (entity != null)
{
return GetChildren(entity.Id, pageNumber, pageSize, orderBy, orderDirection, orderBySystemField, filter);
}
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
[Obsolete("Do not use this method, use either the overload with INT or GUID instead, this will be removed in future versions")]
[EditorBrowsable(EditorBrowsableState.Never)]
[UmbracoTreeAuthorize(Constants.Trees.MediaTypes, Constants.Trees.Media)]
public PagedResult<ContentItemBasic<ContentPropertyBasic, IMedia>> GetChildren(string id,
int pageNumber = 0,
int pageSize = 0,
string orderBy = "SortOrder",
Direction orderDirection = Direction.Ascending,
bool orderBySystemField = true,
string filter = "")
{
foreach (var type in new[] { typeof(int), typeof(Guid) })
{
var parsed = id.TryConvertTo(type);
if (parsed)
{
//oooh magic! will auto select the right overload
return GetChildren((dynamic)parsed.Result);
}
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
#endregion
/// <summary>
/// Moves an item to the recycle bin, if it is already there then it will permanently delete it
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[EnsureUserPermissionForMedia("id")]
[HttpPost]
public HttpResponseMessage DeleteById(int id)
{
var foundMedia = GetObjectFromRequest(() => Services.MediaService.GetById(id));
if (foundMedia == null)
{
return HandleContentNotFound(id, false);
}
//if the current item is in the recycle bin
if (foundMedia.IsInRecycleBin() == false)
{
var moveResult = Services.MediaService.WithResult().MoveToRecycleBin(foundMedia, (int)Security.CurrentUser.Id);
if (moveResult == false)
{
//returning an object of INotificationModel will ensure that any pending
// notification messages are added to the response.
return Request.CreateValidationErrorResponse(new SimpleNotificationModel());
}
}
else
{
var deleteResult = Services.MediaService.WithResult().Delete(foundMedia, (int)Security.CurrentUser.Id);
if (deleteResult == false)
{
//returning an object of INotificationModel will ensure that any pending
// notification messages are added to the response.
return Request.CreateValidationErrorResponse(new SimpleNotificationModel());
}
}
return Request.CreateResponse(HttpStatusCode.OK);
}
/// <summary>
/// Change the sort order for media
/// </summary>
/// <param name="move"></param>
/// <returns></returns>
[EnsureUserPermissionForMedia("move.Id")]
public HttpResponseMessage PostMove(MoveOrCopy move)
{
var toMove = ValidateMoveOrCopy(move);
Services.MediaService.Move(toMove, move.ParentId);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(toMove.Path, Encoding.UTF8, "application/json");
return response;
}
/// <summary>
/// Saves content
/// </summary>
/// <returns></returns>
[FileUploadCleanupFilter]
[MediaPostValidate]
public MediaItemDisplay PostSave(
[ModelBinder(typeof(MediaItemBinder))]
MediaItemSave contentItem)
{
//If we've reached here it means:
// * Our model has been bound
// * and validated
// * any file attachments have been saved to their temporary location for us to use
// * we have a reference to the DTO object and the persisted object
// * Permissions are valid
MapPropertyValues(contentItem);
//We need to manually check the validation results here because:
// * We still need to save the entity even if there are validation value errors
// * Depending on if the entity is new, and if there are non property validation errors (i.e. the name is null)
// then we cannot continue saving, we can only display errors
// * If there are validation errors and they were attempting to publish, we can only save, NOT publish and display
// a message indicating this
if (ModelState.IsValid == false)
{
if (ValidationHelper.ModelHasRequiredForPersistenceErrors(contentItem)
&& (contentItem.Action == ContentSaveAction.SaveNew))
{
//ok, so the absolute mandatory data is invalid and it's new, we cannot actually continue!
// add the modelstate to the outgoing object and throw validation response
var forDisplay = Mapper.Map<IMedia, MediaItemDisplay>(contentItem.PersistedContent);
forDisplay.Errors = ModelState.ToErrorDictionary();
throw new HttpResponseException(Request.CreateValidationErrorResponse(forDisplay));
}
}
//save the item
var saveStatus = Services.MediaService.WithResult().Save(contentItem.PersistedContent, (int)Security.CurrentUser.Id);
//return the updated model
var display = Mapper.Map<IMedia, MediaItemDisplay>(contentItem.PersistedContent);
//lasty, if it is not valid, add the modelstate to the outgoing object and throw a 403
HandleInvalidModelState(display);
//put the correct msgs in
switch (contentItem.Action)
{
case ContentSaveAction.Save:
case ContentSaveAction.SaveNew:
if (saveStatus.Success)
{
display.AddSuccessNotification(
Services.TextService.Localize("speechBubbles/editMediaSaved"),
Services.TextService.Localize("speechBubbles/editMediaSavedText"));
}
else
{
AddCancelMessage(display);
//If the item is new and the operation was cancelled, we need to return a different
// status code so the UI can handle it since it won't be able to redirect since there
// is no Id to redirect to!
if (saveStatus.Result.StatusType == OperationStatusType.FailedCancelledByEvent && IsCreatingAction(contentItem.Action))
{
throw new HttpResponseException(Request.CreateValidationErrorResponse(display));
}
}
break;
}
return display;
}
/// <summary>
/// Maps the property values to the persisted entity
/// </summary>
/// <param name="contentItem"></param>
protected override void MapPropertyValues<TPersisted>(ContentBaseItemSave<TPersisted> contentItem)
{
UpdateName(contentItem);
//use the base method to map the rest of the properties
base.MapPropertyValues(contentItem);
}
/// <summary>
/// Empties the recycle bin
/// </summary>
/// <returns></returns>
[HttpDelete]
[HttpPost]
public HttpResponseMessage EmptyRecycleBin()
{
Services.MediaService.EmptyRecycleBin();
return Request.CreateNotificationSuccessResponse(Services.TextService.Localize("defaultdialogs/recycleBinIsEmpty"));
}
/// <summary>
/// Change the sort order for media
/// </summary>
/// <param name="sorted"></param>
/// <returns></returns>
[EnsureUserPermissionForMedia("sorted.ParentId")]
public HttpResponseMessage PostSort(ContentSortOrder sorted)
{
if (sorted == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
//if there's nothing to sort just return ok
if (sorted.IdSortOrder.Length == 0)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
var mediaService = base.ApplicationContext.Services.MediaService;
var sortedMedia = new List<IMedia>();
try
{
sortedMedia.AddRange(sorted.IdSortOrder.Select(mediaService.GetById));
// Save Media with new sort order and update content xml in db accordingly
if (mediaService.Sort(sortedMedia) == false)
{
LogHelper.Warn<MediaController>("Media sorting failed, this was probably caused by an event being cancelled");
return Request.CreateValidationErrorResponse("Media sorting failed, this was probably caused by an event being cancelled");
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception ex)
{
LogHelper.Error<MediaController>("Could not update media sort order", ex);
throw;
}
}
[EnsureUserPermissionForMedia("folder.ParentId")]
public MediaItemDisplay PostAddFolder(EntityBasic folder)
{
var mediaService = ApplicationContext.Services.MediaService;
var f = mediaService.CreateMedia(folder.Name, folder.ParentId, Constants.Conventions.MediaTypes.Folder);
mediaService.Save(f, Security.CurrentUser.Id);
return Mapper.Map<IMedia, MediaItemDisplay>(f);
}
/// <summary>
/// Used to submit a media file
/// </summary>
/// <returns></returns>
/// <remarks>
/// We cannot validate this request with attributes (nicely) due to the nature of the multi-part for data.
/// </remarks>
[FileUploadCleanupFilter(false)]
public async Task<HttpResponseMessage> PostAddFile()
{
if (Request.Content.IsMimeMultipartContent() == false)
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var root = IOHelper.MapPath("~/App_Data/TEMP/FileUploads");
//ensure it exists
Directory.CreateDirectory(root);
var provider = new MultipartFormDataStreamProvider(root);
var result = await Request.Content.ReadAsMultipartAsync(provider);
//must have a file
if (result.FileData.Count == 0)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
//get the string json from the request
int parentId; bool entityFound; GuidUdi parentUdi;
string currentFolderId = result.FormData["currentFolder"];
// test for udi
if (GuidUdi.TryParse(currentFolderId, out parentUdi))
{
currentFolderId = parentUdi.Guid.ToString();
}
if (int.TryParse(currentFolderId, out parentId) == false)
{
// if a guid then try to look up the entity
Guid idGuid;
if (Guid.TryParse(currentFolderId, out idGuid))
{
var entity = Services.EntityService.GetByKey(idGuid);
if (entity != null)
{
entityFound = true;
parentId = entity.Id;
}
else
{
throw new EntityNotFoundException(currentFolderId, "The passed id doesn't exist");
}
}
else
{
return Request.CreateValidationErrorResponse("The request was not formatted correctly, the currentFolder is not an integer or Guid");
}
if (entityFound == false)
{
return Request.CreateValidationErrorResponse("The request was not formatted correctly, the currentFolder is not an integer or Guid");
}
}
//ensure the user has access to this folder by parent id!
if (CheckPermissions(
new Dictionary<string, object>(),
Security.CurrentUser,
Services.MediaService, parentId) == false)
{
return Request.CreateResponse(
HttpStatusCode.Forbidden,
new SimpleNotificationModel(new Notification(
Services.TextService.Localize("speechBubbles/operationFailedHeader"),
Services.TextService.Localize("speechBubbles/invalidUserPermissionsText"),
SpeechBubbleIcon.Warning)));
}
var tempFiles = new PostedFiles();
var mediaService = ApplicationContext.Services.MediaService;
//in case we pass a path with a folder in it, we will create it and upload media to it.
if (result.FormData.ContainsKey("path"))
{
var folders = result.FormData["path"].Split('/');
for (int i = 0; i < folders.Length - 1; i++)
{
var folderName = folders[i];
IMedia folderMediaItem;
//if uploading directly to media root and not a subfolder
if (parentId == -1)
{
//look for matching folder
folderMediaItem =
mediaService.GetRootMedia().FirstOrDefault(x => x.Name == folderName && x.ContentType.Alias == Constants.Conventions.MediaTypes.Folder);
if (folderMediaItem == null)
{
//if null, create a folder
folderMediaItem = mediaService.CreateMedia(folderName, -1, Constants.Conventions.MediaTypes.Folder);
mediaService.Save(folderMediaItem);
}
}
else
{
//get current parent
var mediaRoot = mediaService.GetById(parentId);
//if the media root is null, something went wrong, we'll abort
if (mediaRoot == null)
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
"The folder: " + folderName + " could not be used for storing images, its ID: " + parentId +
" returned null");
//look for matching folder
folderMediaItem = mediaRoot.Children().FirstOrDefault(x => x.Name == folderName && x.ContentType.Alias == Constants.Conventions.MediaTypes.Folder);
if (folderMediaItem == null)
{
//if null, create a folder
folderMediaItem = mediaService.CreateMedia(folderName, mediaRoot, Constants.Conventions.MediaTypes.Folder);
mediaService.Save(folderMediaItem);
}
}
//set the media root to the folder id so uploaded files will end there.
parentId = folderMediaItem.Id;
}
}
//get the files
foreach (var file in result.FileData)
{
var fileName = file.Headers.ContentDisposition.FileName.Trim(new[] { '\"' }).TrimEnd();
var safeFileName = fileName.ToSafeFileName();
var ext = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLower();
if (UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles.Contains(ext) == false)
{
var mediaType = Constants.Conventions.MediaTypes.File;
if (result.FormData["contentTypeAlias"] == Constants.Conventions.MediaTypes.AutoSelect)
{
if (UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes.Contains(ext))
{
mediaType = Constants.Conventions.MediaTypes.Image;
}
}
else
{
mediaType = result.FormData["contentTypeAlias"];
}
//TODO: make the media item name "nice" since file names could be pretty ugly, we have
// string extensions to do much of this but we'll need:
// * Pascalcase the name (use string extensions)
// * strip the file extension
// * underscores to spaces
// * probably remove 'ugly' characters - let's discuss
// All of this logic should exist in a string extensions method and be unit tested
// http://issues.umbraco.org/issue/U4-5572
var mediaItemName = fileName;
var f = mediaService.CreateMedia(mediaItemName, parentId, mediaType, Security.CurrentUser.Id);
var fileInfo = new FileInfo(file.LocalFileName);
var fs = fileInfo.OpenReadWithRetry();
if (fs == null) throw new InvalidOperationException("Could not acquire file stream");
using (fs)
{
f.SetValue(Constants.Conventions.Media.File, fileName, fs);
}
var saveResult = mediaService.WithResult().Save(f, Security.CurrentUser.Id);
if (saveResult == false)
{
AddCancelMessage(tempFiles,
message: Services.TextService.Localize("speechBubbles/operationCancelledText") + " -- " + mediaItemName,
localizeMessage: false);
}
else
{
tempFiles.UploadedFiles.Add(new ContentItemFile
{
FileName = fileName,
PropertyAlias = Constants.Conventions.Media.File,
TempFilePath = file.LocalFileName
});
}
}
else
{
tempFiles.Notifications.Add(new Notification(
Services.TextService.Localize("speechBubbles/operationFailedHeader"),
Services.TextService.Localize("media/disallowedFileType"),
SpeechBubbleIcon.Warning));
}
}
//Different response if this is a 'blueimp' request
if (Request.GetQueryNameValuePairs().Any(x => x.Key == "origin"))
{
var origin = Request.GetQueryNameValuePairs().First(x => x.Key == "origin");
if (origin.Value == "blueimp")
{
return Request.CreateResponse(HttpStatusCode.OK,
tempFiles,
//Don't output the angular xsrf stuff, blue imp doesn't like that
new JsonMediaTypeFormatter());
}
}
return Request.CreateResponse(HttpStatusCode.OK, tempFiles);
}
/// <summary>
/// Ensures the item can be moved/copied to the new location
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
private IMedia ValidateMoveOrCopy(MoveOrCopy model)
{
if (model == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
var mediaService = Services.MediaService;
var toMove = mediaService.GetById(model.Id);
if (toMove == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
if (model.ParentId < 0)
{
//cannot move if the content item is not allowed at the root
if (toMove.ContentType.AllowedAsRoot == false)
{
var notificationModel = new SimpleNotificationModel();
notificationModel.AddErrorNotification(Services.TextService.Localize("moveOrCopy/notAllowedAtRoot"), "");
throw new HttpResponseException(Request.CreateValidationErrorResponse(notificationModel));
}
}
else
{
var parent = mediaService.GetById(model.ParentId);
if (parent == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
//check if the item is allowed under this one
if (parent.ContentType.AllowedContentTypes.Select(x => x.Id).ToArray()
.Any(x => x.Value == toMove.ContentType.Id) == false)
{
var notificationModel = new SimpleNotificationModel();
notificationModel.AddErrorNotification(Services.TextService.Localize("moveOrCopy/notAllowedByContentType"), "");
throw new HttpResponseException(Request.CreateValidationErrorResponse(notificationModel));
}
// Check on paths
if ((string.Format(",{0},", parent.Path)).IndexOf(string.Format(",{0},", toMove.Id), StringComparison.Ordinal) > -1)
{
var notificationModel = new SimpleNotificationModel();
notificationModel.AddErrorNotification(Services.TextService.Localize("moveOrCopy/notAllowedByPath"), "");
throw new HttpResponseException(Request.CreateValidationErrorResponse(notificationModel));
}
}
return toMove;
}
/// <summary>
/// Performs a permissions check for the user to check if it has access to the node based on
/// start node and/or permissions for the node
/// </summary>
/// <param name="storage">The storage to add the content item to so it can be reused</param>
/// <param name="user"></param>
/// <param name="mediaService"></param>
/// <param name="nodeId">The content to lookup, if the contentItem is not specified</param>
/// <param name="media">Specifies the already resolved content item to check against, setting this ignores the nodeId</param>
/// <returns></returns>
internal static bool CheckPermissions(IDictionary<string, object> storage, IUser user, IMediaService mediaService, int nodeId, IMedia media = null)
{
if (media == null && nodeId != Constants.System.Root && nodeId != Constants.System.RecycleBinMedia)
{
media = mediaService.GetById(nodeId);
//put the content item into storage so it can be retreived
// in the controller (saves a lookup)
storage[typeof(IMedia).ToString()] = media;
}
if (media == null && nodeId != Constants.System.Root && nodeId != Constants.System.RecycleBinMedia)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
var hasPathAccess = (nodeId == Constants.System.Root)
? UserExtensions.HasPathAccess(
Constants.System.Root.ToInvariantString(),
user.StartMediaId,
Constants.System.RecycleBinMedia)
: (nodeId == Constants.System.RecycleBinMedia)
? UserExtensions.HasPathAccess(
Constants.System.RecycleBinMedia.ToInvariantString(),
user.StartMediaId,
Constants.System.RecycleBinMedia)
: user.HasPathAccess(media);
return hasPathAccess;
}
}
}
| 44.221729 | 172 | 0.54826 | [
"MIT"
] | DiogenesPolanco/Umbraco-CMS | src/Umbraco.Web/Editors/MediaController.cs | 39,890 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.0
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WinApp.Properties {
using System;
/// <summary>
/// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
/// </summary>
// Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
// -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
// Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
// mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WinApp.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
/// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Sucht eine lokalisierte Zeichenfolge, die Projectname: ähnelt.
/// </summary>
public static string Projectname {
get {
return ResourceManager.GetString("Projectname", resourceCulture);
}
}
}
}
| 45.890411 | 173 | 0.611045 | [
"MIT"
] | andre-hub/WinApp-Template | source/WinApp/Properties/Resources.Designer.cs | 3,361 | C# |
using System;
using System.Collections.Generic;
using Solo.BinaryTree.Constructor.Core;
using Solo.BinaryTree.Constructor.Infrastructure;
namespace Solo.BinaryTree.Constructor.Parser.ChainedImplementation.Actions
{
public class CreateTreeFromParsedValues : BinaryTreeParseAction
{
public override void Execute(BinaryTreeParseArguments args)
{
foreach (var getModelResult in args.NodeModels)
{
if (getModelResult.IsFailure)
{
args.AddError(getModelResult.FailureMessage);
return;
}
CommandResult result = this.ProcessModelInDictionary(getModelResult.Result, args.SubtreesDictionary);
if (result.IsFailure)
{
args.AddError(result.FailureMessage);
return;
}
}
}
public virtual CommandResult ProcessModelInDictionary(BinaryTreeNodeModel node, Dictionary<string, Tree> subtreesDictionary)
{
var getRootResult = GetFromDictionaryOrAdd(subtreesDictionary, node.Root);
if (getRootResult.IsFailure)
{
return CommandResult.Failure(getRootResult.FailureMessage);
}
Tree root = getRootResult.Result;
if (root.Left != null || root.Right != null)
{
return CommandResult.Failure(
String.Format(
ChainedBinaryTreeMessages.DuplicatingEntryWasFound,
node.Root, node.Left, node.Right, root.Left?.Data, root.Right?.Data));
}
CommandResult processLeft = ProcessChild(subtreesDictionary, node.Left, root, BinaryChildrenEnum.Left);
if (processLeft.IsFailure)
{
return CommandResult.Failure(processLeft.FailureMessage);
}
CommandResult processRight = ProcessChild(subtreesDictionary, node.Right, root, BinaryChildrenEnum.Right);
if (processRight.IsFailure)
{
return CommandResult.Failure(processRight.FailureMessage);
}
return CommandResult.Ok();
}
protected virtual CommandResult ProcessChild(Dictionary<string, Tree> subtreesDictionary, string key, Tree root,
BinaryChildrenEnum childrenEnum)
{
if (key == SpecialIndicators.NullNodeIndicator) return CommandResult.Ok();
var dictionaryResult = GetFromDictionaryOrAdd(subtreesDictionary, key);
if (dictionaryResult.IsFailure)
{
return CommandResult.Failure(dictionaryResult.FailureMessage);
}
return root.OverrideNode(dictionaryResult.Result, childrenEnum);
}
protected virtual CommandResult<Tree> GetFromDictionaryOrAdd(Dictionary<string, Tree> subtreesDictionary, string key)
{
if (!subtreesDictionary.ContainsKey(key))
{
var createTreeResult = Tree.Create(key);
if (createTreeResult.IsFailure)
{
return CommandResult<Tree>.Failure(createTreeResult.FailureMessage);
}
subtreesDictionary.Add(key, createTreeResult.Result);
}
return CommandResult.Ok(subtreesDictionary[key]);
}
public override bool CanExecute(BinaryTreeParseArguments args)
{
return args.NodeModels != null && args.SubtreesDictionary != null;
}
}
} | 36.16 | 132 | 0.6026 | [
"Apache-2.0"
] | SergAtGitHub/Solo.BinaryTree | Solo.BinaryTree.Constructor/Parser/ChainedImplementation/Actions/CreateTreeFromParsedValues.cs | 3,618 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the waf-regional-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.WAFRegional.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.WAFRegional.Model.Internal.MarshallTransformations
{
/// <summary>
/// GetIPSet Request Marshaller
/// </summary>
public class GetIPSetRequestMarshaller : IMarshaller<IRequest, GetIPSetRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((GetIPSetRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(GetIPSetRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.WAFRegional");
string target = "AWSWAF_Regional_20161128.GetIPSet";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-11-28";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetIPSetId())
{
context.Writer.WritePropertyName("IPSetId");
context.Writer.Write(publicRequest.IPSetId);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static GetIPSetRequestMarshaller _instance = new GetIPSetRequestMarshaller();
internal static GetIPSetRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetIPSetRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.533333 | 132 | 0.606004 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/WAFRegional/Generated/Model/Internal/MarshallTransformations/GetIPSetRequestMarshaller.cs | 3,731 | C# |
using System;
using System.Collections.Specialized;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
namespace ChannelX.Email
{
public static class QuartzService
{
public static void AddQuartz(this IServiceCollection sc)
{
Task.Run(async () =>
{
try
{
NameValueCollection cfg = new NameValueCollection();
cfg.Add("quartz.scheduler.instanceName", "BulkEmail scheduler");
cfg.Add("quartz.jobStore.type", "Quartz.Simpl.RAMJobStore, Quartz");
cfg.Add("quartz.threadPool.threadCount", Environment.ProcessorCount.ToString());
StdSchedulerFactory factory = new StdSchedulerFactory();
factory.Initialize(cfg);
IScheduler scheduler = await factory.GetScheduler();
scheduler.JobFactory = new IntegrationJobFactory(sc);
// and start it off
await scheduler.Start();
IJobDetail fc = JobBuilder.Create<SendBulkEmail>()
.WithIdentity("SendBulkEmail", "channelx")
.Build();
ITrigger fct = TriggerBuilder.Create()
.WithIdentity("BulkEmailTrigger", "channelx")
.StartNow()
//.StartAt(DateTime.Now.AddMinutes(1))
// .WithCronSchedule("0 22 * * 0") // “At 22:00 on Sunday.”
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(120)
.RepeatForever()
)
.Build();
// Tell quartz to schedule the job using our trigger
var test = await scheduler.ScheduleJob(fc, fct);
}
catch (SchedulerException se)
{
Console.WriteLine(se);
}
});
}
internal sealed class IntegrationJobFactory : IJobFactory
{
private readonly IServiceProvider _container;
public IntegrationJobFactory(IServiceCollection sc)
{
_container = sc.BuildServiceProvider();
}
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
var jobDetail = bundle.JobDetail;
var job = (IJob)_container.GetRequiredService(jobDetail.JobType);
return job;
}
public void ReturnJob(IJob job)
{
}
}
}
} | 37.173333 | 100 | 0.507532 | [
"MIT"
] | lyzerk/ChannelX | src/Email/QuartzService.cs | 2,792 | C# |
using System;
using System.Linq;
using CourierManagement.ApplicationService;
using CourierManagement.Common.Enums;
using CourierManagement.DomainService;
using CourierManagement.Dto;
using CourierManagement.Repository;
using CourierManagement.RequestModels;
using Moq;
using NUnit.Framework;
namespace UnitTest
{
[TestFixture]
public class CartApplicationServiceTest
{
private Mock<IParcelItemSizeDeterminer> _parcelDimensionDeterminerMock;
private CartRepository _cartRepository;
[SetUp]
public void Setup()
{
_parcelDimensionDeterminerMock = new Mock<IParcelItemSizeDeterminer>();
_parcelDimensionDeterminerMock.Setup(m => m.DetermineParcelSize(It.IsAny<AddParcelItemDto>()))
.Returns(new ParcelSizeDimensionPriceInfo(1,1,1, ParcelSize.Small, 1, 2));
_cartRepository = new CartRepository();
}
[Test]
public void AddParcelItem_Should_Successfully_CreateACart_And_AddItemsToIt()
{
//
// Arrange
//
var cartAppSvc = new CartApplicationService(new CartRepository(), _parcelDimensionDeterminerMock.Object, new FixedPriceSettingsRepository());
//
// Act
//
var cartId = cartAppSvc.AddParcelItem(new AddParcelItemRequest
{
SessionId = Guid.NewGuid(),
ItemName = "Test",
Address = "Test Address 1",
Breadth = 9,
Length = 9,
Width = 9
});
var cart = _cartRepository.GetCart(cartId);
//
// Assert
//
Assert.That(cart.Items.Count == 1);
Assert.That(cart.TotalItemCost() == 3);
Assert.That(cart.Items.First().ItemName == "Test");
Assert.That(cart.Items.First().Address == "Test Address 1");
Assert.That(cart.Items.First().FixedDeliveryCost == 3);
}
[Test]
public void AddParcelItem_Should_Successfully_CreateACart_And_AddMultipleItemsToIt_And_TotalCorrect()
{
//
// Arrange
//
var sessionId = Guid.NewGuid();
var cartAppSvc = new CartApplicationService(_cartRepository, _parcelDimensionDeterminerMock.Object, new FixedPriceSettingsRepository());
var item1 = new AddParcelItemRequest
{
SessionId = sessionId,
ItemName = "Test",
Address = "Test Address 1",
Breadth = 9,
Length = 9,
Width = 9
};
var item2 = new AddParcelItemRequest
{
SessionId = sessionId,
ItemName = "Test",
Address = "Test Address 2",
Breadth = 9,
Length = 9,
Width = 9
};
var item3 = new AddParcelItemRequest
{
SessionId = sessionId,
ItemName = "Test",
Address = "Test Address 3",
Breadth = 9,
Length = 9,
Width = 9
};
//
// Act
//
var cartId = cartAppSvc.AddParcelItem(item1);
cartAppSvc.AddParcelItem(item2);
cartAppSvc.AddParcelItem(item3);
var cart = _cartRepository.GetCart(cartId);
//
// Assert
//
Assert.That(cart.Items.Count == 3);
Assert.That(cart.TotalItemCost() == 9);
}
[Test]
[TestCase(DeliveryType.Speed)]
[TestCase(DeliveryType.Normal)]
public void Checkout_Should_Calculate_DeliveryCost_Correctly_Based_OnDeliveryType(DeliveryType deliveryType)
{
//
// Arrange
//
var sessionId = Guid.NewGuid();
var cartAppSvc = new CartApplicationService(_cartRepository, _parcelDimensionDeterminerMock.Object, new FixedPriceSettingsRepository());
var item1 = new AddParcelItemRequest
{
SessionId = sessionId,
ItemName = "Test",
Address = "Test Address 1",
Breadth = 9,
Length = 9,
Width = 9
};
var item2 = new AddParcelItemRequest
{
SessionId = sessionId,
ItemName = "Test",
Address = "Test Address 2",
Breadth = 9,
Length = 9,
Width = 9
};
var item3 = new AddParcelItemRequest
{
SessionId = sessionId,
ItemName = "Test",
Address = "Test Address 3",
Breadth = 9,
Length = 9,
Width = 9
};
//
// Act
//
var cartId = cartAppSvc.AddParcelItem(item1);
cartAppSvc.AddParcelItem(item2);
cartAppSvc.AddParcelItem(item3);
cartAppSvc.Checkout(cartId, deliveryType);
var cart = _cartRepository.GetCart(cartId);
//
// Assert
//
if (deliveryType == DeliveryType.Speed)
{
Assert.That(cart.GetDeliveryCost() == 18);
Assert.That(cart.TotalItemCost() == 9);
}
else
{
Assert.That(cart.GetDeliveryCost() == 0);
}
}
}
}
| 31.322222 | 153 | 0.509578 | [
"Apache-2.0"
] | sachinmani/CourierManagement | UnitTest/CartApplicationServiceTest.cs | 5,640 | C# |
global using HomeAssistantGenerated;
global using NetDaemon.Extensions.Scheduler;
global using NetDaemon.HassModel;
global using NetDaemon.HassModel.Entities;
global using System.Reactive.Linq;
global using System;
global using System.Linq;
global using System.Collections.Generic;
global using Microsoft.Extensions.Logging;
global using NetDaemon.AppModel;
global using Norbert.Apps.Helpers;
global using System.Reactive.Threading.Tasks;
global using System.Reactive.Concurrency; | 36.923077 | 45 | 0.852083 | [
"MIT"
] | FrankBakkerNl/NetDaemonExample | globals.cs | 480 | C# |
using System;
using Nancy;
namespace Starscream.Web.Api.Infrastructure.RestExceptions
{
public class BadRequestExceptionRepackager : IExceptionRepackager
{
#region IExceptionRepackager Members
public ErrorResponse Repackage(Exception exception, NancyContext context, string contentType)
{
return new ErrorResponse(exception.Message, HttpStatusCode.BadRequest, contentType);
}
public bool CanHandle(Exception ex, string contentType)
{
Type type = ex.GetType();
return type.Name.Contains("NotValid");
}
#endregion
}
} | 27.434783 | 101 | 0.673534 | [
"MIT"
] | TMComayagua/WebSite | src/Starscream.Web/Api/Infrastructure/RestExceptions/BadRequestExceptionRepackager.cs | 631 | 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("04. Histogram")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("04. Histogram")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2a2dcd80-18cf-4fbc-a482-faa150e90594")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.675676 | 84 | 0.745337 | [
"MIT"
] | bobo4aces/01.SoftUni-ProgramingBasics | 99. Exams/2016.03.06/04. Histogram/Properties/AssemblyInfo.cs | 1,397 | 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Structure;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class NamespaceDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<NamespaceDeclarationSyntax>
{
protected override void CollectBlockSpans(
NamespaceDeclarationSyntax namespaceDeclaration,
ArrayBuilder<BlockSpan> spans,
bool isMetadataAsSource,
OptionSet options,
CancellationToken cancellationToken)
{
// add leading comments
CSharpStructureHelpers.CollectCommentBlockSpans(namespaceDeclaration, spans, isMetadataAsSource);
if (!namespaceDeclaration.OpenBraceToken.IsMissing &&
!namespaceDeclaration.CloseBraceToken.IsMissing)
{
spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan(
namespaceDeclaration,
namespaceDeclaration.Name.GetLastToken(includeZeroWidth: true),
compressEmptyLines: false,
autoCollapse: false,
type: BlockTypes.Namespace,
isCollapsible: true));
}
// extern aliases and usings are outlined in a single region
var externsAndUsings = Enumerable.Union<SyntaxNode>(namespaceDeclaration.Externs, namespaceDeclaration.Usings)
.OrderBy(node => node.SpanStart)
.ToList();
// add any leading comments before the extern aliases and usings
if (externsAndUsings.Count > 0)
{
CSharpStructureHelpers.CollectCommentBlockSpans(externsAndUsings.First(), spans, isMetadataAsSource);
}
spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan(
externsAndUsings, compressEmptyLines: true, autoCollapse: true,
type: BlockTypes.Imports, isCollapsible: true));
// finally, add any leading comments before the end of the namespace block
if (!namespaceDeclaration.CloseBraceToken.IsMissing)
{
CSharpStructureHelpers.CollectCommentBlockSpans(
namespaceDeclaration.CloseBraceToken.LeadingTrivia, spans);
}
}
}
}
| 43.741935 | 122 | 0.653024 | [
"MIT"
] | BertanAygun/roslyn | src/Features/CSharp/Portable/Structure/Providers/NamespaceDeclarationStructureProvider.cs | 2,714 | C# |
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.LanguageServer.Protocol;
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
using OmniSharp.Extensions.LanguageServer.Protocol.Document;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities;
using OmniSharp.Models;
using OmniSharp.Models.FileClose;
using OmniSharp.Models.FileOpen;
using OmniSharp.Models.UpdateBuffer;
namespace OmniSharp.LanguageServerProtocol.Handlers
{
class OmniSharpTextDocumentSyncHandler : TextDocumentSyncHandler
{
public static IEnumerable<IJsonRpcHandler> Enumerate(
RequestHandlers handlers,
OmniSharpWorkspace workspace,
DocumentVersions documentVersions)
{
foreach (var (selector, openHandler, closeHandler, bufferHandler) in handlers
.OfType<
Mef.IRequestHandler<FileOpenRequest, FileOpenResponse>,
Mef.IRequestHandler<FileCloseRequest, FileCloseResponse>,
Mef.IRequestHandler<UpdateBufferRequest, object>>())
{
// TODO: Fix once cake has working support for incremental
var documentSyncKind = TextDocumentSyncKind.Incremental;
if (selector.ToString().IndexOf(".cake") > -1) documentSyncKind = TextDocumentSyncKind.Full;
yield return new OmniSharpTextDocumentSyncHandler(openHandler, closeHandler, bufferHandler, selector, documentSyncKind, workspace, documentVersions);
}
}
// TODO Make this configurable?
private readonly Mef.IRequestHandler<FileOpenRequest, FileOpenResponse> _openHandler;
private readonly Mef.IRequestHandler<FileCloseRequest, FileCloseResponse> _closeHandler;
private readonly Mef.IRequestHandler<UpdateBufferRequest, object> _bufferHandler;
private readonly OmniSharpWorkspace _workspace;
private readonly DocumentVersions _documentVersions;
public OmniSharpTextDocumentSyncHandler(
Mef.IRequestHandler<FileOpenRequest, FileOpenResponse> openHandler,
Mef.IRequestHandler<FileCloseRequest, FileCloseResponse> closeHandler,
Mef.IRequestHandler<UpdateBufferRequest, object> bufferHandler,
DocumentSelector documentSelector,
TextDocumentSyncKind documentSyncKind,
OmniSharpWorkspace workspace,
DocumentVersions documentVersions)
: base(documentSyncKind, new TextDocumentSaveRegistrationOptions()
{
DocumentSelector = documentSelector,
IncludeText = true,
})
{
_openHandler = openHandler;
_closeHandler = closeHandler;
_bufferHandler = bufferHandler;
_workspace = workspace;
_documentVersions = documentVersions;
}
public override TextDocumentAttributes GetTextDocumentAttributes(DocumentUri uri)
{
var document = _workspace.GetDocument(Helpers.FromUri(uri));
var langaugeId = "csharp";
if (document == null) return new TextDocumentAttributes(uri, uri.Scheme, langaugeId);
return new TextDocumentAttributes(uri, uri.Scheme, langaugeId);
}
public async override Task<Unit> Handle(DidChangeTextDocumentParams notification, CancellationToken cancellationToken)
{
if (notification.ContentChanges == null)
{
return Unit.Value;
}
var contentChanges = notification.ContentChanges.ToArray();
if (contentChanges.Length == 1 && contentChanges[0].Range == null)
{
var change = contentChanges[0];
await _bufferHandler.Handle(new UpdateBufferRequest()
{
FileName = Helpers.FromUri(notification.TextDocument.Uri),
Buffer = change.Text
});
return Unit.Value;
}
var changes = contentChanges
.Select(change => new LinePositionSpanTextChange()
{
NewText = change.Text,
StartColumn = Convert.ToInt32(change.Range.Start.Character),
StartLine = Convert.ToInt32(change.Range.Start.Line),
EndColumn = Convert.ToInt32(change.Range.End.Character),
EndLine = Convert.ToInt32(change.Range.End.Line),
})
.ToArray();
await _bufferHandler.Handle(new UpdateBufferRequest()
{
FileName = Helpers.FromUri(notification.TextDocument.Uri),
Changes = changes
});
_documentVersions.Update(notification.TextDocument);
return Unit.Value;
}
public async override Task<Unit> Handle(DidOpenTextDocumentParams notification, CancellationToken cancellationToken)
{
if (_openHandler != null)
{
await _openHandler.Handle(new FileOpenRequest()
{
Buffer = notification.TextDocument.Text,
FileName = Helpers.FromUri(notification.TextDocument.Uri)
});
_documentVersions.Reset(notification.TextDocument);
}
return Unit.Value;
}
public async override Task<Unit> Handle(DidCloseTextDocumentParams notification, CancellationToken cancellationToken)
{
if (_closeHandler != null)
{
await _closeHandler.Handle(new FileCloseRequest()
{
FileName = Helpers.FromUri(notification.TextDocument.Uri)
});
_documentVersions.Remove(notification.TextDocument);
}
return Unit.Value;
}
public async override Task<Unit> Handle(DidSaveTextDocumentParams notification, CancellationToken cancellationToken)
{
if (Capability?.DidSave == true)
{
await _bufferHandler.Handle(new UpdateBufferRequest()
{
FileName = Helpers.FromUri(notification.TextDocument.Uri),
Buffer = notification.Text
});
_documentVersions.Reset(notification.TextDocument);
}
return Unit.Value;
}
}
}
| 40.753012 | 165 | 0.630451 | [
"MIT"
] | Samirat/omnisharp-roslyn | src/OmniSharp.LanguageServerProtocol/Handlers/OmniSharpTextDocumentSyncHandler.cs | 6,765 | C# |
namespace BlueprintDeck.Instance.Factory
{
public interface IBlueprintFactory
{
IBlueprintInstance CreateBlueprint(Design.Blueprint design);
}
} | 23.428571 | 68 | 0.75 | [
"MIT"
] | MauriceH/BlueprintDeck | source/BlueprintDeck.Core/Instance/Factory/IBlueprintFactory.cs | 164 | C# |
#region License
/*
MIT License
Copyright(c) 2021 Petteri Kautonen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using VPKSoft.ErrorLogger;
namespace ScriptNotepad.UtilityClasses.CodeDom
{
/// <summary>
/// A class to run C# script snippets a file contents as line strings with line endings.
/// </summary>
/// <seealso cref="RoslynScriptRunner" />
public class CsCodeDomScriptRunnerLines: IScriptRunner
{
/// <summary>
/// Initializes a new instance of the <see cref="CsCodeDomScriptRunnerLines"/> class.
/// </summary>
public CsCodeDomScriptRunnerLines()
{
CSharpScriptBase =
string.Join(Environment.NewLine,
// ReSharper disable once StringLiteralTypo
"#region Usings",
"using System;",
"using System.Linq;",
"using System.Collections;",
"using System.Collections.Generic;",
"using System.Text;",
"using System.Text.RegularExpressions;",
"using System.Xml.Linq;",
"#endregion",
Environment.NewLine,
"public class ManipulateLineLines",
"{",
" public static string Evaluate(List<string> fileLines)",
" {",
" string result = string.Empty;",
" // insert code here..",
" for (int i = 0; i < fileLines.Count; i++)",
" {",
" // A sample: fileLines[i] = fileLines[i]; // NOTE: Line manipulation must be added..",
" }",
string.Empty,
" result = string.Concat(fileLines); // concatenate the result lines.. ",
" return result;",
" }",
"}");
ScriptCode = CSharpScriptBase;
}
/// <summary>
/// Runs the C# script against the given lines and returns the concatenated lines as a string.
/// <note type="note">The line strings may contain various different line endings.</note>
/// </summary>
/// <param name="fileLines">The file lines to run the C# script against.</param>
/// <returns>A <see cref="KeyValuePair{TKey,TValue}"/> containing the file contents after the script manipulation and a boolean value indicating whether the script execution succeeded.</returns>
public async Task<KeyValuePair<string, bool>> ExecuteLinesAsync(List<string> fileLines)
{
try
{
CompileException = null;
ScriptRunner = new RoslynScriptRunner(new RoslynGlobals<List<string>> {DataVariable = fileLines});
await ScriptRunner.ExecuteAsync(ScriptCode);
// try to run the C# script against the given file lines..
object result = await ScriptRunner.ExecuteAsync("ManipulateLineLines.Evaluate(DataVariable)");
if (result is Exception exception)
{
throw exception;
}
CompileFailed = false;
return new KeyValuePair<string, bool>(result as string, true); // indicate a success..
}
catch (Exception ex)
{
CompileException = ScriptRunner?.PreviousCompileException;
CompileFailed = true;
ExceptionLogger.LogError(ex);
// fail..
return new KeyValuePair<string, bool>(string.Concat(fileLines), false);
}
}
/// <summary>
/// Gets or sets the C# script runner.
/// </summary>
/// <value>The C# script runner.</value>
public RoslynScriptRunner ScriptRunner { get; set; }
/// <summary>
/// Gets or sets the base "skeleton" C# code snippet for manipulating text.
/// </summary>
/// <value>The base "skeleton" C# code snippet for manipulating text.</value>
public string CSharpScriptBase { get; set; }
/// <summary>
/// Gets or sets the C# script code.
/// </summary>
/// <value>The C# script code.</value>
public string ScriptCode { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the script compile failed.
/// </summary>
/// <value><c>true</c> if the script compile failed; otherwise, <c>false</c>.</value>
public bool CompileFailed { get; set; }
/// <summary>
/// Gets the previous compile exception.
/// </summary>
/// <value>The previous compile exception.</value>
public Exception CompileException { get; set; }
/// <summary>
/// Executes the script.
/// </summary>
/// <param name="text">The text in some format.</param>
/// <returns>The object containing the manipulated text if the operation was successful.</returns>
public async Task<object> ExecuteScript(object text)
{
return await ExecuteLinesAsync((List<string>) text);
}
}
}
| 41.929487 | 203 | 0.567192 | [
"MIT"
] | VPKSoft/ScriptNotepad | ScriptNotepad/UtilityClasses/CodeDom/CSCodeDOMScriptRunnerLines.cs | 6,543 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Request the system level data associated with Enhanced Call Logs.
/// The response is either a SystemEnhancedCallLogsGetResponse or an ErrorResponse.
/// <see cref="SystemEnhancedCallLogsGetResponse"/>
/// <see cref="ErrorResponse"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""ab0042aa512abc10edb3c55e4b416b0b:26446""}]")]
public class SystemEnhancedCallLogsGetRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest
{
}
}
| 33.25 | 131 | 0.733083 | [
"MIT"
] | Rogn/broadworks-connector-net | BroadworksConnector/Ocip/Models/SystemEnhancedCallLogsGetRequest.cs | 798 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void TransposeEven_Vector128_Int64()
{
var test = new SimpleBinaryOpTest__TransposeEven_Vector128_Int64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__TransposeEven_Vector128_Int64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int64> _fld1;
public Vector128<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__TransposeEven_Vector128_Int64 testClass)
{
var result = AdvSimd.Arm64.TransposeEven(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__TransposeEven_Vector128_Int64 testClass)
{
fixed (Vector128<Int64>* pFld1 = &_fld1)
fixed (Vector128<Int64>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.TransposeEven(
AdvSimd.LoadVector128((Int64*)(pFld1)),
AdvSimd.LoadVector128((Int64*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int64[] _data2 = new Int64[Op2ElementCount];
private static Vector128<Int64> _clsVar1;
private static Vector128<Int64> _clsVar2;
private Vector128<Int64> _fld1;
private Vector128<Int64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__TransposeEven_Vector128_Int64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
}
public SimpleBinaryOpTest__TransposeEven_Vector128_Int64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.TransposeEven(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.TransposeEven(
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.TransposeEven), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.TransposeEven), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.TransposeEven(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int64>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int64>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Arm64.TransposeEven(
AdvSimd.LoadVector128((Int64*)(pClsVar1)),
AdvSimd.LoadVector128((Int64*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Arm64.TransposeEven(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Arm64.TransposeEven(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__TransposeEven_Vector128_Int64();
var result = AdvSimd.Arm64.TransposeEven(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__TransposeEven_Vector128_Int64();
fixed (Vector128<Int64>* pFld1 = &test._fld1)
fixed (Vector128<Int64>* pFld2 = &test._fld2)
{
var result = AdvSimd.Arm64.TransposeEven(
AdvSimd.LoadVector128((Int64*)(pFld1)),
AdvSimd.LoadVector128((Int64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.TransposeEven(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int64>* pFld1 = &_fld1)
fixed (Vector128<Int64>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.TransposeEven(
AdvSimd.LoadVector128((Int64*)(pFld1)),
AdvSimd.LoadVector128((Int64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.TransposeEven(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.TransposeEven(
AdvSimd.LoadVector128((Int64*)(&test._fld1)),
AdvSimd.LoadVector128((Int64*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int64> op1, Vector128<Int64> op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
int index = 0;
int half = RetElementCount / 2;
for (var i = 0; i < RetElementCount; i+=2, index++)
{
if (result[index] != left[i] || result[++index] != right[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.TransposeEven)}<Int64>(Vector128<Int64>, Vector128<Int64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 42.440075 | 187 | 0.58611 | [
"MIT"
] | 06needhamt/runtime | src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/TransposeEven.Vector128.Int64.cs | 22,663 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codestar-connections-2019-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Net;
using Amazon.CodeStarconnections.Model;
using Amazon.CodeStarconnections.Model.Internal.MarshallTransformations;
using Amazon.CodeStarconnections.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.CodeStarconnections
{
/// <summary>
/// Implementation for accessing CodeStarconnections
///
/// AWS CodeStar Connections <important>
/// <para>
/// The CodeStar Connections feature is in preview release and is subject to change.
/// </para>
/// </important>
/// <para>
/// This AWS CodeStar Connections API Reference provides descriptions and usage examples
/// of the operations and data types for the AWS CodeStar Connections API. You can use
/// the connections API to work with connections and installations.
/// </para>
///
/// <para>
/// <i>Connections</i> are configurations that you use to connect AWS resources to external
/// code repositories. Each connection is a resource that can be given to services such
/// as CodePipeline to connect to a third-party repository such as Bitbucket. For example,
/// you can add the connection in CodePipeline so that it triggers your pipeline when
/// a code change is made to your third-party code repository. Each connection is named
/// and associated with a unique ARN that is used to reference the connection.
/// </para>
///
/// <para>
/// When you create a connection, the console initiates a third-party connection handshake.
/// <i>Installations</i> are the apps that are used to conduct this handshake. For example,
/// the installation for the Bitbucket provider type is the Bitbucket Cloud app. When
/// you create a connection, you can choose an existing installation or create one.
/// </para>
///
/// <para>
/// When you want to create a connection to an installed provider type such as GitHub
/// Enterprise Server, you create a <i>host</i> for your connections.
/// </para>
///
/// <para>
/// You can work with connections by calling:
/// </para>
/// <ul> <li>
/// <para>
/// <a>CreateConnection</a>, which creates a uniquely named connection that can be referenced
/// by services such as CodePipeline.
/// </para>
/// </li> <li>
/// <para>
/// <a>DeleteConnection</a>, which deletes the specified connection.
/// </para>
/// </li> <li>
/// <para>
/// <a>GetConnection</a>, which returns information about the connection, including the
/// connection status.
/// </para>
/// </li> <li>
/// <para>
/// <a>ListConnections</a>, which lists the connections associated with your account.
/// </para>
/// </li> </ul>
/// <para>
/// You can work with hosts by calling:
/// </para>
/// <ul> <li>
/// <para>
/// <a>CreateHost</a>, which creates a host that represents the infrastructure where
/// your provider is installed.
/// </para>
/// </li> <li>
/// <para>
/// <a>DeleteHost</a>, which deletes the specified host.
/// </para>
/// </li> <li>
/// <para>
/// <a>GetHost</a>, which returns information about the host, including the setup status.
/// </para>
/// </li> <li>
/// <para>
/// <a>ListHosts</a>, which lists the hosts associated with your account.
/// </para>
/// </li> </ul>
/// <para>
/// You can work with tags in AWS CodeStar Connections by calling the following:
/// </para>
/// <ul> <li>
/// <para>
/// <a>ListTagsForResource</a>, which gets information about AWS tags for a specified
/// Amazon Resource Name (ARN) in AWS CodeStar Connections.
/// </para>
/// </li> <li>
/// <para>
/// <a>TagResource</a>, which adds or updates tags for a resource in AWS CodeStar Connections.
/// </para>
/// </li> <li>
/// <para>
/// <a>UntagResource</a>, which removes tags for a resource in AWS CodeStar Connections.
/// </para>
/// </li> </ul>
/// <para>
/// For information about how to use AWS CodeStar Connections, see the <a href="https://docs.aws.amazon.com/dtconsole/latest/userguide/welcome-connections.html">Developer
/// Tools User Guide</a>.
/// </para>
/// </summary>
public partial class AmazonCodeStarconnectionsClient : AmazonServiceClient, IAmazonCodeStarconnections
{
private static IServiceMetadata serviceMetadata = new AmazonCodeStarconnectionsMetadata();
#region Constructors
/// <summary>
/// Constructs AmazonCodeStarconnectionsClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonCodeStarconnectionsClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonCodeStarconnectionsConfig()) { }
/// <summary>
/// Constructs AmazonCodeStarconnectionsClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonCodeStarconnectionsClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonCodeStarconnectionsConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonCodeStarconnectionsClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonCodeStarconnectionsClient Configuration Object</param>
public AmazonCodeStarconnectionsClient(AmazonCodeStarconnectionsConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonCodeStarconnectionsClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonCodeStarconnectionsClient(AWSCredentials credentials)
: this(credentials, new AmazonCodeStarconnectionsConfig())
{
}
/// <summary>
/// Constructs AmazonCodeStarconnectionsClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonCodeStarconnectionsClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonCodeStarconnectionsConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCodeStarconnectionsClient with AWS Credentials and an
/// AmazonCodeStarconnectionsClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonCodeStarconnectionsClient Configuration Object</param>
public AmazonCodeStarconnectionsClient(AWSCredentials credentials, AmazonCodeStarconnectionsConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCodeStarconnectionsClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonCodeStarconnectionsClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCodeStarconnectionsConfig())
{
}
/// <summary>
/// Constructs AmazonCodeStarconnectionsClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonCodeStarconnectionsClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCodeStarconnectionsConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonCodeStarconnectionsClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCodeStarconnectionsClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonCodeStarconnectionsClient Configuration Object</param>
public AmazonCodeStarconnectionsClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCodeStarconnectionsConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCodeStarconnectionsClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonCodeStarconnectionsClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCodeStarconnectionsConfig())
{
}
/// <summary>
/// Constructs AmazonCodeStarconnectionsClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonCodeStarconnectionsClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCodeStarconnectionsConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCodeStarconnectionsClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCodeStarconnectionsClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonCodeStarconnectionsClient Configuration Object</param>
public AmazonCodeStarconnectionsClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonCodeStarconnectionsConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region CreateConnection
/// <summary>
/// Creates a connection that can then be given to other AWS services like CodePipeline
/// so that it can access third-party code repositories. The connection is in pending
/// status until the third-party connection handshake is completed from the console.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateConnection service method.</param>
///
/// <returns>The response from the CreateConnection service method, as returned by CodeStarconnections.</returns>
/// <exception cref="Amazon.CodeStarconnections.Model.LimitExceededException">
/// Exceeded the maximum limit for connections.
/// </exception>
/// <exception cref="Amazon.CodeStarconnections.Model.ResourceNotFoundException">
/// Resource not found. Verify the connection resource ARN and try again.
/// </exception>
/// <exception cref="Amazon.CodeStarconnections.Model.ResourceUnavailableException">
/// Resource not found. Verify the ARN for the host resource and try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/CreateConnection">REST API Reference for CreateConnection Operation</seealso>
public virtual CreateConnectionResponse CreateConnection(CreateConnectionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateConnectionResponseUnmarshaller.Instance;
return Invoke<CreateConnectionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateConnection operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateConnection operation on AmazonCodeStarconnectionsClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateConnection
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/CreateConnection">REST API Reference for CreateConnection Operation</seealso>
public virtual IAsyncResult BeginCreateConnection(CreateConnectionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateConnectionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateConnection operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateConnection.</param>
///
/// <returns>Returns a CreateConnectionResult from CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/CreateConnection">REST API Reference for CreateConnection Operation</seealso>
public virtual CreateConnectionResponse EndCreateConnection(IAsyncResult asyncResult)
{
return EndInvoke<CreateConnectionResponse>(asyncResult);
}
#endregion
#region CreateHost
/// <summary>
/// Creates a resource that represents the infrastructure where a third-party provider
/// is installed. The host is used when you create connections to an installed third-party
/// provider type, such as GitHub Enterprise Server. You create one host for all connections
/// to that provider.
///
/// <note>
/// <para>
/// A host created through the CLI or the SDK is in `PENDING` status by default. You can
/// make its status `AVAILABLE` by setting up the host in the console.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateHost service method.</param>
///
/// <returns>The response from the CreateHost service method, as returned by CodeStarconnections.</returns>
/// <exception cref="Amazon.CodeStarconnections.Model.LimitExceededException">
/// Exceeded the maximum limit for connections.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/CreateHost">REST API Reference for CreateHost Operation</seealso>
public virtual CreateHostResponse CreateHost(CreateHostRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateHostRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateHostResponseUnmarshaller.Instance;
return Invoke<CreateHostResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateHost operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateHost operation on AmazonCodeStarconnectionsClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateHost
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/CreateHost">REST API Reference for CreateHost Operation</seealso>
public virtual IAsyncResult BeginCreateHost(CreateHostRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateHostRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateHostResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateHost operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateHost.</param>
///
/// <returns>Returns a CreateHostResult from CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/CreateHost">REST API Reference for CreateHost Operation</seealso>
public virtual CreateHostResponse EndCreateHost(IAsyncResult asyncResult)
{
return EndInvoke<CreateHostResponse>(asyncResult);
}
#endregion
#region DeleteConnection
/// <summary>
/// The connection to be deleted.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteConnection service method.</param>
///
/// <returns>The response from the DeleteConnection service method, as returned by CodeStarconnections.</returns>
/// <exception cref="Amazon.CodeStarconnections.Model.ResourceNotFoundException">
/// Resource not found. Verify the connection resource ARN and try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/DeleteConnection">REST API Reference for DeleteConnection Operation</seealso>
public virtual DeleteConnectionResponse DeleteConnection(DeleteConnectionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteConnectionResponseUnmarshaller.Instance;
return Invoke<DeleteConnectionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteConnection operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteConnection operation on AmazonCodeStarconnectionsClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteConnection
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/DeleteConnection">REST API Reference for DeleteConnection Operation</seealso>
public virtual IAsyncResult BeginDeleteConnection(DeleteConnectionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteConnectionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteConnection operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteConnection.</param>
///
/// <returns>Returns a DeleteConnectionResult from CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/DeleteConnection">REST API Reference for DeleteConnection Operation</seealso>
public virtual DeleteConnectionResponse EndDeleteConnection(IAsyncResult asyncResult)
{
return EndInvoke<DeleteConnectionResponse>(asyncResult);
}
#endregion
#region DeleteHost
/// <summary>
/// The host to be deleted. Before you delete a host, all connections associated to the
/// host must be deleted.
///
/// <note>
/// <para>
/// A host cannot be deleted if it is in the VPC_CONFIG_INITIALIZING or VPC_CONFIG_DELETING
/// state.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteHost service method.</param>
///
/// <returns>The response from the DeleteHost service method, as returned by CodeStarconnections.</returns>
/// <exception cref="Amazon.CodeStarconnections.Model.ResourceNotFoundException">
/// Resource not found. Verify the connection resource ARN and try again.
/// </exception>
/// <exception cref="Amazon.CodeStarconnections.Model.ResourceUnavailableException">
/// Resource not found. Verify the ARN for the host resource and try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/DeleteHost">REST API Reference for DeleteHost Operation</seealso>
public virtual DeleteHostResponse DeleteHost(DeleteHostRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteHostRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteHostResponseUnmarshaller.Instance;
return Invoke<DeleteHostResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteHost operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteHost operation on AmazonCodeStarconnectionsClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteHost
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/DeleteHost">REST API Reference for DeleteHost Operation</seealso>
public virtual IAsyncResult BeginDeleteHost(DeleteHostRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteHostRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteHostResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteHost operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteHost.</param>
///
/// <returns>Returns a DeleteHostResult from CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/DeleteHost">REST API Reference for DeleteHost Operation</seealso>
public virtual DeleteHostResponse EndDeleteHost(IAsyncResult asyncResult)
{
return EndInvoke<DeleteHostResponse>(asyncResult);
}
#endregion
#region GetConnection
/// <summary>
/// Returns the connection ARN and details such as status, owner, and provider type.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetConnection service method.</param>
///
/// <returns>The response from the GetConnection service method, as returned by CodeStarconnections.</returns>
/// <exception cref="Amazon.CodeStarconnections.Model.ResourceNotFoundException">
/// Resource not found. Verify the connection resource ARN and try again.
/// </exception>
/// <exception cref="Amazon.CodeStarconnections.Model.ResourceUnavailableException">
/// Resource not found. Verify the ARN for the host resource and try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/GetConnection">REST API Reference for GetConnection Operation</seealso>
public virtual GetConnectionResponse GetConnection(GetConnectionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetConnectionResponseUnmarshaller.Instance;
return Invoke<GetConnectionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetConnection operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetConnection operation on AmazonCodeStarconnectionsClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetConnection
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/GetConnection">REST API Reference for GetConnection Operation</seealso>
public virtual IAsyncResult BeginGetConnection(GetConnectionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetConnectionRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetConnectionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetConnection operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetConnection.</param>
///
/// <returns>Returns a GetConnectionResult from CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/GetConnection">REST API Reference for GetConnection Operation</seealso>
public virtual GetConnectionResponse EndGetConnection(IAsyncResult asyncResult)
{
return EndInvoke<GetConnectionResponse>(asyncResult);
}
#endregion
#region GetHost
/// <summary>
/// Returns the host ARN and details such as status, provider type, endpoint, and, if
/// applicable, the VPC configuration.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetHost service method.</param>
///
/// <returns>The response from the GetHost service method, as returned by CodeStarconnections.</returns>
/// <exception cref="Amazon.CodeStarconnections.Model.ResourceNotFoundException">
/// Resource not found. Verify the connection resource ARN and try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/GetHost">REST API Reference for GetHost Operation</seealso>
public virtual GetHostResponse GetHost(GetHostRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetHostRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetHostResponseUnmarshaller.Instance;
return Invoke<GetHostResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetHost operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetHost operation on AmazonCodeStarconnectionsClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetHost
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/GetHost">REST API Reference for GetHost Operation</seealso>
public virtual IAsyncResult BeginGetHost(GetHostRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetHostRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetHostResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetHost operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetHost.</param>
///
/// <returns>Returns a GetHostResult from CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/GetHost">REST API Reference for GetHost Operation</seealso>
public virtual GetHostResponse EndGetHost(IAsyncResult asyncResult)
{
return EndInvoke<GetHostResponse>(asyncResult);
}
#endregion
#region ListConnections
/// <summary>
/// Lists the connections associated with your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListConnections service method.</param>
///
/// <returns>The response from the ListConnections service method, as returned by CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/ListConnections">REST API Reference for ListConnections Operation</seealso>
public virtual ListConnectionsResponse ListConnections(ListConnectionsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListConnectionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListConnectionsResponseUnmarshaller.Instance;
return Invoke<ListConnectionsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListConnections operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListConnections operation on AmazonCodeStarconnectionsClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListConnections
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/ListConnections">REST API Reference for ListConnections Operation</seealso>
public virtual IAsyncResult BeginListConnections(ListConnectionsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListConnectionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListConnectionsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListConnections operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListConnections.</param>
///
/// <returns>Returns a ListConnectionsResult from CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/ListConnections">REST API Reference for ListConnections Operation</seealso>
public virtual ListConnectionsResponse EndListConnections(IAsyncResult asyncResult)
{
return EndInvoke<ListConnectionsResponse>(asyncResult);
}
#endregion
#region ListHosts
/// <summary>
/// Lists the hosts associated with your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListHosts service method.</param>
///
/// <returns>The response from the ListHosts service method, as returned by CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/ListHosts">REST API Reference for ListHosts Operation</seealso>
public virtual ListHostsResponse ListHosts(ListHostsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListHostsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListHostsResponseUnmarshaller.Instance;
return Invoke<ListHostsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListHosts operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListHosts operation on AmazonCodeStarconnectionsClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListHosts
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/ListHosts">REST API Reference for ListHosts Operation</seealso>
public virtual IAsyncResult BeginListHosts(ListHostsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListHostsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListHostsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListHosts operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListHosts.</param>
///
/// <returns>Returns a ListHostsResult from CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/ListHosts">REST API Reference for ListHosts Operation</seealso>
public virtual ListHostsResponse EndListHosts(IAsyncResult asyncResult)
{
return EndInvoke<ListHostsResponse>(asyncResult);
}
#endregion
#region ListTagsForResource
/// <summary>
/// Gets the set of key-value pairs (metadata) that are used to manage the resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param>
///
/// <returns>The response from the ListTagsForResource service method, as returned by CodeStarconnections.</returns>
/// <exception cref="Amazon.CodeStarconnections.Model.ResourceNotFoundException">
/// Resource not found. Verify the connection resource ARN and try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return Invoke<ListTagsForResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource operation on AmazonCodeStarconnectionsClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTagsForResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual IAsyncResult BeginListTagsForResource(ListTagsForResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTagsForResource.</param>
///
/// <returns>Returns a ListTagsForResourceResult from CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual ListTagsForResourceResponse EndListTagsForResource(IAsyncResult asyncResult)
{
return EndInvoke<ListTagsForResourceResponse>(asyncResult);
}
#endregion
#region TagResource
/// <summary>
/// Adds to or modifies the tags of the given resource. Tags are metadata that can be
/// used to manage a resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
///
/// <returns>The response from the TagResource service method, as returned by CodeStarconnections.</returns>
/// <exception cref="Amazon.CodeStarconnections.Model.LimitExceededException">
/// Exceeded the maximum limit for connections.
/// </exception>
/// <exception cref="Amazon.CodeStarconnections.Model.ResourceNotFoundException">
/// Resource not found. Verify the connection resource ARN and try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual TagResourceResponse TagResource(TagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return Invoke<TagResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the TagResource operation on AmazonCodeStarconnectionsClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual IAsyncResult BeginTagResource(TagResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginTagResource.</param>
///
/// <returns>Returns a TagResourceResult from CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual TagResourceResponse EndTagResource(IAsyncResult asyncResult)
{
return EndInvoke<TagResourceResponse>(asyncResult);
}
#endregion
#region UntagResource
/// <summary>
/// Removes tags from an AWS resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
///
/// <returns>The response from the UntagResource service method, as returned by CodeStarconnections.</returns>
/// <exception cref="Amazon.CodeStarconnections.Model.ResourceNotFoundException">
/// Resource not found. Verify the connection resource ARN and try again.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual UntagResourceResponse UntagResource(UntagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return Invoke<UntagResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UntagResource operation on AmazonCodeStarconnectionsClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUntagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual IAsyncResult BeginUntagResource(UntagResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUntagResource.</param>
///
/// <returns>Returns a UntagResourceResult from CodeStarconnections.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual UntagResourceResponse EndUntagResource(IAsyncResult asyncResult)
{
return EndInvoke<UntagResourceResponse>(asyncResult);
}
#endregion
}
} | 52.424547 | 181 | 0.667684 | [
"Apache-2.0"
] | Singh400/aws-sdk-net | sdk/src/Services/CodeStarconnections/Generated/_bcl35/AmazonCodeStarconnectionsClient.cs | 52,110 | C# |
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace AzureFunctionsSample.DependencyInjection
{
public class ImportantFunctions
{
private readonly HttpClient http;
public ImportantFunctions(HttpClient http)
{
this.http = http;
}
[FunctionName("DoImportantWork")]
public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = "website")] HttpRequest req, ILogger log)
{
log.LogInformation("Doing important work...");
var url = req.Query["url"];
log.LogDebug($"GET'ing {url}...");
var response = await http.GetAsync(url);
if(response.IsSuccessStatusCode)
log.LogInformation($"All good, got success status code when querying {url}.");
else
log.LogWarning($"Got HTTP response: {response.StatusCode} when querying url: {url}.");
return new OkResult();
}
}
}
| 31.972973 | 143 | 0.64328 | [
"MIT"
] | proxus-consulting/azure-function-samples | AzureFunctionsSample.DependencyInjection/ImportantFunctions.cs | 1,183 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Maui.DeviceTests.Stubs;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Handlers;
using Xunit;
using AColor = Android.Graphics.Color;
namespace Microsoft.Maui.DeviceTests
{
public partial class TimePickerHandlerTests
{
[Fact(DisplayName = "CharacterSpacing Initializes Correctly")]
public async Task CharacterSpacingInitializesCorrectly()
{
var xplatCharacterSpacing = 4;
var timePicker = new TimePickerStub()
{
CharacterSpacing = xplatCharacterSpacing,
Time = TimeSpan.FromHours(8)
};
float expectedValue = timePicker.CharacterSpacing.ToEm();
var values = await GetValueAsync(timePicker, (handler) =>
{
return new
{
ViewValue = timePicker.CharacterSpacing,
NativeViewValue = GetNativeCharacterSpacing(handler)
};
});
Assert.Equal(xplatCharacterSpacing, values.ViewValue);
Assert.Equal(expectedValue, values.NativeViewValue, EmCoefficientPrecision);
}
MauiTimePicker GetNativeTimePicker(TimePickerHandler timePickerHandler) =>
(MauiTimePicker)timePickerHandler.NativeView;
async Task ValidateTime(ITimePicker timePickerStub, Action action = null)
{
var actual = await GetValueAsync(timePickerStub, handler =>
{
var native = GetNativeTimePicker(handler);
action?.Invoke();
return native.Text;
});
var expected = timePickerStub.ToFormattedString();
Assert.Equal(actual, expected);
}
double GetNativeCharacterSpacing(TimePickerHandler timePickerHandler)
{
var mauiTimePicker = GetNativeTimePicker(timePickerHandler);
if (mauiTimePicker != null)
{
return mauiTimePicker.LetterSpacing;
}
return -1;
}
Color GetNativeTextColor(TimePickerHandler timePickerHandler)
{
int currentTextColorInt = GetNativeTimePicker(timePickerHandler).CurrentTextColor;
AColor currentTextColor = new AColor(currentTextColorInt);
return currentTextColor.ToColor();
}
}
} | 26.539474 | 85 | 0.757561 | [
"MIT"
] | 3DSX/maui | src/Core/tests/DeviceTests/Handlers/TimePicker/TimePickerHandlerTests.Android.cs | 2,019 | C# |
namespace Rebus.SqlServer.Tests
{
public class Categories
{
public const string SqlServer = "sqlserver";
public const string Msmq = "msmq";
public const string Filesystem = "filesystem";
}
} | 25.222222 | 54 | 0.643172 | [
"MIT"
] | DigitecGalaxus/Rebus.SqlServer | Rebus.SqlServer.Tests/Categories.cs | 229 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace P03_FootballBetting.Data.Models
{
public class Color
{
public int ColorId { get; set; }
public string Name { get; set; }
[InverseProperty("PrimaryKitColor")]
public virtual ICollection<Team> PrimaryKitTeams { get; set; } = new List<Team>();
[InverseProperty("SecondaryKitColor")]
public virtual ICollection<Team> SecondaryKitTeams { get; set; } = new List<Team>();
}
}
| 26.809524 | 92 | 0.680284 | [
"MIT"
] | aalishov/SoftUni | 06-Entity-Framework-Core-June-2020/S10-Entity-Relations-Ex/P03_FootballBetting/Data/Models/Color.cs | 565 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
namespace MaiSoft
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
InitIcon();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
private static Icon _exeIcon;
private static Icon _exeIcon48;
public static Icon ExeIcon
{
get { return _exeIcon; }
}
public static Icon ExeIcon48
{
get
{
return (_exeIcon48 != null) ? _exeIcon48 : _exeIcon;
}
}
private static void InitIcon()
{
bool win7_above = (Environment.OSVersion.Version.Build >= 7600);
string path = Application.ExecutablePath;
// Get basic icon.
try
{
_exeIcon = Icon.ExtractAssociatedIcon(path);
}
catch (Exception) { }
// If eicon.dll is available, try get better icon.
try
{
_exeIcon = ExtractIconDll.ExtractOne(path, 0,
(uint)(win7_above ? 32 : 16));
_exeIcon48 = ExtractIconDll.ExtractOne(path, 0, 48);
}
catch (Exception) { }
}
}
}
| 26.533333 | 77 | 0.48995 | [
"MIT"
] | Raymai97/ThDanConfig | src/Code/Program.cs | 1,594 | C# |
using AutoMapper;
using IdentityUtils.Core.Contracts.Context;
using IdentityUtils.Core.Services.Tests.Setup.DbModels;
using IdentityUtils.Core.Services.Tests.Setup.DtoModels;
using Microsoft.AspNetCore.Identity;
namespace IdentityUtils.Core.Services.Tests.Setup.ServicesTyped
{
public class UsersService : IdentityManagerUserService<UserDb, RoleDb, UserDto>
{
public UsersService(UserManager<UserDb> userManager, RoleManager<RoleDb> roleManager, IdentityManagerDbContext<UserDb, RoleDb> dbContext, IMapper mapper)
: base(userManager, dbContext, mapper)
{
}
}
} | 38.1875 | 162 | 0.767594 | [
"MIT"
] | intellegens-hr/utils-identity | dotnetcore/IdentityUtils.Core.Services.Tests/Setup/ServicesTyped/UsersService.cs | 613 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17020
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace testClient.ServiceReference1 {
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="ServiceReference1.IService1")]
public interface IService1 {
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IService1/DoWork", ReplyAction="http://tempuri.org/IService1/DoWorkResponse")]
void DoWork();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IService1Channel : testClient.ServiceReference1.IService1, System.ServiceModel.IClientChannel {
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class Service1Client : System.ServiceModel.ClientBase<testClient.ServiceReference1.IService1>, testClient.ServiceReference1.IService1 {
public Service1Client() {
}
public Service1Client(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public Service1Client(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public Service1Client(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public Service1Client(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
public void DoWork() {
base.Channel.DoWork();
}
}
}
| 41.481481 | 161 | 0.635268 | [
"Apache-2.0"
] | JonasSyrstad/Stardust | testClient/Service References/ServiceReference1/Reference.cs | 2,242 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Input;
using System.Collections;
using Avalonia;
using Avalonia.Animation;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Interactivity;
using Avalonia.Input;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Platform;
using Avalonia.Controls.Selection;
using AvaloniaReactorUI.Internals;
namespace AvaloniaReactorUI
{
public partial interface IRxGrid : IRxPanel
{
ColumnDefinitions Columns { get; set; }
RowDefinitions Rows { get; set; }
}
public partial class RxGrid<T> : RxPanel<T>, IRxGrid where T : Grid, new()
{
public RxGrid(string rows, string columns)
{
var thisAsIRxGrid = (IRxGrid)this;
thisAsIRxGrid.Rows = new RowDefinitions(rows);
thisAsIRxGrid.Columns = new ColumnDefinitions(columns);
}
public RxGrid(RowDefinitions rows, ColumnDefinitions columns)
{
var thisAsIRxGrid = (IRxGrid)this;
thisAsIRxGrid.Rows = rows;
thisAsIRxGrid.Columns = columns;
}
public RxGrid(IEnumerable<RowDefinition> rows, IEnumerable<ColumnDefinition> columns)
{
var thisAsIRxGrid = (IRxGrid)this;
thisAsIRxGrid.Rows = new RowDefinitions();
thisAsIRxGrid.Columns = new ColumnDefinitions();
foreach (var row in rows)
thisAsIRxGrid.Rows.Add(row);
foreach (var column in columns)
thisAsIRxGrid.Columns.Add(column);
}
ColumnDefinitions IRxGrid.Columns { get; set; } = new ColumnDefinitions();
RowDefinitions IRxGrid.Rows { get; set; } = new RowDefinitions();
partial void OnBeginUpdate()
{
Validate.EnsureNotNull(NativeControl);
var thisAsIRxGrid = (IRxGrid)this;
if (NativeControl.RowDefinitions.ToString() != thisAsIRxGrid.Rows.ToString())
{
NativeControl.RowDefinitions = thisAsIRxGrid.Rows;
}
if (NativeControl.ColumnDefinitions.ToString() != thisAsIRxGrid.Columns.ToString())
{
NativeControl.ColumnDefinitions = thisAsIRxGrid.Columns;
}
}
}
public partial class RxGrid : RxGrid<Grid>
{
public RxGrid(string rows, string columns)
:base(rows, columns)
{
}
public RxGrid(RowDefinitions rows, ColumnDefinitions columns)
:base(rows, columns)
{
}
}
public static partial class RxGridExtensions
{
public static T Rows<T>(this T grid, string rows) where T : IRxGrid
{
grid.Rows = new RowDefinitions(rows);
return grid;
}
public static T Columns<T>(this T grid, string columns) where T : IRxGrid
{
grid.Columns = new ColumnDefinitions(columns);
return grid;
}
public static T ColumnDefinition<T>(this T grid) where T : IRxGrid
{
grid.Columns.Add(new ColumnDefinition());
return grid;
}
public static T ColumnDefinition<T>(this T grid, double width) where T : IRxGrid
{
grid.Columns.Add(new ColumnDefinition() { Width = new GridLength(width) });
return grid;
}
public static T ColumnDefinitionAuto<T>(this T grid) where T : IRxGrid
{
grid.Columns.Add(new ColumnDefinition() { Width = GridLength.Auto });
return grid;
}
public static T ColumnDefinitionStar<T>(this T grid, double starValue) where T : IRxGrid
{
grid.Columns.Add(new ColumnDefinition() { Width = new GridLength(starValue, GridUnitType.Star) });
return grid;
}
public static T ColumnDefinition<T>(this T grid, GridLength width) where T : IRxGrid
{
grid.Columns.Add(new ColumnDefinition() { Width = width });
return grid;
}
public static T RowDefinition<T>(this T grid) where T : IRxGrid
{
grid.Rows.Add(new RowDefinition());
return grid;
}
public static T RowDefinition<T>(this T grid, double height) where T : IRxGrid
{
grid.Rows.Add(new RowDefinition() { Height = new GridLength(height) });
return grid;
}
public static T RowDefinitionAuto<T>(this T grid) where T : IRxGrid
{
grid.Rows.Add(new RowDefinition() { Height = GridLength.Auto });
return grid;
}
public static T RowDefinitionStar<T>(this T grid, double starValue) where T : IRxGrid
{
grid.Rows.Add(new RowDefinition() { Height = new GridLength(starValue, GridUnitType.Star) });
return grid;
}
public static T RowDefinition<T>(this T grid, GridLength width) where T : IRxGrid
{
grid.Rows.Add(new RowDefinition() { Height = width });
return grid;
}
public static T GridRow<T>(this T element, int rowIndex) where T : VisualNode
{
element.SetAttachedProperty(Grid.RowProperty, rowIndex);
return element;
}
public static T GridRowSpan<T>(this T element, int rowSpan) where T : VisualNode
{
element.SetAttachedProperty(Grid.RowSpanProperty, rowSpan);
return element;
}
public static T GridColumn<T>(this T element, int columnIndex) where T : VisualNode
{
element.SetAttachedProperty(Grid.ColumnProperty, columnIndex);
return element;
}
public static T GridColumnSpan<T>(this T element, int columnSpan) where T : VisualNode
{
element.SetAttachedProperty(Grid.ColumnSpanProperty, columnSpan);
return element;
}
}
}
| 31.757895 | 110 | 0.601591 | [
"MIT"
] | adospace/reactorui-avalonia | src/AvaloniaReactorUI/RxGrid.partial.cs | 6,034 | C# |
namespace Iridium.DB.Test
{
public class OrderItem
{
public int OrderItemID { get; set; }
public int OrderID { get;set; }
public short Qty { get; set; }
public double Price { get; set; }
[Column.Size(200)]
public string Description { get; set; }
public string ProductID { get; set; }
[Relation]
public Order Order { get; set; }
[Relation]
public Product Product;
}
} | 22.857143 | 47 | 0.541667 | [
"MIT"
] | ArwinNL/iridium | src/Iridium.DB.Test/Model/Orders/OrderItem.cs | 480 | C# |
using UnityEngine;
using System.Collections;
public class PooShooter : MonoBehaviour {
float lastFired;
float shootRate; // In seconds
StreamCell currentTarget;
public bool pooTime = false;
public PooBullet pooBullet;
void Awake ()
{
}
// Use this for initialization
void Start () {
lastFired = 0.0f;
shootRate = 0.3f; // In seconds
}
// Update is called once per frame
void Update () {
if (Time.time > lastFired + shootRate) {
}
if (pooTime) {
pooTime = false;
lastFired = Time.time;
//shootRate = 0.5f;
PooBullet poo = (PooBullet) Instantiate (pooBullet, transform.position, transform.rotation);
poo.setTarget(currentTarget);
}
}
public void shoot(StreamCell target){
this.pooTime = true;
this.currentTarget = target;
}
}
| 17.733333 | 96 | 0.671679 | [
"Artistic-2.0"
] | subrodrigues/PooPooCow | Assets/Scripts/PooShooter.cs | 800 | C# |
//------------------------------------------------------------------------------
// <copyright file="QilUnary.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Xml.Xsl.Qil {
/// <summary>
/// View over a Qil operator having one child.
/// </summary>
/// <remarks>
/// Don't construct QIL nodes directly; instead, use the <see cref="QilFactory">QilFactory</see>.
/// </remarks>
internal class QilUnary : QilNode {
private QilNode child;
//-----------------------------------------------
// Constructor
//-----------------------------------------------
/// <summary>
/// Construct a new node
/// </summary>
public QilUnary(QilNodeType nodeType, QilNode child) : base(nodeType) {
this.child = child;
}
//-----------------------------------------------
// IList<QilNode> methods -- override
//-----------------------------------------------
public override int Count {
get { return 1; }
}
public override QilNode this[int index] {
get { if (index != 0) throw new IndexOutOfRangeException(); return this.child; }
set { if (index != 0) throw new IndexOutOfRangeException(); this.child = value; }
}
//-----------------------------------------------
// QilUnary methods
//-----------------------------------------------
public QilNode Child {
get { return this.child; }
set { this.child = value; }
}
}
}
| 31.59322 | 101 | 0.419528 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/fx/src/XmlUtils/System/Xml/Xsl/QIL/QilUnary.cs | 1,864 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NSubstitute;
using OpenSleigh.Core.Messaging;
using OpenSleigh.Core.Persistence;
using Xunit;
namespace OpenSleigh.Core.Tests.Unit.Messaging
{
public class OutboxProcessorTests
{
[Fact]
public void ctor_should_throw_if_arguments_null()
{
var repo = NSubstitute.Substitute.For<IOutboxRepository>();
var publisher = NSubstitute.Substitute.For<IPublisher>();
var options = OutboxProcessorOptions.Default;
var logger = NSubstitute.Substitute.For<ILogger<OutboxProcessor>>();
Assert.Throws<ArgumentNullException>(() => new OutboxProcessor(null, publisher, options, logger));
Assert.Throws<ArgumentNullException>(() => new OutboxProcessor(repo, null, options, logger));
Assert.Throws<ArgumentNullException>(() => new OutboxProcessor(repo, publisher, null, logger));
Assert.Throws<ArgumentNullException>(() => new OutboxProcessor(repo, publisher, options, null));
}
[Fact]
public async Task StartAsync_should_do_nothing_when_no_pending_messages_available()
{
var repo = NSubstitute.Substitute.For<IOutboxRepository>();
var publisher = NSubstitute.Substitute.For<IPublisher>();
var options = new OutboxProcessorOptions(TimeSpan.FromSeconds(2));
var logger = NSubstitute.Substitute.For<ILogger<OutboxProcessor>>();
var sut = new OutboxProcessor(repo, publisher, options, logger);
var token = new CancellationTokenSource(options.Interval);
try
{
await sut.StartAsync(token.Token);
}
catch (TaskCanceledException) { }
await repo.Received().ReadMessagesToProcess(Arg.Any<CancellationToken>());
await publisher.DidNotReceiveWithAnyArgs().PublishAsync(Arg.Any<IMessage>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_process_pending_messages_()
{
var messages = new[]
{
StartDummySaga.New(),
StartDummySaga.New(),
StartDummySaga.New()
};
var repo = NSubstitute.Substitute.For<IOutboxRepository>();
repo.ReadMessagesToProcess(Arg.Any<CancellationToken>())
.ReturnsForAnyArgs(messages);
var publisher = NSubstitute.Substitute.For<IPublisher>();
var options = new OutboxProcessorOptions(TimeSpan.FromSeconds(2));
var logger = NSubstitute.Substitute.For<ILogger<OutboxProcessor>>();
var sut = new OutboxProcessor(repo, publisher, options, logger);
var token = new CancellationTokenSource(options.Interval);
try
{
await sut.StartAsync(token.Token);
}
catch (TaskCanceledException) { }
await repo.Received().ReadMessagesToProcess(Arg.Any<CancellationToken>());
foreach (var message in messages)
{
await publisher.Received(1)
.PublishAsync(message, Arg.Any<CancellationToken>());
await repo.MarkAsSentAsync(message, Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
}
}
}
| 39.056818 | 119 | 0.622054 | [
"Apache-2.0"
] | adamralph/OpenSleigh | tests/OpenSleigh.Core.Tests/Unit/Messaging/OutboxProcessorTests.cs | 3,439 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/dwrite_1.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public enum DWRITE_PANOSE_ARM_STYLE
{
DWRITE_PANOSE_ARM_STYLE_ANY = 0,
DWRITE_PANOSE_ARM_STYLE_NO_FIT = 1,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_HORIZONTAL = 2,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_WEDGE = 3,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_VERTICAL = 4,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_SINGLE_SERIF = 5,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_DOUBLE_SERIF = 6,
DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_HORIZONTAL = 7,
DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_WEDGE = 8,
DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_VERTICAL = 9,
DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_SINGLE_SERIF = 10,
DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_DOUBLE_SERIF = 11,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_HORZ = DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_HORIZONTAL,
DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_VERT = DWRITE_PANOSE_ARM_STYLE_STRAIGHT_ARMS_VERTICAL,
DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_HORZ = DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_HORIZONTAL,
DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_WEDGE = DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_WEDGE,
DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_VERT = DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_VERTICAL,
DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_SINGLE_SERIF = DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_SINGLE_SERIF,
DWRITE_PANOSE_ARM_STYLE_BENT_ARMS_DOUBLE_SERIF = DWRITE_PANOSE_ARM_STYLE_NONSTRAIGHT_ARMS_DOUBLE_SERIF,
}
}
| 58.483871 | 145 | 0.813017 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/dwrite_1/DWRITE_PANOSE_ARM_STYLE.cs | 1,815 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using yachay.Models;
namespace yachay.Controllers
{
[Route("api/[controller]")]
public class StudentsController : Controller
{
private readonly YachayContext _context;
public StudentsController(YachayContext context)
{
_context = context;
}
//GET: All students
[HttpGet]
public IEnumerable<Student> Index()
{
return _context.Students.ToList();
}
[HttpGet("{studentId}")]
public Student GetEnrollments(int studentId)
{
var student = _context.Students.Find(studentId);
if (student != null)
{
_context.Entry(student).Collection(s => s.Enrollments)
.Query().Include(e => e.Unit).Load();
}
return student;
}
[HttpPost("[action]")]
//we need `FromBody` since this is a complex type
public Student Add([FromBody]Student student)
{
if (!ModelState.IsValid)
{
return null;
}
_context.Add(student);
_context.SaveChanges();
return student;
}
[HttpPost("{studentId}/[action]")]
//we need `FromBody` since this is a complex type
public int Remove(int studentId)
{
var student = _context.Students.Find(studentId);
_context.Remove(student);
_context.SaveChanges();
return 0;
}
}
}
| 25.893939 | 70 | 0.549444 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | gpuma/yachay | Controllers/StudentsController.cs | 1,709 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace HGV.Basilius.Contants
{
public enum GameMode : int
{
None = 0,
AllPick = 1,
CaptainsMode = 2,
RandomDraft = 3,
SingleDraft = 4,
AllRandom = 5,
Intro = 6,
TheDiretide = 7,
ReverseCaptainsMode = 8,
TheGreeviling = 9,
Tutorial = 10,
MidOnly = 11,
LeastPlayed = 12,
NewPlayerPool = 13,
CompendiumMatchmaking = 14,
Custom = 15,
CaptainsDraft = 16,
BalancedDraft = 17,
AbilityDraft = 18,
Event = 19,
AllRandomDeathmatch = 20,
SoloMid = 21,
AllDraft = 22,
Turbo = 23,
Mutation = 24,
}
}
| 21.416667 | 35 | 0.521401 | [
"MIT"
] | HighGroundVision/Basilius | src/Contants/GameModes.cs | 773 | C# |
namespace RxBim.Nuke.Models
{
using global::Nuke.Common.ProjectModel;
/// <summary>
/// Pair of <see cref="Project"/> and <see cref="AssemblyType"/>
/// </summary>
public class ProjectWithAssemblyType
{
/// <summary>
/// ctor
/// </summary>
/// <param name="project"><see cref="Project"/></param>
/// <param name="assemblyType"><see cref="AssemblyType"/></param>
public ProjectWithAssemblyType(
Project project,
AssemblyType assemblyType)
{
Project = project;
AssemblyType = assemblyType;
}
/// <summary>
/// Project
/// </summary>
public Project Project { get; }
/// <summary>
/// Assembly type
/// </summary>
public AssemblyType AssemblyType { get; }
}
} | 26.181818 | 73 | 0.524306 | [
"MIT"
] | AlexNik235/RxBim | src/RxBim.Nuke/Models/ProjectWithAssemblyType.cs | 866 | C# |
using FluentAssertions;
using LyricsBoard.Core;
using LyricsBoard.Core.System;
using Moq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Xunit;
namespace LyricsBoard.Test.Core
{
// Newtonsoft Json DLL included in BeatSaber game is modified to depend on UnityEngine.
// Since i would like to make the test project independent of BeatSaber components,
// implement IJson here by using pure Newtonsoft Json DLL.
internal class UnityIndependentSilentJson : IJson
{
public T? DeserializeObjectOrDefault<T>(string value)
{
try
{
return JsonConvert.DeserializeObject<T>(value);
}
catch (Exception ex) when (ex is JsonReaderException || ex is JsonSerializationException)
{
return default;
}
}
}
public class SongDefinitionLoaderTests
{
private readonly IJson json = new UnityIndependentSilentJson();
private readonly string fullJson = "{OffsetMs:300, MaxExpirationMs:250, AnimationDurationMs:200, StandbyDurationMs:800, CustomLrcFileName:\"abc.lrc\"}";
[Theory]
[InlineData("")]
[InlineData("{}")]
[InlineData("{{}")]
[InlineData("{OffsetMs:300")]
public void Parse_Empty(string input)
{
var loader = new SongDefinitionLoader(Mock.Of<IFileSystem>(), json, "dummy");
var actual = loader.ParseCustomDefinition("hash", input);
actual.Should().NotBeNull();
actual.SongHash.Should().Be("hash");
actual.OffsetMs.Should().BeNull();
actual.MaxExpirationMs.Should().BeNull();
actual.AnimationDurationMs.Should().BeNull();
actual.StandbyDurationMs.Should().BeNull();
actual.CustomLrcFileName.Should().BeNull();
actual.Lyrics.Should().BeNull();
}
[Fact]
public void Parse_Full()
{
var loader = new SongDefinitionLoader(Mock.Of<IFileSystem>(), json, "dummy");
var actual = loader.ParseCustomDefinition("hash", fullJson);
actual.Should().NotBeNull();
actual.SongHash.Should().Be("hash");
actual.OffsetMs.Should().Be(300);
actual.MaxExpirationMs.Should().Be(250);
actual.AnimationDurationMs.Should().Be(200);
actual.StandbyDurationMs.Should().Be(800);
actual.CustomLrcFileName.Should().Be("abc.lrc");
actual.Lyrics.Should().BeNull();
}
[Fact]
public void LoadCustomDefinition_Work()
{
var mfs = new Mock<IFileSystem>();
mfs.Setup(x => x.ReadTextAllOrEmpty("filepath")).Returns(fullJson);
var loader = new SongDefinitionLoader(mfs.Object, json, "dummy");
var actual = loader.LoadCustomDefinition("filepath", "hash");
actual.SongHash.Should().Be("hash");
actual.CustomLrcFileName.Should().Be("abc.lrc");
}
[Fact]
public void LoadByHash_WithCustomLrc()
{
var mfs = new Mock<IFileSystem>();
mfs.Setup(x => x.ReadTextAllOrEmpty("rootfolder\\songhash.json")).Returns(fullJson);
mfs.Setup(x => x.ReatTextLinesOrNull("rootfolder\\abc.lrc")).Returns(new List<string>() { "[01:01]valid line 1" });
var loader = new SongDefinitionLoader(mfs.Object, json, "rootfolder");
var actual = loader.LoadByHash("songhash");
actual.SongHash.Should().Be("songhash");
actual.CustomLrcFileName.Should().Be("abc.lrc");
actual.Lyrics!.Lines.Should().HaveCount(1);
mfs.Verify(
x => x.ReadTextAllOrEmpty(It.IsNotIn(new[] { "rootfolder\\songhash.json" })),
Times.Never()
);
mfs.Verify(
x => x.ReatTextLinesOrNull(It.IsNotIn(new[] { "rootfolder\\abc.lrc" })),
Times.Never()
);
}
[Fact]
public void LoadByHash_WithoutCustomLrc()
{
var mfs = new Mock<IFileSystem>();
mfs.Setup(x => x.ReadTextAllOrEmpty("rootfolder\\songhash.json")).Returns("{OffsetMs:300}");
mfs.Setup(x => x.ReatTextLinesOrNull("rootfolder\\songhash.lrc")).Returns(new List<string>() { "[01:01]valid line 1" });
var loader = new SongDefinitionLoader(mfs.Object, json, "rootfolder");
var actual = loader.LoadByHash("songhash");
actual.SongHash.Should().Be("songhash");
actual.OffsetMs.Should().Be(300);
actual.CustomLrcFileName.Should().BeNull();
actual.Lyrics!.Lines.Should().HaveCount(1);
mfs.Verify(
x => x.ReadTextAllOrEmpty(It.IsNotIn(new[] { "rootfolder\\songhash.json" })),
Times.Never()
);
mfs.Verify(
x => x.ReatTextLinesOrNull(It.IsNotIn(new[] { "rootfolder\\songhash.lrc" })),
Times.Never()
);
}
[Fact]
public void LoadByHash_WithoutCustomDef()
{
var mfs = new Mock<IFileSystem>();
mfs.Setup(x => x.ReadTextAllOrEmpty("rootfolder\\songhash.json")).Returns(string.Empty);
mfs.Setup(x => x.ReatTextLinesOrNull("rootfolder\\songhash.lrc")).Returns(new List<string>() { "[01:01]valid line 1" });
var loader = new SongDefinitionLoader(mfs.Object, json, "rootfolder");
var actual = loader.LoadByHash("songhash");
actual.SongHash.Should().Be("songhash");
actual.CustomLrcFileName.Should().BeNull();
actual.Lyrics!.Lines.Should().HaveCount(1);
mfs.Verify(
x => x.ReadTextAllOrEmpty(It.IsNotIn(new[] { "rootfolder\\songhash.json" })),
Times.Never()
);
mfs.Verify(
x => x.ReatTextLinesOrNull(It.IsNotIn(new[] { "rootfolder\\songhash.lrc" })),
Times.Never()
);
}
[Fact]
public void GenerateSafely_Fill()
{
var loader = new SongDefinitionLoader(Mock.Of<IFileSystem>(), json, "rootfolder");
var actual = loader.GenerateCustomDefinitionSafely("songhash", 100, 200, 300, 400, "lrc");
actual.SongHash.Should().Be("songhash");
actual.OffsetMs.Should().Be(100);
actual.MaxExpirationMs.Should().Be(200);
actual.AnimationDurationMs.Should().Be(300);
actual.StandbyDurationMs.Should().Be(400);
actual.CustomLrcFileName.Should().Be("lrc");
}
[Fact]
public void GenerateSafely_ClampUpper()
{
var loader = new SongDefinitionLoader(Mock.Of<IFileSystem>(), json, "rootfolder");
var actual = loader.GenerateCustomDefinitionSafely("songhash", 3600001, 3600001, 60001, 3600001, "lrc");
actual.SongHash.Should().Be("songhash");
actual.OffsetMs.Should().Be(3600000);
actual.MaxExpirationMs.Should().Be(3600000);
actual.AnimationDurationMs.Should().Be(60000);
actual.StandbyDurationMs.Should().Be(3600000);
actual.CustomLrcFileName.Should().Be("lrc");
}
[Fact]
public void GenerateSafely_ClampLower()
{
var loader = new SongDefinitionLoader(Mock.Of<IFileSystem>(), json, "rootfolder");
var actual = loader.GenerateCustomDefinitionSafely("songhash", -3600001, 99, -1, -1, "lrc");
actual.SongHash.Should().Be("songhash");
actual.OffsetMs.Should().Be(-3600000);
actual.MaxExpirationMs.Should().Be(100);
actual.AnimationDurationMs.Should().Be(0);
actual.StandbyDurationMs.Should().Be(0);
actual.CustomLrcFileName.Should().Be("lrc");
}
}
} | 41.187817 | 161 | 0.568893 | [
"MIT"
] | kan8pachi/lyricsboard | LyricsBoardTest/Core/SongDefinitionLoaderTests.cs | 8,116 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour {
// Use this for initialization
void Start () {
InvokeRepeating("Spawn",3,2);//Call Spawn after 3 seconds and then every 2 seconds
}
// Update is called once per frame
void Update () {
}
void Spawn()
{
GameObject newPrize = Instantiate(Resources.Load<GameObject>("Prefab/Prize"));
newPrize.transform.position = new Vector2(Random.Range(-8,8),Random.Range(-3,5));
}
}
| 19.807692 | 84 | 0.706796 | [
"Unlicense"
] | UtarMantyke/CodeLab1-2019-HW1 | CodeLabWeek1/Assets/Scripts/Spawner.cs | 517 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Project_OLP_Rest.Data;
using Project_OLP_Rest.Data.Interfaces;
using Project_OLP_Rest.Domain;
namespace Project_OLP_Rest.Controllers
{
[Produces("application/json", new string[] { "application/json+hateoas" })]
[Route("api/ChatSessions")]
public class ChatSessionsController : Controller
{
private readonly IChatSessionService _chatSessionService;
public ChatSessionsController(IChatSessionService chatSessionService)
{
_chatSessionService = chatSessionService;
}
// GET: api/ChatSessions
[HttpGet(Name = "get-sessions")]
public async Task<IEnumerable<ChatSession>> GetChatSessions()
{
return await _chatSessionService.GetAll();
}
// GET: api/ChatSessions/5
[HttpGet("{id}", Name = "get-session")]
public async Task<IActionResult> GetChatSession([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var chatSession = await _chatSessionService.FindBy(m => m.ChatSessionId == id);
if (chatSession == null)
{
return NotFound();
}
return Ok(chatSession);
}
// PUT: api/ChatSessions/5
[HttpPut("{id}",Name ="edit-session")]
public async Task<IActionResult> PutChatSession([FromRoute] int id, [FromBody] ChatSession chatSession)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != chatSession.ChatSessionId)
{
return BadRequest();
}
try
{
await _chatSessionService.Update(chatSession);
}
catch (DbUpdateConcurrencyException)
{
if (!(await ChatSessionExists(id)))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/ChatSessions
[HttpPost(Name = "add-session")]
public async Task<IActionResult> PostChatSession([FromBody] ChatSession chatSession)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
await _chatSessionService.Create(chatSession);
return CreatedAtAction("GetChatSession", new { id = chatSession.ChatSessionId }, chatSession);
}
// DELETE: api/ChatSessions/5
[HttpDelete("{id}",Name = "delete-session")]
public async Task<IActionResult> DeleteChatSession([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var chatSession = await _chatSessionService.FindBy(m => m.ChatSessionId == id);
if (chatSession == null)
{
return NotFound();
}
await _chatSessionService.Delete(chatSession);
return Ok(chatSession);
}
private async Task<bool> ChatSessionExists(int id)
{
return await _chatSessionService.Exists(e => e.ChatSessionId == id);
}
}
} | 29.073171 | 111 | 0.553971 | [
"MIT"
] | dbnmur/Project_OLP_Rest | Project_OLP_Rest/Controllers/ModelControllers/ChatSessionsController.cs | 3,578 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ShiftRightArithmeticRoundedAdd_Vector64_Int32_1()
{
var test = new ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_Int32_1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_Int32_1
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int32> _fld1;
public Vector64<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_Int32_1 testClass)
{
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_Int32_1 testClass)
{
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2)),
1
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly byte Imm = 1;
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector64<Int32> _clsVar1;
private static Vector64<Int32> _clsVar2;
private Vector64<Int32> _fld1;
private Vector64<Int32> _fld2;
private DataTable _dataTable;
static ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_Int32_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
}
public ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_Int32_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightArithmeticRoundedAdd), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightArithmeticRoundedAdd), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(
AdvSimd.LoadVector64((Int32*)(pClsVar1)),
AdvSimd.LoadVector64((Int32*)(pClsVar2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr);
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(op1, op2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr));
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(op1, op2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_Int32_1();
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_Int32_1();
fixed (Vector64<Int32>* pFld1 = &test._fld1)
fixed (Vector64<Int32>* pFld2 = &test._fld2)
{
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ShiftRightArithmeticRoundedAdd(
AdvSimd.LoadVector64((Int32*)(&test._fld1)),
AdvSimd.LoadVector64((Int32*)(&test._fld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int32> firstOp, Vector64<Int32> secondOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), firstOp);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), secondOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ShiftRightArithmeticRoundedAdd(firstOp[i], secondOp[i], Imm) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightArithmeticRoundedAdd)}<Int32>(Vector64<Int32>, Vector64<Int32>, 1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 42.933457 | 190 | 0.588109 | [
"MIT"
] | 06needhamt/runtime | src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftRightArithmeticRoundedAdd.Vector64.Int32.1.cs | 23,227 | 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("bungeecordhandler")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("bungeecordhandler")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("63312a48-2ff8-4869-b0ec-df567bfbc32b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.891892 | 84 | 0.749643 | [
"Unlicense"
] | FallingAnvils/MCSIM | bungeecordhandler/Properties/AssemblyInfo.cs | 1,405 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace FileSlynchy
{
public class DirectorySpec
{
public List<string> PathNameExcludes { get; set; } //Excludes any directory with this name
public List<string> PathRelativeExcludes { get; set; } //Excludes this directory path from root
public List<string> IncludedFileExtensions { get; set; } //List of file extensions for comparison
public List<string> FileNameExcludes { get; set; } //List of file names to exclude
public List<string> FilePathExcludes { get; set; } //List of path.files to exclude (redundant?). Under files tab in form
public List<string> DirFileExcludes { get; set; } //List of root relative path.files to exclude. Under file type and files in directory tab in form
public DirectorySpec()
{
PathNameExcludes = new List<string>();
PathRelativeExcludes = new List<string>();
IncludedFileExtensions = new List<string>();
FileNameExcludes = new List<string>();
FilePathExcludes = new List<string>();
DirFileExcludes = new List<string>();
}
}
}
| 33.470588 | 151 | 0.704745 | [
"MIT"
] | waltal/FileSlynchy | FileSlynchy/DirectorySpec.cs | 1,140 | C# |
using System;
using BowlingGame;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BowlingGameTests
{
[TestClass]
public class GameTest
{
Game g;
[TestInitialize]
public void Setup()
{
g = new Game();
}
private void RollMany(int rollCount, int pins)
{
for (int i = 0; i < rollCount; i++)
g.Roll(pins);
}
[TestMethod]
public void TestGutterGame()
{
RollMany(20, 0);
Assert.AreEqual(0, g.Score());
}
[TestMethod]
public void TestAllInOneGame()
{
RollMany(20, 1);
Assert.AreEqual(20, g.Score());
}
[TestMethod]
public void TestOneSpare()
{
g.Roll(5);
g.Roll(5);
g.Roll(3);
RollMany(17, 0);
Assert.AreEqual(16, g.Score());
}
[TestMethod]
public void TestOneStrike()
{
g.Roll(10);
g.Roll(5);
g.Roll(3);
RollMany(16, 0);
Assert.AreEqual(26, g.Score());
}
[TestMethod]
public void TestPerfectGame()
{
RollMany(12, 10);
Assert.AreEqual(300, g.Score());
}
}
}
| 18.506849 | 54 | 0.449297 | [
"MIT"
] | cjhnim/daily-kata | BowlingKata/day6/BowlingGame/BowlingGameTests/GameTest.cs | 1,353 | C# |
/*
* Original author: Nick Shulman <nicksh .at. u.washington.edu>,
* MacCoss Lab, Department of Genome Sciences, UW
*
* Copyright 2013 University of Washington - Seattle, WA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using pwiz.Common.DataBinding.Controls;
using pwiz.Common.DataBinding.Layout;
using pwiz.Common.SystemUtil;
using pwiz.Skyline.Alerts;
using pwiz.Skyline.Model.AuditLog;
using pwiz.Skyline.Model.Databinding;
using pwiz.Skyline.Properties;
namespace pwiz.Skyline.Util
{
/// <summary>
/// Can be attached to a DataGridView so that when the user pastes (Ctrl+V), and the
/// the text on the clipboard is parsed into rows and columns and pasted into the
/// editable cells going right and down from the currently selected cell.
/// </summary>
public class DataGridViewPasteHandler
{
private DataGridViewPasteHandler(BoundDataGridView boundDataGridView)
{
DataGridView = boundDataGridView;
DataGridView.KeyDown += DataGridViewOnKeyDown;
}
/// <summary>
/// Attaches a DataGridViewPasteHandler to the specified DataGridView.
/// </summary>
public static DataGridViewPasteHandler Attach(BoundDataGridView boundDataGridView)
{
return new DataGridViewPasteHandler(boundDataGridView);
}
public BoundDataGridView DataGridView { get; private set; }
public enum BatchModifyAction { Paste, Clear, FillDown }
public class BatchModifyInfo : AuditLogOperationSettings<BatchModifyInfo> // TODO: this is a little lazy, consider rewriting
{
public BatchModifyInfo(BatchModifyAction batchModifyAction, string viewName, RowFilter rowFilter, string extraInfo = null)
{
BatchModifyAction = batchModifyAction;
ViewName = viewName;
Filter = rowFilter;
ExtraInfo = extraInfo;
}
public BatchModifyAction BatchModifyAction { get; private set; }
[Track(defaultValues:typeof(DefaultValuesNull))]
public string ViewName { get; private set; }
[TrackChildren]
public RowFilter Filter { get; private set; }
public string ExtraInfo { get; private set; }
}
private void DataGridViewOnKeyDown(object sender, KeyEventArgs e)
{
if (e.Handled)
{
return;
}
if (DataGridView.IsCurrentCellInEditMode && !(DataGridView.CurrentCell is DataGridViewCheckBoxCell))
{
return;
}
var bindingListSource = DataGridView.DataSource as BindingListSource;
var rowFilter = bindingListSource == null ? RowFilter.Empty : bindingListSource.RowFilter;
var viewName = bindingListSource == null ? null : bindingListSource.ViewInfo.Name;
if (Equals(e.KeyData, Keys.Control | Keys.V))
{
var clipboardText = ClipboardHelper.GetClipboardText(DataGridView);
if (null == clipboardText)
{
return;
}
using (var reader = new StringReader(clipboardText))
{
e.Handled = PerformUndoableOperation(Resources.DataGridViewPasteHandler_DataGridViewOnKeyDown_Paste,
monitor => Paste(monitor, reader),
new BatchModifyInfo(BatchModifyAction.Paste, viewName,
rowFilter, clipboardText));
}
}
else if (e.KeyCode == Keys.Delete && 0 == e.Modifiers)
{
e.Handled = PerformUndoableOperation(
Resources.DataGridViewPasteHandler_DataGridViewOnKeyDown_Clear_cells, ClearCells,
new BatchModifyInfo(BatchModifyAction.Clear, viewName, rowFilter));
}
}
public bool PerformUndoableOperation(string description, Func<ILongWaitBroker, bool> operation, BatchModifyInfo batchModifyInfo)
{
var skylineDataSchema = GetDataSchema();
if (skylineDataSchema == null)
{
return false;
}
bool resultsGridSynchSelectionOld = Settings.Default.ResultsGridSynchSelection;
bool enabledOld = DataGridView.Enabled;
try
{
Settings.Default.ResultsGridSynchSelection = false;
var cellAddress = DataGridView.CurrentCellAddress;
DataGridView.Enabled = false;
DataGridView.CurrentCell = DataGridView.Rows[cellAddress.Y].Cells[cellAddress.X];
lock (skylineDataSchema.SkylineWindow.GetDocumentChangeLock())
{
skylineDataSchema.BeginBatchModifyDocument();
var longOperationRunner = new LongOperationRunner
{
ParentControl = FormUtil.FindTopLevelOwner(DataGridView),
JobTitle = description
};
if (longOperationRunner.CallFunction(operation))
{
skylineDataSchema.CommitBatchModifyDocument(description, batchModifyInfo);
return true;
}
}
return false;
}
finally
{
DataGridView.Enabled = enabledOld;
Settings.Default.ResultsGridSynchSelection = resultsGridSynchSelectionOld;
skylineDataSchema.RollbackBatchModifyDocument();
}
}
private SkylineDataSchema GetDataSchema()
{
var bindingListSource = DataGridView.DataSource as BindingListSource;
if (bindingListSource == null || bindingListSource.ViewInfo == null)
{
return null;
}
return bindingListSource.ViewInfo.DataSchema as SkylineDataSchema;
}
/// <summary>
/// Pastes tab delimited data into rows and columns starting from the current cell.
/// If an error is encountered (e.g. type conversion), then a message is displayed,
/// and the focus is left in the cell which had an error.
/// Returns true if any changes were made to the document, false if there were no
/// changes.
/// </summary>
private bool Paste(ILongWaitBroker longWaitBroker, TextReader reader)
{
bool anyChanges = false;
var columnsByDisplayIndex =
DataGridView.Columns.Cast<DataGridViewColumn>().Where(column => column.Visible).ToArray();
Array.Sort(columnsByDisplayIndex, (col1, col2) => col1.DisplayIndex.CompareTo(col2.DisplayIndex));
int iFirstCol;
int iFirstRow;
if (null == DataGridView.CurrentCell)
{
iFirstRow = 0;
iFirstCol = 0;
}
else
{
iFirstCol = columnsByDisplayIndex.IndexOf(col => col.Index == DataGridView.CurrentCell.ColumnIndex);
iFirstRow = DataGridView.CurrentCell.RowIndex;
}
for (int iRow = iFirstRow; iRow < DataGridView.Rows.Count; iRow++)
{
if (longWaitBroker.IsCanceled)
{
return anyChanges;
}
longWaitBroker.Message = string.Format(Resources.DataGridViewPasteHandler_Paste_Pasting_row__0_, iRow + 1);
string line = reader.ReadLine();
if (null == line)
{
return anyChanges;
}
var row = DataGridView.Rows[iRow];
using (var values = SplitLine(line).GetEnumerator())
{
for (int iCol = iFirstCol; iCol < columnsByDisplayIndex.Length; iCol++)
{
if (!values.MoveNext())
{
break;
}
var column = columnsByDisplayIndex[iCol];
if (column.ReadOnly)
{
continue;
}
if (!TrySetValue(row.Cells[column.Index], values.Current))
{
return anyChanges;
}
anyChanges = true;
}
}
}
return anyChanges;
}
private bool ClearCells(ILongWaitBroker longWaitBroker)
{
if (DataGridView.SelectedRows.Count > 0)
{
return false;
}
var columnIndexes = DataGridView.SelectedCells.Cast<DataGridViewCell>().Select(cell => cell.ColumnIndex).Distinct().ToArray();
if (columnIndexes.Any(columnIndex => DataGridView.Columns[columnIndex].ReadOnly))
{
return false;
}
bool anyChanges = false;
var cellsByRow = DataGridView.SelectedCells.Cast<DataGridViewCell>().ToLookup(cell => cell.RowIndex).ToArray();
Array.Sort(cellsByRow, (g1,g2)=>g1.Key.CompareTo(g2.Key));
for (int iGrouping = 0; iGrouping < cellsByRow.Length; iGrouping++)
{
if (longWaitBroker.IsCanceled)
{
return anyChanges;
}
longWaitBroker.ProgressValue = 100 * iGrouping / cellsByRow.Length;
longWaitBroker.Message = string.Format(Resources.DataGridViewPasteHandler_ClearCells_Cleared__0___1__rows, iGrouping, cellsByRow.Length);
var rowGrouping = cellsByRow[iGrouping];
var cells = rowGrouping.ToArray();
Array.Sort(cells, (c1, c2) => c1.ColumnIndex.CompareTo(c2.ColumnIndex));
foreach (var cell in cells)
{
if (!TrySetValue(cell, string.Empty))
{
return anyChanges;
}
anyChanges = true;
}
}
return anyChanges;
}
private bool TrySetValue(DataGridViewCell cell, string strValue)
{
IDataGridViewEditingControl editingControl = null;
DataGridViewEditingControlShowingEventHandler onEditingControlShowing =
(sender, args) =>
{
Assume.IsNull(editingControl);
editingControl = args.Control as IDataGridViewEditingControl;
};
try
{
DataGridView.EditingControlShowing += onEditingControlShowing;
DataGridView.CurrentCell = cell;
DataGridView.BeginEdit(true);
if (null != editingControl)
{
object convertedValue;
if (!TryConvertValue(strValue, DataGridView.CurrentCell.FormattedValueType, out convertedValue))
{
return false;
}
editingControl.EditingControlFormattedValue = convertedValue;
}
else
{
object convertedValue;
if (!TryConvertValue(strValue, DataGridView.CurrentCell.ValueType, out convertedValue))
{
return false;
}
DataGridView.CurrentCell.Value = convertedValue;
}
if (!DataGridView.EndEdit())
{
return false;
}
return true;
}
catch (Exception e)
{
Program.ReportException(e);
return false;
}
finally
{
DataGridView.EditingControlShowing -= onEditingControlShowing;
}
}
private static readonly char[] COLUMN_SEPARATORS = {'\t'};
private IEnumerable<string> SplitLine(string row)
{
return row.Split(COLUMN_SEPARATORS);
}
protected bool TryConvertValue(string strValue, Type valueType, out object convertedValue)
{
if (null == valueType)
{
convertedValue = strValue;
return true;
}
try
{
convertedValue = Convert.ChangeType(strValue, valueType);
return true;
}
catch (Exception exception)
{
string message = string.Format(Resources.DataGridViewPasteHandler_TryConvertValue_Error_converting___0___to_required_type___1_, strValue,
exception.Message);
// CONSIDER(bspratt): this is probably not the proper parent. See "Issue 775: follow up on possible improper parenting of MessageDlg"
MessageDlg.Show(DataGridView, message);
convertedValue = null;
return false;
}
}
}
}
| 41.827988 | 154 | 0.539067 | [
"Apache-2.0"
] | CSi-Studio/pwiz | pwiz_tools/Skyline/Util/DataGridViewPasteHandler.cs | 14,349 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Drawing;
using SdlDotNet.Graphics;
using SdlDotNet.Graphics.Sprites;
using Moway.Project.GraphicProject.GraphLayout;
using Moway.Project.GraphicProject.GraphLayout.Elements;
namespace Moway.Project.GraphicProject.Actions.StartRf
{
public class StartRfGraphic : GraphConditional
{
public override bool Selected
{
get
{
return base.Selected;
}
set
{
if (this.selected != value)
{
this.selected = value;
if (this.selected)
this.Surface.Blit(new Surface(StartRf.GraphicIconSelected));
else
{
this.Surface.Fill(GraphDiagram.TRASPARENT_COLOR);
this.Surface.Blit(new Surface(StartRf.GraphicIcon));
this.DrawOutIcons();
}
}
}
}
public StartRfGraphic(string key)
: base(key)
{
this.needInit = System.Convert.ToBoolean(StartRf.NeedInit);
this.Surface.Blit(new Surface(StartRf.GraphicIcon));
}
public StartRfGraphic(string key, StartRfAction element, Point center)
: base(key, element, center)
{
this.needInit = System.Convert.ToBoolean(StartRf.NeedInit);
this.Surface.Blit(new Surface(StartRf.GraphicIcon));
}
public StartRfGraphic(string key, XmlElement elementData, System.Collections.Generic.SortedList<string, Variable> variables)
: base(key)
{
this.needInit = System.Convert.ToBoolean(StartRf.NeedInit);
this.Surface.Blit(new Surface(StartRf.GraphicIcon));
foreach (XmlElement nodo in elementData)
{
switch (nodo.Name)
{
case "position":
this.Center = new Point(System.Convert.ToInt32(nodo.ChildNodes[0].InnerText), System.Convert.ToInt32(nodo.ChildNodes[1].InnerText));
break;
case "properties":
this.element = new StartRfAction(key, nodo);
break;
case "previous":
break;
case "nextTrue":
break;
case "nextFalse":
break;
default:
throw new GraphException("Error al crear GraphStart");
}
}
}
public override void EnableConnector(Connector connector)
{
this.Surface.Fill(GraphDiagram.TRASPARENT_COLOR);
this.Surface.Blit(new Surface(StartRf.GraphicIcon));
this.DrawOutIcons();
base.EnableConnector(connector);
}
public override void DisableConnectors()
{
base.DisableConnectors();
this.Surface.Fill(GraphDiagram.TRASPARENT_COLOR);
this.Surface.Blit(new Surface(StartRf.GraphicIcon));
this.DrawOutIcons();
}
public override GraphElement Clone()
{
return new StartRfGraphic(this.key, (StartRfAction)this.element.Clone(), this.Center);
}
}
}
| 33.960784 | 156 | 0.533776 | [
"MIT"
] | Bizintek/mOway_SW_mOwayWorld | mOway_SW_mOwayWorld/MowayProject/GraphicProject/Actions/StartRf/StartRfGraphic.cs | 3,466 | C# |
// Copyright © Conatus Creative, Inc. All rights reserved.
// Licensed under the Apache 2.0 License. See LICENSE.md in the project root for license terms.
using Lidgren.Network;
namespace Pixel3D.P2P
{
public static class InputAssignmentExtensions
{
public const int MaxPlayerInputAssignments = 4;
// There a bunch of bit-twiddling that could be done here, for some fun over-optimisation.
public static InputAssignment GetNextAssignment(this InputAssignment ia)
{
for (var i = 0; i < MaxPlayerInputAssignments; i++)
if (((int) ia & (1 << i)) == 0)
return (InputAssignment) (1 << i);
return 0;
}
// TODO: To add support for multiple players per network peer, remove this (find-all-references to fix up the places it gets used)
/// <returns>The first player assigned in a given assignment, or -1 if no players are assigned</returns>
public static int GetFirstAssignedPlayerIndex(this InputAssignment ia)
{
for (var i = 0; i < MaxPlayerInputAssignments; i++)
if (((int) ia & (1 << i)) != 0)
return i;
return -1;
}
#region Network Read/Write
public static void Write(this NetOutgoingMessage message, InputAssignment ia)
{
message.Write((uint) ia, MaxPlayerInputAssignments);
}
public static InputAssignment ReadInputAssignment(this NetIncomingMessage message)
{
return (InputAssignment) message.ReadUInt32(MaxPlayerInputAssignments);
}
#endregion
}
} | 29.265306 | 132 | 0.717573 | [
"Apache-2.0"
] | caogtaa/Pixel3D | src/Pixel3D.P2P/InputAssignmentExtensions.cs | 1,437 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Moq.AutoMock;
using PandaPlayer.Adviser;
using PandaPlayer.Adviser.Grouping;
using PandaPlayer.Adviser.Interfaces;
using PandaPlayer.Adviser.Internal;
using PandaPlayer.Adviser.PlaylistAdvisers;
using PandaPlayer.Core.Models;
using PandaPlayer.UnitTests.Extensions;
namespace PandaPlayer.UnitTests.Adviser.PlaylistAdvisers
{
[TestClass]
public class FavoriteAdviseGroupsAdviserTests
{
[TestMethod]
public async Task Advise_IfAllAdviseSetsAreActive_AdvisesSetsInCorrectOrder()
{
// Arrange
// Last playback time for each advise group:
//
// adviseGroup1: 3, 2
// adviseGroup2: null
// adviseGroup3: null, 1
//
// Expected order (order within advise group is provided by inner adviser and is not changed):
//
// adviseSet21, adviseSet11, adviseSet31
var adviseSet11 = CreateTestAdviseSet("11", new[] { CreateTestSong(1, new DateTime(2018, 08, 17)) });
var adviseSet12 = CreateTestAdviseSet("12", new[] { CreateTestSong(2, new DateTime(2018, 08, 18)) });
var adviseSet21 = CreateTestAdviseSet("21", new[] { CreateTestSong(3) });
var adviseSet31 = CreateTestAdviseSet("31", new[] { CreateTestSong(4) });
var adviseSet32 = CreateTestAdviseSet("32", new[] { CreateTestSong(5, new DateTime(2018, 08, 19)) });
var adviseGroups = new[]
{
CreateAdviseGroup("1", isFavorite: true, adviseSet11, adviseSet12),
CreateAdviseGroup("2", isFavorite: true, adviseSet21),
CreateAdviseGroup("3", isFavorite: true, adviseSet31, adviseSet32),
};
var playbacksInfo = new PlaybacksInfo(adviseGroups);
var rankBasedAdviserStub = new Mock<IPlaylistAdviser>();
rankBasedAdviserStub.Setup(x => x.Advise(adviseGroups, playbacksInfo, It.IsAny<CancellationToken>())).ReturnsAsync(CreatedAdvisedPlaylists(adviseGroups));
var mocker = new AutoMocker();
mocker.Use(rankBasedAdviserStub);
var target = mocker.CreateInstance<FavoriteAdviseGroupsAdviser>();
// Act
var advisedPlaylists = await target.Advise(adviseGroups, playbacksInfo, CancellationToken.None);
// Assert
var expectedPlaylists = new[]
{
AdvisedPlaylist.ForAdviseSetFromFavoriteAdviseGroup(adviseSet21),
AdvisedPlaylist.ForAdviseSetFromFavoriteAdviseGroup(adviseSet11),
AdvisedPlaylist.ForAdviseSetFromFavoriteAdviseGroup(adviseSet31),
};
advisedPlaylists.Should().BeEquivalentTo(expectedPlaylists, x => x.WithStrictOrdering());
}
[TestMethod]
public async Task Advise_AdvisesOnlySetsFromFavoriteAdviseGroups()
{
// Arrange
var adviseSetFromFavoriteAdviseGroup = CreateTestAdviseSet("1", new[] { CreateTestSong(1) });
var adviseSetFromNonFavoriteAdviseGroup = CreateTestAdviseSet("2", new[] { CreateTestSong(2) });
var adviseGroups = new[]
{
CreateAdviseGroup("1", isFavorite: false, adviseSetFromNonFavoriteAdviseGroup),
CreateAdviseGroup("2", isFavorite: true, adviseSetFromFavoriteAdviseGroup),
};
var playbacksInfo = new PlaybacksInfo(adviseGroups);
var rankBasedAdviserStub = new Mock<IPlaylistAdviser>();
rankBasedAdviserStub.Setup(x => x.Advise(adviseGroups, playbacksInfo, It.IsAny<CancellationToken>()))
.ReturnsAsync(CreatedAdvisedPlaylists(adviseGroups));
var mocker = new AutoMocker();
mocker.Use(rankBasedAdviserStub);
var target = mocker.CreateInstance<FavoriteAdviseGroupsAdviser>();
// Act
var advisedPlaylists = await target.Advise(adviseGroups, playbacksInfo, CancellationToken.None);
// Assert
var expectedPlaylists = new[]
{
AdvisedPlaylist.ForAdviseSetFromFavoriteAdviseGroup(adviseSetFromFavoriteAdviseGroup),
};
advisedPlaylists.Should().BeEquivalentTo(expectedPlaylists, x => x.WithStrictOrdering());
}
private static IReadOnlyCollection<AdvisedPlaylist> CreatedAdvisedPlaylists(IEnumerable<AdviseGroupContent> adviseGroups)
{
return adviseGroups
.SelectMany(x => x.AdviseSets)
.Select(AdvisedPlaylist.ForAdviseSet)
.ToList();
}
private static AdviseSetContent CreateTestAdviseSet(string id, IEnumerable<SongModel> songs)
{
var disc = new DiscModel()
{
Id = new ItemId(id),
Folder = new ShallowFolderModel(),
AllSongs = songs.ToList(),
};
return disc.ToAdviseSet();
}
private static SongModel CreateTestSong(int id, DateTimeOffset? lastPlaybackTime = null, DateTimeOffset? deleteDate = null)
{
return new()
{
Id = new ItemId(id.ToString(CultureInfo.InvariantCulture)),
LastPlaybackTime = lastPlaybackTime,
DeleteDate = deleteDate,
};
}
private static AdviseGroupContent CreateAdviseGroup(string id, bool isFavorite, params AdviseSetContent[] adviseSets)
{
var adviseGroup = new AdviseGroupContent(id, isFavorite: isFavorite);
foreach (var adviseSet in adviseSets)
{
foreach (var disc in adviseSet.Discs)
{
adviseGroup.AddDisc(disc);
}
}
return adviseGroup;
}
}
}
| 32.666667 | 158 | 0.720711 | [
"MIT"
] | CodeFuller/music-library | tests/PandaPlayer.UnitTests/Adviser/PlaylistAdvisers/FavoriteAdviseGroupsAdviserTests.cs | 5,294 | 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("JsMate.Api")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JsMate.Api")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cc3adbca-2baf-46d6-96f3-5438dfe2189e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.583333 | 84 | 0.746489 | [
"MIT"
] | ballance/jsmate | JsMate.Api/Properties/AssemblyInfo.cs | 1,356 | 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("DrClockwork.Nancy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DrClockwork.Nancy")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a7fe54f8-f161-4c6e-9b06-c240264ce70a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.972222 | 84 | 0.749086 | [
"Unlicense"
] | MacsDickinson/DoctorClockwork | DrClockwork/DrClockwork.Nancy/Properties/AssemblyInfo.cs | 1,370 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.