content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Permissions;
using System.ComponentModel;
namespace System.ComponentModel
{
//[HostProtection(SecurityAction.LinkDemand,SharedState = true)]
public class DataTimeLimitLicenseProvider:LicenseProvider
{
public override System.ComponentModel.License GetLicense(LicenseContext context,Type type,object instance,bool allowExceptions)
{
if(context.UsageMode == LicenseUsageMode.Runtime)
{
string con = context.GetSavedLicenseKey(type,null);
if(DateTime.Now < EndDateTime && DateTime.Now > BeginDateTime)
{
System.ComponentModel.License license = new DateTimeLimitLicense();
context.SetSavedLicenseKey(type,license.LicenseKey);
return license;
}
else
{
return null;
}
}
else
{
return new DateTimeLimitLicense();
}
}
public virtual DateTime EndDateTime
{
get
{
return new DateTime(2010,2,20);
}
}
public virtual DateTime BeginDateTime
{
get
{
return new DateTime(2010,10,12);
}
}
private class DateTimeLimitLicense:System.ComponentModel.License
{
public override void Dispose()
{
}
public override string LicenseKey
{
get { return "Licensed"; }
}
}
}
}
| 28.683333 | 135 | 0.525857 | [
"MIT"
] | obpt123/Core | YS.System.Base/ComponentModel/License/DataTimeLimitLicenseProvider.cs | 1,723 | C# |
using System.Web;
using System.Web.Mvc;
namespace Microsoft.Azure.AppConfiguration.WebDemo
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 20.928571 | 80 | 0.679181 | [
"MIT"
] | Anne56njeri/AppConfiguration | examples/DotNetFramework/WebDemo/Microsoft.Azure.AppConfiguration.WebDemo/App_Start/FilterConfig.cs | 295 | C# |
using System;
using System.Collections.Generic;
using Photon.Realtime;
using UniRx;
using UnityEngine;
namespace PUN2Rx
{
/// <summary>
/// <see cref="Photon.Realtime.ILobbyCallbacks"/>
/// </summary>
public static class LobbyCallbacksTriggersExtension
{
/// <summary>
/// <c>OnNext(Unit)</c> - ILobbyCallbacks.OnJoinedLobby
/// </summary>
public static IObservable<Unit> OnJoinedLobbyAsObservable(this Component component)
{
return component?.gameObject == null
? Observable.Empty<Unit>()
: GetOrAddComponent<LobbyCallbacksTriggers>(component.gameObject).OnJoinedLobbyAsObservable();
}
/// <summary>
/// <c>OnNext(Unit)</c> - ILobbyCallbacks.OnLeftLobby
/// </summary>
public static IObservable<Unit> OnLeftLobbyAsObservable(this Component component)
{
return component?.gameObject == null
? Observable.Empty<Unit>()
: GetOrAddComponent<LobbyCallbacksTriggers>(component.gameObject).OnLeftRoomAsObservable();
}
/// <summary>
/// <c>OnNext(List<RoomInfo>)</c> - ILobbyCallbacks.OnRoomListUpdate
/// </summary>
public static IObservable<List<RoomInfo>> OnRoomListUpdateAsObservable(this Component component)
{
return component?.gameObject == null
? Observable.Empty<List<RoomInfo>>()
: GetOrAddComponent<LobbyCallbacksTriggers>(component.gameObject).OnRoomListUpdateAsObservable();
}
/// <summary>
/// <c>OnNext(List<TypedLobbyInfo>)</c> - ILobbyCallbacks.OnLobbyStatisticsUpdate
/// </summary>
public static IObservable<List<TypedLobbyInfo>> OnLobbyStatisticsUpdateAsObservable(this Component component)
{
return component?.gameObject == null
? Observable.Empty<List<TypedLobbyInfo>>()
: GetOrAddComponent<LobbyCallbacksTriggers>(component.gameObject).OnLobbyStatisticsUpdateAsObservable();
}
private static T GetOrAddComponent<T>(GameObject gameObject)
where T : Component
{
var component = gameObject.GetComponent<T>();
if (component == null)
{
component = gameObject.AddComponent<T>();
}
return component;
}
}
}
| 37.61194 | 121 | 0.596825 | [
"MIT"
] | nekomimi-daimao/PUN2Rx | Packages/PUN2Rx/Runtime/Triggers/LobbyCallbacksTriggersExtension.cs | 2,522 | C# |
using System;
using Avalonia.Threading;
using MangaReader.Avalonia.ViewModel;
using MangaReader.Core.Convertation;
using MangaReader.Core.Services.Config;
namespace MangaReader.Avalonia
{
public class ProcessModel : ViewModelBase, IProcess
{
private double percent;
private ConvertState state;
private string status;
private ProgressState progressState;
public event EventHandler<ConvertState> StateChanged;
public double Percent
{
get { return percent; }
set
{
percent = value;
this.RaisePropertyChanged();
}
}
public bool IsIndeterminate
{
get { return this.ProgressState == ProgressState.Indeterminate; }
}
public ProgressState ProgressState
{
get { return progressState; }
set
{
progressState = value;
RaisePropertyChanged();
RaisePropertyChanged(nameof(IsIndeterminate));
}
}
public string Status
{
get { return status; }
set
{
status = value;
RaisePropertyChanged();
}
}
public Version Version { get; set; }
public ConvertState State
{
get { return state; }
set
{
if (!Equals(value, state))
{
state = value;
RaisePropertyChanged();
OnStateChanged(value);
}
}
}
public ProcessModel()
{
this.Percent = 0;
this.ProgressState = ProgressState.Indeterminate;
this.Status = string.Empty;
this.Version = AppConfig.Version;
this.State = ConvertState.None;
}
protected virtual void OnStateChanged(ConvertState newState)
{
if (Dispatcher.UIThread.CheckAccess())
StateChanged?.Invoke(this, newState);
else
Dispatcher.UIThread.InvokeAsync(() => StateChanged?.Invoke(this, newState));
}
}
}
| 21.11236 | 84 | 0.616285 | [
"MIT"
] | Kadantte/MangaReader | MangaReader.Avalonia/ProcessModel.cs | 1,881 | C# |
using System;
using System.Collections.Generic;
using System.IO;
namespace mapgenerator
{
class mapgenerator
{
static void WriteFieldMember(TextWriter writer, MapField field)
{
string type = String.Empty;
switch (field.Type)
{
case FieldType.BOOL:
type = "bool";
break;
case FieldType.F32:
type = "float";
break;
case FieldType.F64:
type = "double";
break;
case FieldType.IPPORT:
case FieldType.U16:
type = "ushort";
break;
case FieldType.IPADDR:
case FieldType.U32:
type = "uint";
break;
case FieldType.LLQuaternion:
type = "Quaternion";
break;
case FieldType.LLUUID:
type = "UUID";
break;
case FieldType.LLVector3:
type = "Vector3";
break;
case FieldType.LLVector3d:
type = "Vector3d";
break;
case FieldType.LLVector4:
type = "Vector4";
break;
case FieldType.S16:
type = "short";
break;
case FieldType.S32:
type = "int";
break;
case FieldType.S8:
type = "sbyte";
break;
case FieldType.U64:
type = "ulong";
break;
case FieldType.U8:
type = "byte";
break;
case FieldType.Fixed:
type = "byte[]";
break;
}
if (field.Type != FieldType.Variable)
{
//writer.WriteLine(" /// <summary>" + field.Name + " field</summary>");
writer.WriteLine(" public " + type + " " + field.Name + ";");
}
else
{
writer.WriteLine(" public byte[] " + field.Name + ";");
//writer.WriteLine(" private byte[] _" + field.Name.ToLower() + ";");
////writer.WriteLine(" /// <summary>" + field.Name + " field</summary>");
//writer.WriteLine(" public byte[] " + field.Name + Environment.NewLine + " {");
//writer.WriteLine(" get { return _" + field.Name.ToLower() + "; }");
//writer.WriteLine(" set" + Environment.NewLine + " {");
//writer.WriteLine(" if (value == null) { _" +
// field.Name.ToLower() + " = null; return; }");
//writer.WriteLine(" if (value.Length > " +
// ((field.Count == 1) ? "255" : "1100") + ") { throw new OverflowException(" +
// "\"Value exceeds " + ((field.Count == 1) ? "255" : "1100") + " characters\"); }");
//writer.WriteLine(" else { _" + field.Name.ToLower() +
// " = new byte[value.Length]; Buffer.BlockCopy(value, 0, _" +
// field.Name.ToLower() + ", 0, value.Length); }");
//writer.WriteLine(" }" + Environment.NewLine + " }");
}
}
static void WriteFieldFromBytes(TextWriter writer, MapField field)
{
switch (field.Type)
{
case FieldType.BOOL:
writer.WriteLine(" " +
field.Name + " = (bytes[i++] != 0) ? (bool)true : (bool)false;");
break;
case FieldType.F32:
writer.WriteLine(" " +
field.Name + " = Utils.BytesToFloat(bytes, i); i += 4;");
break;
case FieldType.F64:
writer.WriteLine(" " +
field.Name + " = Utils.BytesToDouble(bytes, i); i += 8;");
break;
case FieldType.Fixed:
writer.WriteLine(" " + field.Name + " = new byte[" + field.Count + "];");
writer.WriteLine(" Buffer.BlockCopy(bytes, i, " + field.Name +
", 0, " + field.Count + "); i += " + field.Count + ";");
break;
case FieldType.IPADDR:
case FieldType.U32:
writer.WriteLine(" " + field.Name +
" = (uint)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24));");
break;
case FieldType.IPPORT:
// IPPORT is big endian while U16/S16 are little endian. Go figure
writer.WriteLine(" " + field.Name +
" = (ushort)((bytes[i++] << 8) + bytes[i++]);");
break;
case FieldType.U16:
writer.WriteLine(" " + field.Name +
" = (ushort)(bytes[i++] + (bytes[i++] << 8));");
break;
case FieldType.LLQuaternion:
writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i, true); i += 12;");
break;
case FieldType.LLUUID:
writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i); i += 16;");
break;
case FieldType.LLVector3:
writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i); i += 12;");
break;
case FieldType.LLVector3d:
writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i); i += 24;");
break;
case FieldType.LLVector4:
writer.WriteLine(" " + field.Name + ".FromBytes(bytes, i); i += 16;");
break;
case FieldType.S16:
writer.WriteLine(" " + field.Name +
" = (short)(bytes[i++] + (bytes[i++] << 8));");
break;
case FieldType.S32:
writer.WriteLine(" " + field.Name +
" = (int)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24));");
break;
case FieldType.S8:
writer.WriteLine(" " + field.Name +
" = (sbyte)bytes[i++];");
break;
case FieldType.U64:
writer.WriteLine(" " + field.Name +
" = (ulong)((ulong)bytes[i++] + ((ulong)bytes[i++] << 8) + " +
"((ulong)bytes[i++] << 16) + ((ulong)bytes[i++] << 24) + " +
"((ulong)bytes[i++] << 32) + ((ulong)bytes[i++] << 40) + " +
"((ulong)bytes[i++] << 48) + ((ulong)bytes[i++] << 56));");
break;
case FieldType.U8:
writer.WriteLine(" " + field.Name +
" = (byte)bytes[i++];");
break;
case FieldType.Variable:
if (field.Count == 1)
{
writer.WriteLine(" length = bytes[i++];");
}
else
{
writer.WriteLine(" length = (bytes[i++] + (bytes[i++] << 8));");
}
writer.WriteLine(" " + field.Name + " = new byte[length];");
writer.WriteLine(" Buffer.BlockCopy(bytes, i, " + field.Name + ", 0, length); i += length;");
break;
default:
writer.WriteLine("!!! ERROR: Unhandled FieldType: " + field.Type.ToString() + " !!!");
break;
}
}
static void WriteFieldToBytes(TextWriter writer, MapField field)
{
writer.Write(" ");
switch (field.Type)
{
case FieldType.BOOL:
writer.WriteLine("bytes[i++] = (byte)((" + field.Name + ") ? 1 : 0);");
break;
case FieldType.F32:
writer.WriteLine("Utils.FloatToBytes(" + field.Name + ", bytes, i); i += 4;");
break;
case FieldType.F64:
writer.WriteLine("Utils.DoubleToBytes(" + field.Name + ", bytes, i); i += 8;");
break;
case FieldType.Fixed:
writer.WriteLine("Buffer.BlockCopy(" + field.Name + ", 0, bytes, i, " + field.Count + ");" +
"i += " + field.Count + ";");
break;
case FieldType.IPPORT:
// IPPORT is big endian while U16/S16 is little endian. Go figure
writer.WriteLine("bytes[i++] = (byte)((" + field.Name + " >> 8) % 256);");
writer.WriteLine(" bytes[i++] = (byte)(" + field.Name + " % 256);");
break;
case FieldType.U16:
case FieldType.S16:
writer.WriteLine("bytes[i++] = (byte)(" + field.Name + " % 256);");
writer.WriteLine(" bytes[i++] = (byte)((" + field.Name + " >> 8) % 256);");
break;
case FieldType.LLQuaternion:
case FieldType.LLVector3:
writer.WriteLine(field.Name + ".ToBytes(bytes, i); i += 12;");
break;
case FieldType.LLUUID:
case FieldType.LLVector4:
writer.WriteLine(field.Name + ".ToBytes(bytes, i); i += 16;");
break;
case FieldType.LLVector3d:
writer.WriteLine(field.Name + ".ToBytes(bytes, i); i += 24;");
break;
case FieldType.U8:
writer.WriteLine("bytes[i++] = " + field.Name + ";");
break;
case FieldType.S8:
writer.WriteLine("bytes[i++] = (byte)" + field.Name + ";");
break;
case FieldType.IPADDR:
case FieldType.U32:
writer.WriteLine("Utils.UIntToBytes(" + field.Name + ", bytes, i); i += 4;");
break;
case FieldType.S32:
writer.WriteLine("Utils.IntToBytes(" + field.Name + ", bytes, i); i += 4;");
break;
case FieldType.U64:
writer.WriteLine("Utils.UInt64ToBytes(" + field.Name + ", bytes, i); i += 8;");
break;
case FieldType.Variable:
//writer.WriteLine("if(" + field.Name + " == null) { Console.WriteLine(\"Warning: " + field.Name + " is null, in \" + this.GetType()); }");
//writer.Write(" ");
if (field.Count == 1)
{
writer.WriteLine("bytes[i++] = (byte)" + field.Name + ".Length;");
}
else
{
writer.WriteLine("bytes[i++] = (byte)(" + field.Name + ".Length % 256);");
writer.WriteLine(" bytes[i++] = (byte)((" +
field.Name + ".Length >> 8) % 256);");
}
writer.WriteLine(" Buffer.BlockCopy(" + field.Name + ", 0, bytes, i, " +
field.Name + ".Length); " + "i += " + field.Name + ".Length;");
break;
default:
writer.WriteLine("!!! ERROR: Unhandled FieldType: " + field.Type.ToString() + " !!!");
break;
}
}
static int GetFieldLength(TextWriter writer, MapField field)
{
switch (field.Type)
{
case FieldType.BOOL:
case FieldType.U8:
case FieldType.S8:
return 1;
case FieldType.U16:
case FieldType.S16:
case FieldType.IPPORT:
return 2;
case FieldType.U32:
case FieldType.S32:
case FieldType.F32:
case FieldType.IPADDR:
return 4;
case FieldType.U64:
case FieldType.F64:
return 8;
case FieldType.LLVector3:
case FieldType.LLQuaternion:
return 12;
case FieldType.LLUUID:
case FieldType.LLVector4:
return 16;
case FieldType.LLVector3d:
return 24;
case FieldType.Fixed:
return field.Count;
case FieldType.Variable:
return 0;
default:
writer.WriteLine("!!! ERROR: Unhandled FieldType " + field.Type.ToString() + " !!!");
return 0;
}
}
static void WriteBlockClass(TextWriter writer, MapBlock block, MapPacket packet)
{
int variableFieldCountBytes = 0;
//writer.WriteLine(" /// <summary>" + block.Name + " block</summary>");
writer.WriteLine(" /// <exclude/>");
writer.WriteLine(" public sealed class " + block.Name + "Block : PacketBlock" + Environment.NewLine + " {");
foreach (MapField field in block.Fields)
{
WriteFieldMember(writer, field);
if (field.Type == FieldType.Variable) { variableFieldCountBytes += field.Count; }
}
// Length property
writer.WriteLine("");
//writer.WriteLine(" /// <summary>Length of this block serialized in bytes</summary>");
writer.WriteLine(" public override int Length" + Environment.NewLine +
" {" + Environment.NewLine +
" get" + Environment.NewLine +
" {");
int length = variableFieldCountBytes;
// Figure out the length of this block
foreach (MapField field in block.Fields)
{
length += GetFieldLength(writer, field);
}
if (variableFieldCountBytes == 0)
{
writer.WriteLine(" return " + length + ";");
}
else
{
writer.WriteLine(" int length = " + length + ";");
foreach (MapField field in block.Fields)
{
if (field.Type == FieldType.Variable)
{
writer.WriteLine(" if (" + field.Name +
" != null) { length += " + field.Name + ".Length; }");
}
}
writer.WriteLine(" return length;");
}
writer.WriteLine(" }" + Environment.NewLine + " }" + Environment.NewLine);
// Default constructor
//writer.WriteLine(" /// <summary>Default constructor</summary>");
writer.WriteLine(" public " + block.Name + "Block() { }");
// Constructor for building the class from bytes
//writer.WriteLine(" /// <summary>Constructor for building the block from a byte array</summary>");
writer.WriteLine(" public " + block.Name + "Block(byte[] bytes, ref int i)" + Environment.NewLine +
" {" + Environment.NewLine +
" FromBytes(bytes, ref i);" + Environment.NewLine +
" }" + Environment.NewLine);
// Initiates instance variables from a byte message
writer.WriteLine(" public override void FromBytes(byte[] bytes, ref int i)" + Environment.NewLine +
" {");
// Declare a length variable if we need it for variable fields in this constructor
if (variableFieldCountBytes > 0) { writer.WriteLine(" int length;"); }
// Start of the try catch block
writer.WriteLine(" try" + Environment.NewLine + " {");
foreach (MapField field in block.Fields)
{
WriteFieldFromBytes(writer, field);
}
writer.WriteLine(" }" + Environment.NewLine +
" catch (Exception)" + Environment.NewLine +
" {" + Environment.NewLine +
" throw new MalformedDataException();" + Environment.NewLine +
" }" + Environment.NewLine + " }" + Environment.NewLine);
// ToBytes() function
//writer.WriteLine(" /// <summary>Serialize this block to a byte array</summary>");
writer.WriteLine(" public override void ToBytes(byte[] bytes, ref int i)" + Environment.NewLine +
" {");
foreach (MapField field in block.Fields)
{
WriteFieldToBytes(writer, field);
}
writer.WriteLine(" }" + Environment.NewLine);
writer.WriteLine(" }" + Environment.NewLine);
}
static void WritePacketClass(TextWriter writer, MapPacket packet)
{
bool hasVariableBlocks = false;
string sanitizedName;
//writer.WriteLine(" /// <summary>" + packet.Name + " packet</summary>");
writer.WriteLine(" /// <exclude/>");
writer.WriteLine(" public sealed class " + packet.Name + "Packet : Packet" + Environment.NewLine + " {");
// Write out each block class
foreach (MapBlock block in packet.Blocks)
{
WriteBlockClass(writer, block, packet);
}
// Length member
writer.WriteLine(" public override int Length" + Environment.NewLine +
" {" + Environment.NewLine + " get" + Environment.NewLine +
" {");
int length = 0;
if (packet.Frequency == PacketFrequency.Low) { length = 10; }
else if (packet.Frequency == PacketFrequency.Medium) { length = 8; }
else { length = 7; }
foreach (MapBlock block in packet.Blocks)
{
if (block.Count == -1)
{
hasVariableBlocks = true;
++length;
}
}
writer.WriteLine(" int length = " + length + ";");
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
// Variable count block
writer.WriteLine(" for (int j = 0; j < " + sanitizedName + ".Length; j++)");
writer.WriteLine(" length += " + sanitizedName + "[j].Length;");
}
else if (block.Count == 1)
{
writer.WriteLine(" length += " + sanitizedName + ".Length;");
}
else
{
// Multiple count block
writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++)");
writer.WriteLine(" length += " + sanitizedName + "[j].Length;");
}
}
writer.WriteLine(" return length;");
writer.WriteLine(" }" + Environment.NewLine + " }");
// Block members
foreach (MapBlock block in packet.Blocks)
{
// TODO: More thorough name blacklisting
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
//writer.WriteLine(" /// <summary>" + block.Name + " block</summary>");
writer.WriteLine(" public " + block.Name + "Block" +
((block.Count != 1) ? "[]" : "") + " " + sanitizedName + ";");
}
writer.WriteLine("");
// Default constructor
//writer.WriteLine(" /// <summary>Default constructor</summary>");
writer.WriteLine(" public " + packet.Name + "Packet()" + Environment.NewLine + " {");
writer.WriteLine(" HasVariableBlocks = " + hasVariableBlocks.ToString().ToLowerInvariant() + ";");
writer.WriteLine(" Type = PacketType." + packet.Name + ";");
writer.WriteLine(" Trusted = " + (packet.Trusted ? "true;" : "false;"));
writer.WriteLine(" Header = new Header();");
writer.WriteLine(" Header.Frequency = PacketFrequency." + packet.Frequency + ";");
writer.WriteLine(" Header.ID = " + packet.ID + ";");
writer.WriteLine(" Header.Reliable = true;"); // Turn the reliable flag on by default
if (packet.Encoded) { writer.WriteLine(" Header.Zerocoded = true;"); }
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == 1)
{
// Single count block
writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block();");
}
else if (block.Count == -1)
{
// Variable count block
writer.WriteLine(" " + sanitizedName + " = null;");
}
else
{
// Multiple count block
writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[" + block.Count + "];");
}
}
writer.WriteLine(" }" + Environment.NewLine);
// Constructor that takes a byte array and beginning position only (no prebuilt header)
bool seenVariable = false;
//writer.WriteLine(" /// <summary>Constructor that takes a byte array and beginning position (no prebuilt header)</summary>");
writer.WriteLine(" public " + packet.Name + "Packet(byte[] bytes, ref int i) : this()" + Environment.NewLine +
" {" + Environment.NewLine +
" int packetEnd = bytes.Length - 1;" + Environment.NewLine +
" FromBytes(bytes, ref i, ref packetEnd, null);" + Environment.NewLine +
" }" + Environment.NewLine);
writer.WriteLine(" override public void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[] zeroBuffer)" + Environment.NewLine + " {");
writer.WriteLine(" Header.FromBytes(bytes, ref i, ref packetEnd);");
writer.WriteLine(" if (Header.Zerocoded && zeroBuffer != null)");
writer.WriteLine(" {");
writer.WriteLine(" packetEnd = Helpers.ZeroDecode(bytes, packetEnd + 1, zeroBuffer) - 1;");
writer.WriteLine(" bytes = zeroBuffer;");
writer.WriteLine(" }");
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == 1)
{
// Single count block
writer.WriteLine(" " + sanitizedName + ".FromBytes(bytes, ref i);");
}
else if (block.Count == -1)
{
// Variable count block
if (!seenVariable)
{
writer.WriteLine(" int count = (int)bytes[i++];");
seenVariable = true;
}
else
{
writer.WriteLine(" count = (int)bytes[i++];");
}
writer.WriteLine(" if(" + sanitizedName + " == null || " + sanitizedName + ".Length != " + block.Count + ") {");
writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[count];");
writer.WriteLine(" for(int j = 0; j < count; j++)");
writer.WriteLine(" { " + sanitizedName + "[j] = new " + block.Name + "Block(); }");
writer.WriteLine(" }");
writer.WriteLine(" for (int j = 0; j < count; j++)");
writer.WriteLine(" { " + sanitizedName + "[j].FromBytes(bytes, ref i); }");
}
else
{
// Multiple count block
writer.WriteLine(" if(" + sanitizedName + " == null || " + sanitizedName + ".Length != " + block.Count + ") {");
writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[" + block.Count + "];");
writer.WriteLine(" for(int j = 0; j < " + block.Count + "; j++)");
writer.WriteLine(" { " + sanitizedName + "[j] = new " + block.Name + "Block(); }");
writer.WriteLine(" }");
writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++)");
writer.WriteLine(" { " + sanitizedName + "[j].FromBytes(bytes, ref i); }");
}
}
writer.WriteLine(" }" + Environment.NewLine);
seenVariable = false;
// Constructor that takes a byte array and a prebuilt header
//writer.WriteLine(" /// <summary>Constructor that takes a byte array and a prebuilt header</summary>");
writer.WriteLine(" public " + packet.Name + "Packet(Header head, byte[] bytes, ref int i): this()" + Environment.NewLine +
" {" + Environment.NewLine +
" int packetEnd = bytes.Length - 1;" + Environment.NewLine +
" FromBytes(head, bytes, ref i, ref packetEnd);" + Environment.NewLine +
" }" + Environment.NewLine);
writer.WriteLine(" override public void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd)" + Environment.NewLine +
" {");
writer.WriteLine(" Header = header;");
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == 1)
{
// Single count block
writer.WriteLine(" " + sanitizedName + ".FromBytes(bytes, ref i);");
}
else if (block.Count == -1)
{
// Variable count block
if (!seenVariable)
{
writer.WriteLine(" int count = (int)bytes[i++];");
seenVariable = true;
}
else
{
writer.WriteLine(" count = (int)bytes[i++];");
}
writer.WriteLine(" if(" + sanitizedName + " == null || " + sanitizedName + ".Length != count) {");
writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[count];");
writer.WriteLine(" for(int j = 0; j < count; j++)");
writer.WriteLine(" { " + sanitizedName + "[j] = new " + block.Name + "Block(); }");
writer.WriteLine(" }");
writer.WriteLine(" for (int j = 0; j < count; j++)");
writer.WriteLine(" { " + sanitizedName + "[j].FromBytes(bytes, ref i); }");
}
else
{
// Multiple count block
writer.WriteLine(" if(" + sanitizedName + " == null || " + sanitizedName + ".Length != " + block.Count + ") {");
writer.WriteLine(" " + sanitizedName + " = new " + block.Name + "Block[" + block.Count + "];");
writer.WriteLine(" for(int j = 0; j < " + block.Count + "; j++)");
writer.WriteLine(" { " + sanitizedName + "[j] = new " + block.Name + "Block(); }");
writer.WriteLine(" }");
writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++)");
writer.WriteLine(" { " + sanitizedName + "[j].FromBytes(bytes, ref i); }");
}
}
writer.WriteLine(" }" + Environment.NewLine);
#region ToBytes() Function
//writer.WriteLine(" /// <summary>Serialize this packet to a byte array</summary><returns>A byte array containing the serialized packet</returns>");
writer.WriteLine(" public override byte[] ToBytes()" + Environment.NewLine + " {");
writer.Write(" int length = ");
if (packet.Frequency == PacketFrequency.Low) { writer.WriteLine("10;"); }
else if (packet.Frequency == PacketFrequency.Medium) { writer.WriteLine("8;"); }
else { writer.WriteLine("7;"); }
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == 1)
{
// Single count block
writer.WriteLine(" length += " + sanitizedName + ".Length;");
}
}
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
writer.WriteLine(" length++;");
writer.WriteLine(" for (int j = 0; j < " + sanitizedName +
".Length; j++) { length += " + sanitizedName + "[j].Length; }");
}
else if (block.Count > 1)
{
writer.WriteLine(" for (int j = 0; j < " + block.Count +
"; j++) { length += " + sanitizedName + "[j].Length; }");
}
}
writer.WriteLine(" if (Header.AckList != null && Header.AckList.Length > 0) { length += Header.AckList.Length * 4 + 1; }");
writer.WriteLine(" byte[] bytes = new byte[length];");
writer.WriteLine(" int i = 0;");
writer.WriteLine(" Header.ToBytes(bytes, ref i);");
foreach (MapBlock block in packet.Blocks)
{
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
// Variable count block
writer.WriteLine(" bytes[i++] = (byte)" + sanitizedName + ".Length;");
writer.WriteLine(" for (int j = 0; j < " + sanitizedName +
".Length; j++) { " + sanitizedName + "[j].ToBytes(bytes, ref i); }");
}
else if (block.Count == 1)
{
writer.WriteLine(" " + sanitizedName + ".ToBytes(bytes, ref i);");
}
else
{
// Multiple count block
writer.WriteLine(" for (int j = 0; j < " + block.Count +
"; j++) { " + sanitizedName + "[j].ToBytes(bytes, ref i); }");
}
}
writer.WriteLine(" if (Header.AckList != null && Header.AckList.Length > 0) { Header.AcksToBytes(bytes, ref i); }");
writer.WriteLine(" return bytes;" + Environment.NewLine + " }" + Environment.NewLine);
#endregion ToBytes() Function
WriteToBytesMultiple(writer, packet);
writer.WriteLine(" }" + Environment.NewLine);
}
static void WriteToBytesMultiple(TextWriter writer, MapPacket packet)
{
writer.WriteLine(
" public override byte[][] ToBytesMultiple()" + Environment.NewLine +
" {");
// Check if there are any variable blocks
bool hasVariable = false;
bool cannotSplit = false;
foreach (MapBlock block in packet.Blocks)
{
if (block.Count == -1)
{
hasVariable = true;
}
else if (hasVariable)
{
// A fixed or single block showed up after a variable count block.
// Our automatic splitting algorithm won't work for this packet
cannotSplit = true;
break;
}
}
if (hasVariable && !cannotSplit)
{
writer.WriteLine(
" System.Collections.Generic.List<byte[]> packets = new System.Collections.Generic.List<byte[]>();");
writer.WriteLine(
" int i = 0;");
writer.Write(
" int fixedLength = ");
if (packet.Frequency == PacketFrequency.Low) { writer.WriteLine("10;"); }
else if (packet.Frequency == PacketFrequency.Medium) { writer.WriteLine("8;"); }
else { writer.WriteLine("7;"); }
writer.WriteLine();
// ACK serialization
writer.WriteLine(" byte[] ackBytes = null;");
writer.WriteLine(" int acksLength = 0;");
writer.WriteLine(" if (Header.AckList != null && Header.AckList.Length > 0) {");
writer.WriteLine(" Header.AppendedAcks = true;");
writer.WriteLine(" ackBytes = new byte[Header.AckList.Length * 4 + 1];");
writer.WriteLine(" Header.AcksToBytes(ackBytes, ref acksLength);");
writer.WriteLine(" }");
writer.WriteLine();
// Count fixed blocks
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == 1)
{
// Single count block
writer.WriteLine(" fixedLength += " + sanitizedName + ".Length;");
}
else if (block.Count > 0)
{
// Fixed count block
writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++) { fixedLength += " + sanitizedName + "[j].Length; }");
}
}
// Serialize fixed blocks
writer.WriteLine(
" byte[] fixedBytes = new byte[fixedLength];");
writer.WriteLine(
" Header.ToBytes(fixedBytes, ref i);");
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == 1)
{
// Single count block
writer.WriteLine(" " + sanitizedName + ".ToBytes(fixedBytes, ref i);");
}
else if (block.Count > 0)
{
// Fixed count block
writer.WriteLine(" for (int j = 0; j < " + block.Count + "; j++) { " + sanitizedName + "[j].ToBytes(fixedBytes, ref i); }");
}
}
int variableCountBlock = 0;
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
// Variable count block
++variableCountBlock;
}
}
writer.WriteLine(" fixedLength += " + variableCountBlock + ";");
writer.WriteLine();
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
// Variable count block
writer.WriteLine(" int " + sanitizedName + "Start = 0;");
}
}
writer.WriteLine(" do");
writer.WriteLine(" {");
// Count how many variable blocks can go in this packet
writer.WriteLine(" int variableLength = 0;");
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
// Variable count block
writer.WriteLine(" int " + sanitizedName + "Count = 0;");
}
}
writer.WriteLine();
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
// Variable count block
writer.WriteLine(" i = " + sanitizedName + "Start;");
writer.WriteLine(" while (fixedLength + variableLength + acksLength < Packet.MTU && i < " + sanitizedName + ".Length) {");
writer.WriteLine(" int blockLength = " + sanitizedName + "[i].Length;");
writer.WriteLine(" if (fixedLength + variableLength + blockLength + acksLength <= MTU || i == " + sanitizedName + "Start) {");
writer.WriteLine(" variableLength += blockLength;");
writer.WriteLine(" ++" + sanitizedName + "Count;");
writer.WriteLine(" }");
writer.WriteLine(" else { break; }");
writer.WriteLine(" ++i;");
writer.WriteLine(" }");
writer.WriteLine();
}
}
// Create the packet
writer.WriteLine(" byte[] packet = new byte[fixedLength + variableLength + acksLength];");
writer.WriteLine(" int length = fixedBytes.Length;");
writer.WriteLine(" Buffer.BlockCopy(fixedBytes, 0, packet, 0, length);");
// Remove the appended ACKs flag from subsequent packets
writer.WriteLine(" if (packets.Count > 0) { packet[0] = (byte)(packet[0] & ~0x10); }");
writer.WriteLine();
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
writer.WriteLine(" packet[length++] = (byte)" + sanitizedName + "Count;");
writer.WriteLine(" for (i = " + sanitizedName + "Start; i < " + sanitizedName + "Start + "
+ sanitizedName + "Count; i++) { " + sanitizedName + "[i].ToBytes(packet, ref length); }");
writer.WriteLine(" " + sanitizedName + "Start += " + sanitizedName + "Count;");
writer.WriteLine();
}
}
// ACK appending
writer.WriteLine(" if (acksLength > 0) {");
writer.WriteLine(" Buffer.BlockCopy(ackBytes, 0, packet, length, acksLength);");
writer.WriteLine(" acksLength = 0;");
writer.WriteLine(" }");
writer.WriteLine();
writer.WriteLine(" packets.Add(packet);");
writer.WriteLine(" } while (");
bool first = true;
foreach (MapBlock block in packet.Blocks)
{
string sanitizedName;
if (block.Name == "Header") { sanitizedName = "_" + block.Name; }
else { sanitizedName = block.Name; }
if (block.Count == -1)
{
if (first) first = false;
else writer.WriteLine(" ||");
// Variable count block
writer.Write(" " + sanitizedName + "Start < " + sanitizedName + ".Length");
}
}
writer.WriteLine(");");
writer.WriteLine();
writer.WriteLine(" return packets.ToArray();");
writer.WriteLine(" }");
}
else
{
writer.WriteLine(" return new byte[][] { ToBytes() };");
writer.WriteLine(" }");
}
}
static int Main(string[] args)
{
ProtocolManager protocol;
List<string> unused = new List<string>();
TextWriter writer;
try
{
if (args.Length != 4)
{
Console.WriteLine("Usage: [message_template.msg] [template.cs] [unusedpackets.txt] [_Packets_.cs]");
return -1;
}
writer = new StreamWriter(args[3]);
protocol = new ProtocolManager(args[0]);
// Build a list of unused packets
using (StreamReader unusedReader = new StreamReader(args[2]))
{
while (unusedReader.Peek() >= 0)
{
unused.Add(unusedReader.ReadLine().Trim());
}
}
// Read in the template.cs file and write it to our output
TextReader reader = new StreamReader(args[1]);
writer.WriteLine(reader.ReadToEnd());
reader.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return -2;
}
// Prune all of the unused packets out of the protocol
int i = 0;
foreach (MapPacket packet in protocol.LowMaps)
{
if (packet != null && unused.Contains(packet.Name))
protocol.LowMaps[i] = null;
i++;
}
i = 0;
foreach (MapPacket packet in protocol.MediumMaps)
{
if (packet != null && unused.Contains(packet.Name))
protocol.MediumMaps[i] = null;
i++;
}
i = 0;
foreach (MapPacket packet in protocol.HighMaps)
{
if (packet != null && unused.Contains(packet.Name))
protocol.HighMaps[i] = null;
i++;
}
// Write the PacketType enum
writer.WriteLine(" public enum PacketType" + Environment.NewLine + " {" + Environment.NewLine +
" /// <summary>A generic value, not an actual packet type</summary>" + Environment.NewLine +
" Default,");
foreach (MapPacket packet in protocol.LowMaps)
if (packet != null)
writer.WriteLine(" " + packet.Name + " = " + (0x10000 | packet.ID) + ",");
foreach (MapPacket packet in protocol.MediumMaps)
if (packet != null)
writer.WriteLine(" " + packet.Name + " = " + (0x20000 | packet.ID) + ",");
foreach (MapPacket packet in protocol.HighMaps)
if (packet != null)
writer.WriteLine(" " + packet.Name + " = " + (0x30000 | packet.ID) + ",");
writer.WriteLine(" }" + Environment.NewLine);
// Write the base Packet class
writer.WriteLine(
" public abstract partial class Packet" + Environment.NewLine + " {" + Environment.NewLine +
" public const int MTU = 1200;" + Environment.NewLine +
Environment.NewLine +
" public Header Header;" + Environment.NewLine +
" public bool HasVariableBlocks;" + Environment.NewLine +
" public PacketType Type;" + Environment.NewLine +
" public bool Trusted;" + Environment.NewLine +
" public abstract int Length { get; }" + Environment.NewLine +
" public abstract void FromBytes(byte[] bytes, ref int i, ref int packetEnd, byte[] zeroBuffer);" + Environment.NewLine +
" public abstract void FromBytes(Header header, byte[] bytes, ref int i, ref int packetEnd);" + Environment.NewLine +
" public abstract byte[] ToBytes();" + Environment.NewLine +
" public abstract byte[][] ToBytesMultiple();"
);
writer.WriteLine();
// Write the Packet.GetType() function
writer.WriteLine(
" public static PacketType GetType(ushort id, PacketFrequency frequency)" + Environment.NewLine +
" {" + Environment.NewLine +
" switch (frequency)" + Environment.NewLine +
" {" + Environment.NewLine +
" case PacketFrequency.Low:" + Environment.NewLine +
" switch (id)" + Environment.NewLine +
" {");
foreach (MapPacket packet in protocol.LowMaps)
if (packet != null)
writer.WriteLine(" case " + packet.ID + ": return PacketType." + packet.Name + ";");
writer.WriteLine(" }" + Environment.NewLine +
" break;" + Environment.NewLine +
" case PacketFrequency.Medium:" + Environment.NewLine +
" switch (id)" + Environment.NewLine + " {");
foreach (MapPacket packet in protocol.MediumMaps)
if (packet != null)
writer.WriteLine(" case " + packet.ID + ": return PacketType." + packet.Name + ";");
writer.WriteLine(" }" + Environment.NewLine +
" break;" + Environment.NewLine +
" case PacketFrequency.High:" + Environment.NewLine +
" switch (id)" + Environment.NewLine + " {");
foreach (MapPacket packet in protocol.HighMaps)
if (packet != null)
writer.WriteLine(" case " + packet.ID + ": return PacketType." + packet.Name + ";");
writer.WriteLine(" }" + Environment.NewLine +
" break;" + Environment.NewLine + " }" + Environment.NewLine + Environment.NewLine +
" return PacketType.Default;" + Environment.NewLine + " }" + Environment.NewLine);
// Write the Packet.BuildPacket(PacketType) function
writer.WriteLine(" public static Packet BuildPacket(PacketType type)");
writer.WriteLine(" {");
foreach (MapPacket packet in protocol.HighMaps)
if (packet != null)
writer.WriteLine(" if(type == PacketType." + packet.Name + ") return new " + packet.Name + "Packet();");
foreach (MapPacket packet in protocol.MediumMaps)
if (packet != null)
writer.WriteLine(" if(type == PacketType." + packet.Name + ") return new " + packet.Name + "Packet();");
foreach (MapPacket packet in protocol.LowMaps)
if (packet != null)
writer.WriteLine(" if(type == PacketType." + packet.Name + ") return new " + packet.Name + "Packet();");
writer.WriteLine(" return null;" + Environment.NewLine);
writer.WriteLine(" }");
// Write the Packet.BuildPacket() function
writer.WriteLine(@"
public static Packet BuildPacket(byte[] packetBuffer, ref int packetEnd, byte[] zeroBuffer)
{
byte[] bytes;
int i = 0;
Header header = Header.BuildHeader(packetBuffer, ref i, ref packetEnd);
if (header.Zerocoded)
{
packetEnd = Helpers.ZeroDecode(packetBuffer, packetEnd + 1, zeroBuffer) - 1;
bytes = zeroBuffer;
}
else
{
bytes = packetBuffer;
}
Array.Clear(bytes, packetEnd + 1, bytes.Length - packetEnd - 1);
switch (header.Frequency)
{
case PacketFrequency.Low:
switch (header.ID)
{");
foreach (MapPacket packet in protocol.LowMaps)
if (packet != null)
writer.WriteLine(" case " + packet.ID + ": return new " + packet.Name + "Packet(header, bytes, ref i);");
writer.WriteLine(@"
}
break;
case PacketFrequency.Medium:
switch (header.ID)
{");
foreach (MapPacket packet in protocol.MediumMaps)
if (packet != null)
writer.WriteLine(" case " + packet.ID + ": return new " + packet.Name + "Packet(header, bytes, ref i);");
writer.WriteLine(@"
}
break;
case PacketFrequency.High:
switch (header.ID)
{");
foreach (MapPacket packet in protocol.HighMaps)
if (packet != null)
writer.WriteLine(" case " + packet.ID + ": return new " + packet.Name + "Packet(header, bytes, ref i);");
writer.WriteLine(@"
}
break;
}
throw new MalformedDataException(""Unknown packet ID "" + header.Frequency + "" "" + header.ID);
}
}");
// Write the packet classes
foreach (MapPacket packet in protocol.LowMaps)
if (packet != null) { WritePacketClass(writer, packet); }
foreach (MapPacket packet in protocol.MediumMaps)
if (packet != null) { WritePacketClass(writer, packet); }
foreach (MapPacket packet in protocol.HighMaps)
if (packet != null) { WritePacketClass(writer, packet); }
// Finish up
writer.WriteLine("}");
writer.Close();
return 0;
}
}
}
| 49.119258 | 170 | 0.418862 | [
"BSD-3-Clause"
] | StolenRuby/libopenmetaverse | Programs/mapgenerator/mapgenerator.cs | 55,603 | 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/SpatialAudioMetadata.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using static TerraFX.Interop.Windows.IID;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="ISpatialAudioMetadataItemsBuffer" /> struct.</summary>
[SupportedOSPlatform("windows10.0.15063.0")]
public static unsafe partial class ISpatialAudioMetadataItemsBufferTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="ISpatialAudioMetadataItemsBuffer" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(ISpatialAudioMetadataItemsBuffer).GUID, Is.EqualTo(IID_ISpatialAudioMetadataItemsBuffer));
}
/// <summary>Validates that the <see cref="ISpatialAudioMetadataItemsBuffer" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<ISpatialAudioMetadataItemsBuffer>(), Is.EqualTo(sizeof(ISpatialAudioMetadataItemsBuffer)));
}
/// <summary>Validates that the <see cref="ISpatialAudioMetadataItemsBuffer" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(ISpatialAudioMetadataItemsBuffer).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="ISpatialAudioMetadataItemsBuffer" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(ISpatialAudioMetadataItemsBuffer), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(ISpatialAudioMetadataItemsBuffer), Is.EqualTo(4));
}
}
}
| 39.490566 | 145 | 0.725275 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | tests/Interop/Windows/Windows/um/SpatialAudioMetadata/ISpatialAudioMetadataItemsBufferTests.cs | 2,095 | C# |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Cell : MonoBehaviour {
//public string elementName; // Element Name
//public int elementCount = 1; // Element Count
//public Color elementColor; // Element Color
public Transform elementTransform; //Transform Element
private GameObject elementPrefab;
public item item = new item();
//Method to update UI of this cell
public void UpdateCellInterface () {
if (elementPrefab == null) {
elementPrefab = (FindObjectOfType (typeof(ElementalInventory)) as ElementalInventory).elementPrefab;
}
if (item.elementCount == 0) {
if (elementTransform != null) {
Destroy (elementTransform.gameObject);
}
return;
}
else {
if (elementTransform == null) {
//spawn a new element prefab
Transform newElement = Instantiate (elementPrefab).transform;
newElement.parent = transform;
newElement.localPosition = new Vector3 ();
newElement.localScale = new Vector3 (1f,1f,1f);
elementTransform = newElement;
}
//init UI elements
Image bgImage = SimpleMethods.getChildByTag (elementTransform, "backgroundImage").GetComponent<Image> ();
Text elementText = SimpleMethods.getChildByTag (elementTransform, "elementText").GetComponent<Text> ();
Text amountText = SimpleMethods.getChildByTag (elementTransform, "amountText").GetComponent<Text> ();
//change UI options
bgImage.color = item.elementColor;
elementText.text = item.elementName;
amountText.text = item.elementCount.ToString ();
}
}
//Change element options
public void ChangeElement (string name, int count, Color color) {
item.elementName = name;
item.elementCount = count;
item.elementColor = color;
UpdateCellInterface ();
}
//Clear element
public void ClearElement () {
item.elementCount = 0;
UpdateCellInterface ();
}
}
| 31.283333 | 108 | 0.715503 | [
"MIT"
] | LunaPg/StarFinder | Assets/Sky Inventory/Scripts/Cell.cs | 1,879 | C# |
using System.Reflection;
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("AWSSDK.Cloud9")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Cloud9. Adds support for creating and managing AWS Cloud9 development environments. AWS Cloud9 is a cloud-based integrated development environment (IDE) that you use to write, run, and debug code.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.3.100.55")] | 48.5 | 280 | 0.751933 | [
"Apache-2.0"
] | costleya/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/Cloud9/Properties/AssemblyInfo.cs | 1,552 | C# |
/*
* tilia Phoenix API
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 7.0.6
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = TiliaLabs.Phoenix.Client.SwaggerDateConverter;
namespace TiliaLabs.Phoenix.Model
{
/// <summary>
/// Per-process aggregate stats
/// </summary>
[DataContract]
public partial class ProcessStats : IEquatable<ProcessStats>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ProcessStats" /> class.
/// </summary>
/// <param name="time">time (required).</param>
/// <param name="cost">cost (required).</param>
/// <param name="process">Process (required).</param>
public ProcessStats(TimeInfo time = default(TimeInfo), CostInfo cost = default(CostInfo), string process = default(string))
{
// to ensure "time" is required (not null)
if (time == null)
{
throw new InvalidDataException("time is a required property for ProcessStats and cannot be null");
}
else
{
this.Time = time;
}
// to ensure "cost" is required (not null)
if (cost == null)
{
throw new InvalidDataException("cost is a required property for ProcessStats and cannot be null");
}
else
{
this.Cost = cost;
}
// to ensure "process" is required (not null)
if (process == null)
{
throw new InvalidDataException("process is a required property for ProcessStats and cannot be null");
}
else
{
this.Process = process;
}
}
/// <summary>
/// Gets or Sets Time
/// </summary>
[DataMember(Name="time", EmitDefaultValue=false)]
public TimeInfo Time { get; set; }
/// <summary>
/// Gets or Sets Cost
/// </summary>
[DataMember(Name="cost", EmitDefaultValue=false)]
public CostInfo Cost { get; set; }
/// <summary>
/// Process
/// </summary>
/// <value>Process</value>
[DataMember(Name="process", EmitDefaultValue=false)]
public string Process { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ProcessStats {\n");
sb.Append(" Time: ").Append(Time).Append("\n");
sb.Append(" Cost: ").Append(Cost).Append("\n");
sb.Append(" Process: ").Append(Process).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ProcessStats);
}
/// <summary>
/// Returns true if ProcessStats instances are equal
/// </summary>
/// <param name="input">Instance of ProcessStats to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ProcessStats input)
{
if (input == null)
return false;
return
(
this.Time == input.Time ||
(this.Time != null &&
this.Time.Equals(input.Time))
) &&
(
this.Cost == input.Cost ||
(this.Cost != null &&
this.Cost.Equals(input.Cost))
) &&
(
this.Process == input.Process ||
(this.Process != null &&
this.Process.Equals(input.Process))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Time != null)
hashCode = hashCode * 59 + this.Time.GetHashCode();
if (this.Cost != null)
hashCode = hashCode * 59 + this.Cost.GetHashCode();
if (this.Process != null)
hashCode = hashCode * 59 + this.Process.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 33.655556 | 140 | 0.529713 | [
"Apache-2.0"
] | matthewkayy/tilia-phoenix-client-csharp | src/TiliaLabs.Phoenix/Model/ProcessStats.cs | 6,058 | C# |
using Serilog;
namespace Exercism.Representers.CSharp.Bulk
{
internal static class Logging
{
public static void Configure() =>
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
}
} | 22.5 | 50 | 0.588889 | [
"MIT"
] | ErikSchierboom/csharp-representer | src/Exercism.Representers.CSharp.Bulk/Logging.cs | 270 | C# |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.PythonTools.Uwp.Project;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.PythonTools.Uwp {
/// <summary>
/// This is the class that implements the package exposed by this assembly.
///
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell.
/// </summary>
// This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
// a package.
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
// This attribute is needed to let the shell know that this package exposes some menus.
[Guid(GuidList.guidUwpPkgString)]
[ProvideObject(typeof(PythonUwpPropertyPage))]
[ProvideObject(typeof(PythonUwpProject))]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionHasAppContainerProject_string, PackageAutoLoadFlags.BackgroundLoad)]
[Description("Python - UWP support")] // TODO: Localization (this may not be needed)
[ProvideProjectFactory(typeof(PythonUwpProjectFactory), null, null, null, null, ".\\NullPath", LanguageVsTemplate = "Python")]
[InstalledProductRegistration("#110", "#112", AssemblyVersionInfo.Version, IconResourceID = 400)]
public sealed class PythonUwpPackage : AsyncPackage {
internal static PythonUwpPackage Instance;
/// <summary>
/// Default constructor of the package.
/// Inside this method you can place any initialization code that does not require
/// any Visual Studio service because at this point the package object is created but
/// not sited yet inside Visual Studio environment. The place to do all the other
/// initialization is the Initialize method.
/// </summary>
public PythonUwpPackage() {
Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this));
Instance = this;
}
/////////////////////////////////////////////////////////////////////////////
// Overridden Package Implementation
#region Package Members
/// <inheritdoc />
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) {
Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering InitializeAsync() of: {0}", ToString()));
await base.InitializeAsync(cancellationToken, progress);
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
RegisterProjectFactory(new PythonUwpProjectFactory(this));
}
#endregion
internal new object GetService(Type serviceType) {
return base.GetService(serviceType);
}
public EnvDTE.DTE DTE {
get {
return (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
}
}
internal static PythonUwpProject GetProject(IServiceProvider serviceProvider, string filename) {
IVsHierarchy hierarchy;
IVsRunningDocumentTable rdt = serviceProvider.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
uint itemid;
IntPtr docData = IntPtr.Zero;
uint cookie;
try {
int hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock,
filename,
out hierarchy,
out itemid,
out docData,
out cookie);
if (ErrorHandler.Succeeded(hr)) {
rdt.UnlockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, cookie);
}
var res = hierarchy as PythonUwpProject;
if (res != null) {
return res;
}
return null;
} finally {
if (docData != IntPtr.Zero) {
Marshal.Release(docData);
}
}
}
}
}
| 43.798387 | 133 | 0.660836 | [
"Apache-2.0"
] | 113771169/PTVS | Python/Product/Uwp/PythonUwpPackage.cs | 5,431 | C# |
using System.Xml.Serialization;
namespace Witsml.Data
{
public class WitsmlWellbore
{
[XmlAttribute("uid")] public string Uid { get; set; }
[XmlElement("nameWell")] public string NameWell { get; set; }
[XmlElement("name")] public string Name { get; set; }
[XmlAttribute("uidWell")] public string UidWell { get; set; }
[XmlElement("parentWellbore")] public WitsmlParentWellbore ParentWellbore { get; set; }
[XmlElement("statusWellbore")] public string StatusWellbore { get; set; }
[XmlElement("purposeWellbore")] public string PurposeWellbore { get; set; }
[XmlElement("typeWellbore")] public string TypeWellbore { get; set; }
[XmlElement("commonData")] public WitsmlCommonData CommonData { get; set; }
[XmlElement("isActive")] public string IsActive { get; set; }
}
}
| 45.315789 | 95 | 0.660859 | [
"Apache-2.0"
] | HakarK/witsml-explorer | Src/Witsml/Data/WitsmlWellbore.cs | 861 | 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.Collections.Generic;
using Newtonsoft.Json;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Cbn.Model.V20170912
{
public class CreateTrafficMarkingPolicyResponse : AcsResponse
{
private string trafficMarkingPolicyId;
private string requestId;
public string TrafficMarkingPolicyId
{
get
{
return trafficMarkingPolicyId;
}
set
{
trafficMarkingPolicyId = value;
}
}
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
}
}
| 24.122807 | 63 | 0.706909 | [
"Apache-2.0"
] | pengweiqhca/aliyun-openapi-net-sdk | aliyun-net-sdk-cbn/Cbn/Model/V20170912/CreateTrafficMarkingPolicyResponse.cs | 1,375 | 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>
// ------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS1591
#pragma warning disable CS0108
#pragma warning disable 618
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Space.Common;
using JetBrains.Space.Common.Json.Serialization;
using JetBrains.Space.Common.Json.Serialization.Polymorphism;
using JetBrains.Space.Common.Types;
namespace JetBrains.Space.Client;
public class DocsDraftsForIdEditorsTeamsPostRequest
: IPropagatePropertyAccessPath
{
public DocsDraftsForIdEditorsTeamsPostRequest() { }
public DocsDraftsForIdEditorsTeamsPostRequest(string teamId)
{
TeamId = teamId;
}
private PropertyValue<string> _teamId = new PropertyValue<string>(nameof(DocsDraftsForIdEditorsTeamsPostRequest), nameof(TeamId));
[Required]
[JsonPropertyName("teamId")]
public string TeamId
{
get => _teamId.GetValue();
set => _teamId.SetValue(value);
}
public virtual void SetAccessPath(string path, bool validateHasBeenSet)
{
_teamId.SetAccessPath(path, validateHasBeenSet);
}
}
| 28.745763 | 134 | 0.679245 | [
"Apache-2.0"
] | JetBrains/space-dotnet-sdk | src/JetBrains.Space.Client/Generated/Dtos/DocsDraftsForIdEditorsTeamsPostRequest.generated.cs | 1,696 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.Streams;
using UnitTests.GrainInterfaces;
namespace UnitTests.Grains
{
public class MultipleSubscriptionConsumerGrain : Grain, IMultipleSubscriptionConsumerGrain
{
private readonly Dictionary<StreamSubscriptionHandle<int>, Tuple<Counter,Counter>> consumedMessageCounts;
private ILogger logger;
private int consumerCount = 0;
public MultipleSubscriptionConsumerGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
consumedMessageCounts = new Dictionary<StreamSubscriptionHandle<int>, Tuple<Counter, Counter>>();
}
private class Counter
{
public int Value { get; private set; }
public void Increment()
{
Value++;
}
public void Clear()
{
Value = 0;
}
}
public override Task OnActivateAsync()
{
logger.Info("OnActivateAsync");
return Task.CompletedTask;
}
public async Task<StreamSubscriptionHandle<int>> BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse)
{
logger.Info("BecomeConsumer");
// new counter for this subscription
var count = new Counter();
var error = new Counter();
// get stream
IStreamProvider streamProvider = GetStreamProvider(providerToUse);
var stream = streamProvider.GetStream<int>(streamId, streamNamespace);
int countCapture = consumerCount;
consumerCount++;
// subscribe
StreamSubscriptionHandle<int> handle = await stream.SubscribeAsync(
(e, t) => OnNext(e, t, countCapture, count),
e => OnError(e, countCapture, error));
// track counter
consumedMessageCounts.Add(handle, Tuple.Create(count,error));
// return handle
return handle;
}
public async Task<StreamSubscriptionHandle<int>> Resume(StreamSubscriptionHandle<int> handle)
{
logger.Info("Resume");
if(handle == null)
throw new ArgumentNullException("handle");
// new counter for this subscription
Tuple<Counter,Counter> counters;
if (!consumedMessageCounts.TryGetValue(handle, out counters))
{
counters = Tuple.Create(new Counter(), new Counter());
}
int countCapture = consumerCount;
consumerCount++;
// subscribe
StreamSubscriptionHandle<int> newhandle = await handle.ResumeAsync(
(e, t) => OnNext(e, t, countCapture, counters.Item1),
e => OnError(e, countCapture, counters.Item2));
// track counter
consumedMessageCounts[newhandle] = counters;
// return handle
return newhandle;
}
public async Task StopConsuming(StreamSubscriptionHandle<int> handle)
{
logger.Info("StopConsuming");
// unsubscribe
await handle.UnsubscribeAsync();
// stop tracking event count for stream
consumedMessageCounts.Remove(handle);
}
public Task<IList<StreamSubscriptionHandle<int>>> GetAllSubscriptions(Guid streamId, string streamNamespace, string providerToUse)
{
logger.Info("GetAllSubscriptionHandles");
// get stream
IStreamProvider streamProvider = GetStreamProvider(providerToUse);
var stream = streamProvider.GetStream<int>(streamId, streamNamespace);
// get all active subscription handles for this stream.
return stream.GetAllSubscriptionHandles();
}
public Task<Dictionary<StreamSubscriptionHandle<int>, Tuple<int,int>>> GetNumberConsumed()
{
logger.Info(String.Format("ConsumedMessageCounts = \n{0}",
Utils.EnumerableToString(consumedMessageCounts, kvp => String.Format("Consumer: {0} -> count: {1}", kvp.Key.HandleId.ToString(), kvp.Value.ToString()))));
return Task.FromResult(consumedMessageCounts.ToDictionary(kvp => kvp.Key, kvp => Tuple.Create(kvp.Value.Item1.Value, kvp.Value.Item2.Value)));
}
public Task ClearNumberConsumed()
{
logger.Info("ClearNumberConsumed");
foreach (var counters in consumedMessageCounts.Values)
{
counters.Item1.Clear();
counters.Item2.Clear();
}
return Task.CompletedTask;
}
public Task Deactivate()
{
DeactivateOnIdle();
return Task.CompletedTask;
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
return Task.CompletedTask;
}
private Task OnNext(int e, StreamSequenceToken token, int countCapture, Counter count)
{
logger.Info("Got next event {0} on handle {1}", e, countCapture);
var contextValue = RequestContext.Get(SampleStreaming_ProducerGrain.RequestContextKey) as string;
if (!String.Equals(contextValue, SampleStreaming_ProducerGrain.RequestContextValue))
{
throw new Exception(String.Format("Got the wrong RequestContext value {0}.", contextValue));
}
count.Increment();
return Task.CompletedTask;
}
private Task OnError(Exception e, int countCapture, Counter error)
{
logger.Info("Got exception {0} on handle {1}", e.ToString(), countCapture);
error.Increment();
return Task.CompletedTask;
}
}
}
| 35.109827 | 170 | 0.602239 | [
"MIT"
] | rossbuggins/orleans | test/Grains/TestGrains/MultipleSubscriptionConsumerGrain.cs | 6,074 | 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\Requests\MethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type WorkbookFilterApplyBottomPercentFilterRequest.
/// </summary>
public partial class WorkbookFilterApplyBottomPercentFilterRequest : BaseRequest, IWorkbookFilterApplyBottomPercentFilterRequest
{
/// <summary>
/// Constructs a new WorkbookFilterApplyBottomPercentFilterRequest.
/// </summary>
public WorkbookFilterApplyBottomPercentFilterRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
this.ContentType = "application/json";
this.RequestBody = new WorkbookFilterApplyBottomPercentFilterRequestBody();
}
/// <summary>
/// Gets the request body.
/// </summary>
public WorkbookFilterApplyBottomPercentFilterRequestBody RequestBody { get; private set; }
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task PostAsync(
CancellationToken cancellationToken)
{
this.Method = "POST";
return this.SendAsync(this.RequestBody, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFilterApplyBottomPercentFilterRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFilterApplyBottomPercentFilterRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| 35.83908 | 153 | 0.593329 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/WorkbookFilterApplyBottomPercentFilterRequest.cs | 3,118 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace nyom.infra.Migrations
{
public partial class workflow : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 18.85 | 71 | 0.68435 | [
"MIT"
] | hdrezei/dotnetcore-rabbitmq | nyom/nyom.infra/Migrations/20170820143331_workflow.cs | 379 | C# |
namespace SemVersion
{
using System.Collections.Generic;
/// <summary>Compares two <see cref="SemanticVersion"/> ojects for equality.</summary>
public sealed class VersionComparer : IEqualityComparer<SemanticVersion>, IComparer<SemanticVersion>
{
/// <inheritdoc/>
public bool Equals(SemanticVersion left, SemanticVersion right)
{
return this.Compare(left, right) == 0;
}
/// <inheritdoc/>
public int Compare(SemanticVersion left, SemanticVersion right)
{
if (ReferenceEquals(left, null))
{
return ReferenceEquals(right, null) ? 0 : -1;
}
if (ReferenceEquals(right, null))
{
return 1;
}
int majorComp = left.Major.CompareToBoxed(right.Major);
if (majorComp != 0)
{
return majorComp;
}
int minorComp = left.Minor.CompareToBoxed(right.Minor);
if (minorComp != 0)
{
return minorComp;
}
int patchComp = left.Patch.CompareToBoxed(right.Patch);
if (patchComp != 0)
{
return patchComp;
}
return left.Prerelease.CompareComponent(right.Prerelease);
}
/// <inheritdoc/>
public int GetHashCode(SemanticVersion obj)
{
return obj.GetHashCode();
}
}
}
| 27.181818 | 104 | 0.523077 | [
"MIT"
] | ilohmar/SemanticVersion | src/SemanticVersion/VersionComparer.cs | 1,497 | C# |
// Copyright (c) 2021 Yoakke.
// Licensed under the Apache License, Version 2.0.
// Source repository: https://github.com/LanguageDev/Yoakke
using System;
using System.Collections.Generic;
using System.Collections.Generic.Polyfill;
using System.IO;
using System.Linq;
using Yoakke.Text;
namespace Yoakke.Reporting.Present
{
/// <summary>
/// A diagnostic presenter that just writes to a text buffer or console with color.
/// </summary>
public class TextDiagnosticsPresenter : IDiagnosticsPresenter
{
private abstract class LinePrimitive
{
}
private class SourceLine : LinePrimitive
{
public ISourceFile? Source { get; set; }
public int Line { get; set; }
}
private class DotLine : LinePrimitive
{
}
private class AnnotationLine : LinePrimitive
{
public int AnnotatedLine { get; set; }
public IEnumerable<SourceDiagnosticInfo>? Annotations { get; set; }
}
/// <summary>
/// A default text presenter that writes to the console error.
/// </summary>
public static readonly TextDiagnosticsPresenter Default = new(Console.Error);
/// <inheritdoc/>
public DiagnosticsStyle Style { get; set; } = DiagnosticsStyle.Default;
/// <inheritdoc/>
public ISyntaxHighlighter SyntaxHighlighter { get; set; } = NullSyntaxHighlighter.Instance;
/// <summary>
/// The <see cref="TextWriter"/> this presenter writes to.
/// </summary>
public TextWriter Writer { get; }
private readonly ColoredBuffer buffer;
/// <summary>
/// Initializes a new instance of the <see cref="TextDiagnosticsPresenter"/> class.
/// </summary>
/// <param name="writer">The writer to write to.</param>
public TextDiagnosticsPresenter(TextWriter writer)
{
this.Writer = writer;
this.buffer = new ColoredBuffer();
}
/// <inheritdoc/>
public void Present(Diagnostics diagnostic)
{
// Clear the buffer
this.buffer.Clear();
// Write the head
// error[CS123]: Some message
this.WriteDiagnosticHead(diagnostic);
// Collect out source information grouped by the files and ordered by their positions
var sourceInfo = diagnostic.Information
.OfType<SourceDiagnosticInfo>()
.OrderBy(si => si.Location.Range.Start)
.GroupBy(si => si.Location.File);
// Print the groups
foreach (var info in sourceInfo) this.WriteSourceGroup(info);
// Finally print the footnores
var footnotes = diagnostic.Information.OfType<FootnoteDiagnosticInfo>();
foreach (var footnote in footnotes) this.WriteFootnote(footnote);
// Dump results to the buffer
this.buffer.OutputTo(this.Writer);
}
// Format is
// error[CS123]: Some message
private void WriteDiagnosticHead(Diagnostics diagnostic)
{
if (diagnostic.Severity != null)
{
this.buffer.ForegroundColor = this.Style.GetSeverityColor(diagnostic.Severity.Value);
this.buffer.Write(diagnostic.Severity.Value.Name);
}
if (diagnostic.Code != null)
{
if (diagnostic.Severity != null) this.buffer.Write('[');
this.buffer.Write(diagnostic.Code);
if (diagnostic.Severity != null) this.buffer.Write(']');
if (diagnostic.Message != null) this.buffer.Write(": ");
}
if (diagnostic.Message != null)
{
this.buffer.ForegroundColor = this.Style.DefaultColor;
this.buffer.Write(diagnostic.Message);
}
if (diagnostic.Severity != null || diagnostic.Code != null || diagnostic.Message != null) this.buffer.WriteLine();
}
private void WriteSourceGroup(IEnumerable<SourceDiagnosticInfo> infos)
{
// Get the source file for this group
var sourceFile = infos.First().Location.File;
// Get what we assume to be the primary information
// It's the first info with the biggest severity, or the first info if there are no severities
var primaryInfo = infos
.Where(info => info.Severity != null)
.OrderByDescending(info => info.Severity)
.FirstOrDefault()
?? infos.First();
// Generate all line primitives
var linePrimitives = this.CollectLinePrimitives(infos).ToList();
// Find the largest line index printed
var maxLineIndex = linePrimitives.OfType<SourceLine>().Select(l => l.Line).Max();
// Create a padding to fit all line numbers from the largest of the group
var lineNumberPadding = new string(' ', (maxLineIndex + 1).ToString().Length);
// Print the ┌─ <file name>
this.buffer.ForegroundColor = this.Style.DefaultColor;
this.buffer.Write($"{lineNumberPadding} ┌─ {sourceFile.Path}");
// If there is a primary info, write the line and column
if (primaryInfo != null) this.buffer.Write($":{primaryInfo.Location.Range.Start.Line + 1}:{primaryInfo.Location.Range.Start.Column + 1}");
this.buffer.WriteLine();
// Write a single separator line
this.buffer.WriteLine($"{lineNumberPadding} │");
// Now print all the line primitives
foreach (var line in linePrimitives)
{
switch (line)
{
case SourceLine sourceLine:
this.buffer.ForegroundColor = this.Style.LineNumberColor;
this.buffer.Write((sourceLine.Line + 1).ToString().PadLeft(lineNumberPadding.Length, this.Style.LineNumberPadding));
this.buffer.ForegroundColor = this.Style.DefaultColor;
this.buffer.Write(" │ ");
this.WriteSourceLine(sourceLine);
this.buffer.WriteLine();
break;
case AnnotationLine annotation:
this.WriteAnnotationLine(annotation, $"{lineNumberPadding} │ ");
break;
case DotLine dotLine:
this.buffer.ForegroundColor = this.Style.DefaultColor;
this.buffer.WriteLine($"{lineNumberPadding} │ ...");
break;
}
}
// Write a single separator line
this.buffer.ForegroundColor = this.Style.DefaultColor;
this.buffer.WriteLine($"{lineNumberPadding} │");
}
private void WriteFootnote(FootnoteDiagnosticInfo info)
{
this.buffer.ForegroundColor = this.Style.DefaultColor;
if (info.Message != null) this.buffer.WriteLine(info.Message);
}
private void WriteSourceLine(SourceLine line)
{
var xOffset = this.buffer.CursorX;
// First print the source line with the default color
this.buffer.ForegroundColor = this.SyntaxHighlighter.Style.DefaultColor;
var lineText = line.Source!.GetLine(line.Line);
var lineCur = 0;
foreach (var ch in lineText)
{
if (ch == '\r' || ch == '\n') break;
if (this.AdvanceCursor(ref lineCur, ch)) this.buffer.Write(ch);
this.buffer.CursorX = xOffset + lineCur;
}
// Get the syntax highlight info
var coloredTokens = this.SyntaxHighlighter.GetHighlightingForLine(line.Source, line.Line)
.OrderBy(info => info.Start)
.ToList();
if (coloredTokens.Count > 0)
{
// There is info to highlight
lineCur = 0;
var charIndex = 0;
foreach (var token in coloredTokens)
{
// Walk there until the next token
for (; charIndex < token.Start; this.AdvanceCursor(ref lineCur, lineText[charIndex++]))
{
}
// Go through the token
var tokenStart = lineCur;
for (; charIndex < token.Start + token.Length; this.AdvanceCursor(ref lineCur, lineText[charIndex++]))
{
}
var tokenEnd = lineCur;
// Recolor it
this.buffer.ForegroundColor = this.SyntaxHighlighter.Style.GetTokenColor(token.Kind);
this.buffer.Recolor(xOffset + tokenStart, this.buffer.CursorY, tokenEnd - tokenStart, 1);
}
}
}
private void WriteAnnotationLine(AnnotationLine line, string prefix)
{
var sourceFile = line.Annotations!.First().Location.File;
var lineText = sourceFile.GetLine(line.AnnotatedLine).TrimEnd();
// Order annotations by starting position
var annotationsOrdered = line.Annotations!.OrderBy(si => si.Location.Range.Start).ToList();
// Now we draw the arrows to their correct places under the annotated line
// Also collect physical column positions to extend the arrows
var arrowHeadColumns = new List<(int Column, SourceDiagnosticInfo Info)>();
this.buffer.ForegroundColor = this.Style.DefaultColor;
this.buffer.Write(prefix);
var lineCur = 0;
var charIdx = 0;
foreach (var annot in annotationsOrdered)
{
// From the last character index until the start of this annotation we need to fill with spaces
for (; charIdx < annot.Location.Range.Start.Column; ++charIdx)
{
if (charIdx < lineText.Length)
{
// Still in range of the line
this.AdvanceCursor(ref lineCur, lineText[charIdx]);
}
else
{
// After the line
lineCur += 1;
}
}
this.buffer.CursorX = prefix.Length + lineCur;
// Now we are inside the span
var arrowHead = annot.Severity != null ? '^' : '-';
var startColumn = this.buffer.CursorX;
arrowHeadColumns.Add((startColumn, annot));
if (annot.Severity != null) this.buffer.ForegroundColor = this.Style.GetSeverityColor(annot.Severity.Value);
for (; charIdx < annot.Location.Range.End.Column; ++charIdx)
{
if (charIdx < lineText.Length)
{
// Still in range of the line
var oldOffset = lineCur;
this.AdvanceCursor(ref lineCur, lineText[charIdx]);
// Fill with arrow head
this.buffer.Fill(prefix.Length + oldOffset, this.buffer.CursorY, lineCur - oldOffset, 1, arrowHead);
this.buffer.CursorX = prefix.Length + lineCur;
}
else
{
// After the line
this.buffer.Write(arrowHead);
}
}
var endColumn = this.buffer.CursorX;
// Recolor the source line too
if (annot.Severity != null) this.buffer.Recolor(startColumn, this.buffer.CursorY - 1, endColumn - startColumn, 1);
}
// Now we are done with arrows in the line, it's time to do the arrow bodies downwards
// The first one will have N, the last 0 length bodies, decreasing by one
// The last one just has the message inline
{
var lastAnnot = annotationsOrdered.Last();
if (lastAnnot.Message != null) this.buffer.Write($" {lastAnnot.Message}");
this.buffer.WriteLine();
}
// From now on all previous ones will be one longer than the ones later
var arrowBaseLine = this.buffer.CursorY;
var arrowBodyLength = 0;
// We only consider annotations with messages
foreach (var (col, annot) in arrowHeadColumns.SkipLast(1).Reverse().Where(a => a.Info.Message != null))
{
if (annot.Severity != null) this.buffer.ForegroundColor = this.Style.GetSeverityColor(annot.Severity.Value);
// Draw the arrow
this.buffer.Fill(col, arrowBaseLine, 1, arrowBodyLength, '│');
this.buffer.Plot(col, arrowBaseLine + arrowBodyLength, '└');
arrowBodyLength += 1;
// Append the message
this.buffer.Write($" {annot.Message}");
if (annot.Severity != null) this.buffer.ForegroundColor = this.Style.DefaultColor;
}
// Fill the in between lines with the prefix
for (var i = 0; i < arrowBodyLength; ++i)
{
this.buffer.WriteAt(0, arrowBaseLine + i, prefix);
}
// Reset cursor position
this.buffer.CursorX = 0;
this.buffer.CursorY = arrowBaseLine + arrowBodyLength;
}
private IEnumerable<LinePrimitive> CollectLinePrimitives(IEnumerable<SourceDiagnosticInfo> infos)
{
// We need to group the spanned informations per line
var groupedInfos = infos.GroupBy(si => si.Location.Range.Start.Line).ToList();
var sourceFile = infos.First().Location.File;
// Now we collect each line primitive
int? lastLineIndex = null;
for (var j = 0; j < groupedInfos.Count; ++j)
{
var infoGroup = groupedInfos[j];
// First we determine the range we need to print for this info
var currentLineIndex = infoGroup.Key;
var minLineIndex = Math.Max(lastLineIndex ?? 0, currentLineIndex - this.Style.SurroundingLines);
var maxLineIndex = Math.Min(sourceFile.AvailableLines, currentLineIndex + this.Style.SurroundingLines + 1);
// Trim empty source lines at edges
if (this.Style.TrimEmptySourceLinesAtEdges)
{
for (var i = minLineIndex; i < currentLineIndex && string.IsNullOrWhiteSpace(sourceFile.GetLine(i)); ++i)
{
++minLineIndex;
}
for (var i = maxLineIndex - 1; i > currentLineIndex && string.IsNullOrWhiteSpace(sourceFile.GetLine(i)); --i)
{
--maxLineIndex;
}
}
if (j < groupedInfos.Count - 1)
{
// There's a chance we step over to the next annotation
var nextGroupLineIndex = groupedInfos[j + 1].Key;
maxLineIndex = Math.Min(maxLineIndex, nextGroupLineIndex);
}
// Determine if we need dotting or a line in between
if (lastLineIndex != null)
{
var difference = minLineIndex - lastLineIndex.Value;
if (difference <= this.Style.ConnectUpLines)
{
// Difference is negligible, connect them up, no reason to dot it out
for (var i = 0; i < difference; ++i)
{
yield return new SourceLine { Source = sourceFile, Line = lastLineIndex.Value + i };
}
}
else
{
// Bigger difference, dot out
yield return new DotLine { };
}
}
lastLineIndex = maxLineIndex;
// Now we need to print all the relevant lines
for (var i = minLineIndex; i < maxLineIndex; ++i)
{
yield return new SourceLine { Source = sourceFile, Line = i };
// If this was an annotated line, yield the annotation
if (i == infoGroup.Key) yield return new AnnotationLine { AnnotatedLine = i, Annotations = infoGroup };
}
}
}
private bool AdvanceCursor(ref int pos, char ch)
{
if (ch == '\t')
{
pos += this.Style.TabSize - (pos % this.Style.TabSize);
return false;
}
else if (!char.IsControl(ch))
{
pos += 1;
return true;
}
return false;
}
}
}
| 43.793893 | 150 | 0.535181 | [
"Apache-2.0"
] | kant2002/Yoakke | Sources/Core/Yoakke.Reporting/Present/TextDiagnosticsPresenter.cs | 17,233 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Windows.Forms;
using Microsoft.Win32;
namespace WinDynamicDesktop
{
class FormWrapper : ApplicationContext
{
private ProgressDialog downloadDialog;
private InputDialog locationDialog;
private NotifyIcon notifyIcon;
public StartupManager _startupManager;
public WallpaperChangeScheduler _wcsService;
public FormWrapper()
{
Application.ApplicationExit += new EventHandler(OnApplicationExit);
SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(OnPowerModeChanged);
JsonConfig.LoadConfig();
_wcsService = new WallpaperChangeScheduler();
InitializeComponent();
_startupManager = UwpDesktop.GetStartupManager(notifyIcon.ContextMenu.MenuItems[5]);
if (!Directory.Exists("images"))
{
DownloadImages();
}
else if (JsonConfig.firstRun)
{
UpdateLocation();
}
else
{
_wcsService.StartScheduler();
}
}
private void InitializeComponent()
{
notifyIcon = new NotifyIcon
{
Visible = true,
Icon = Properties.Resources.AppIcon,
Text = "WinDynamicDesktop",
BalloonTipTitle = "WinDynamicDesktop"
};
notifyIcon.ContextMenu = new ContextMenu(new MenuItem[]
{
new MenuItem("WinDynamicDesktop"),
new MenuItem("-"),
new MenuItem("&Update Location...", OnLocationItemClick),
new MenuItem("&Refresh Wallpaper", OnRefreshItemClick),
new MenuItem("-"),
new MenuItem("&Start on Boot", OnStartupItemClick),
new MenuItem("-"),
new MenuItem("E&xit", OnExitItemClick)
});
notifyIcon.ContextMenu.MenuItems[0].Enabled = false;
}
private void OnLocationItemClick(object sender, EventArgs e)
{
UpdateLocation();
}
private void OnRefreshItemClick(object sender, EventArgs e)
{
_wcsService.StartScheduler(true);
}
private void OnStartupItemClick(object sender, EventArgs e)
{
_startupManager.ToggleStartOnBoot();
}
private void OnExitItemClick(object sender, EventArgs e)
{
notifyIcon.Visible = false;
Application.Exit();
}
public void DownloadImages()
{
string imagesZipUri = JsonConfig.imageSettings.imagesZipUri;
if (imagesZipUri == null)
{
MessageBox.Show("Images folder not found. The program will quit now.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(1);
return;
}
else
{
DialogResult result = MessageBox.Show("WinDynamicDesktop needs to download images for " +
"the " + JsonConfig.imageSettings.themeName + " theme from " + imagesZipUri +
Environment.NewLine + Environment.NewLine + "Do you want to continue?", "Setup",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result != DialogResult.Yes)
{
Environment.Exit(0);
}
}
downloadDialog = new ProgressDialog();
downloadDialog.FormClosed += OnDownloadDialogClosed;
downloadDialog.Show();
notifyIcon.ContextMenu.MenuItems[2].Enabled = false;
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += downloadDialog.OnDownloadProgressChanged;
client.DownloadFileCompleted += downloadDialog.OnDownloadFileCompleted;
client.DownloadFileAsync(new Uri(imagesZipUri), "images.zip");
}
}
private void OnDownloadDialogClosed(object sender, EventArgs e)
{
downloadDialog = null;
if (!Directory.Exists("images"))
{
DialogResult result = MessageBox.Show("Failed to download images. Click Retry to " +
"try again or Cancel to exit the program.", "Error", MessageBoxButtons.RetryCancel,
MessageBoxIcon.Error);
if (result == DialogResult.Retry)
{
DownloadImages();
}
else
{
Environment.Exit(0);
}
}
else if (JsonConfig.settings.location == null)
{
notifyIcon.ContextMenu.MenuItems[2].Enabled = true;
UpdateLocation();
}
}
public void UpdateLocation()
{
if (locationDialog == null)
{
locationDialog = new InputDialog { _wcsService = _wcsService };
locationDialog.FormClosed += OnLocationDialogClosed;
locationDialog.Show();
}
else
{
locationDialog.Activate();
}
}
private void OnLocationDialogClosed(object sender, EventArgs e)
{
locationDialog = null;
if (JsonConfig.firstRun)
{
notifyIcon.BalloonTipText = "The app is still running in the background. " +
"You can access it at any time by right-clicking on this icon.";
notifyIcon.ShowBalloonTip(10000);
JsonConfig.firstRun = false; // Don't show this message again
}
}
private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
if (e.Mode == PowerModes.Suspend)
{
if (_wcsService.wallpaperTimer != null)
{
_wcsService.wallpaperTimer.Stop();
}
_wcsService.enableTransitions = false;
}
else if (e.Mode == PowerModes.Resume)
{
if (JsonConfig.settings.location != null)
{
_wcsService.StartScheduler();
}
_wcsService.enableTransitions = true;
}
}
private void OnApplicationExit(object sender, EventArgs e)
{
if (downloadDialog != null)
{
downloadDialog.Close();
}
if (locationDialog != null)
{
locationDialog.Close();
}
notifyIcon.Visible = false;
}
}
} | 32.743243 | 106 | 0.511762 | [
"MIT"
] | lookitsnicholas/WinDynamicDesktop | src/FormWrapper.cs | 7,271 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EmitMapper.Utils;
namespace EmitMapper.MappingConfiguration
{
class TypeDictionary<T> where T: class
{
class ListElement
{
public Type[] types;
public T value;
public ListElement(Type[] types, T value)
{
this.types = types;
this.value = value;
}
public override int GetHashCode()
{
return types.Sum(t => t.GetHashCode());
}
public override bool Equals(object obj)
{
var rhs = (ListElement)obj;
for (int i = 0; i < types.Length; ++i)
{
if (types[i] != rhs.types[i])
{
return false;
}
}
return true;
}
}
private List<ListElement> elements = new List<ListElement>();
public override string ToString()
{
return elements.Select(e => e.types.ToCSV("|") + (e.value == null ? "|" : ("|" + e.value) )).ToCSV("||");
}
public bool IsTypesInList(Type[] types)
{
return FindTypes(types) != null;
}
public T GetValue(Type[] types)
{
var elem = FindTypes(types);
return elem == null ? null : elem.value;
}
public void Add(Type[] types, T value)
{
var newElem = new ListElement(types, value);
if (elements.Contains(newElem))
{
elements.Remove(newElem);
}
elements.Add(new ListElement(types, value));
}
private ListElement FindTypes(Type[] types)
{
foreach (var element in elements)
{
bool isAssignable = true;
for (int i = 0; i < element.types.Length; ++i)
{
if (!IsGeneralType(element.types[i], types[i]))
{
isAssignable = false;
break;
}
}
if (isAssignable)
{
return element;
}
}
return null;
}
private static bool IsGeneralType(Type generalType, Type type)
{
if (generalType == type)
{
return true;
}
if (generalType.IsGenericTypeDefinition)
{
if (generalType.IsInterface)
{
return
(type.IsInterface ? new[]{type} : new Type[0]).Concat(type.GetInterfaces())
.Any(
i =>
i.IsGenericType &&
i.GetGenericTypeDefinition() == generalType
);
}
else
{
return type.IsGenericType && (type.GetGenericTypeDefinition() == generalType || type.GetGenericTypeDefinition().IsSubclassOf(generalType));
}
}
return type.IsSubclassOf(generalType);
}
}
}
| 27.737288 | 159 | 0.439047 | [
"MIT"
] | PuGuihong/Dos.Common | EmitMapper/MappingConfiguration/TypeList.cs | 3,275 | C# |
/* Copyright 2018 Ellisnet - Jeremy Ellis (jeremy@ellisnet.com)
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 CodeBrix.Models
{
public class PhotoResolution
{
public int Width { get; set; } = 0;
public int Height { get; set; } = 0;
}
}
| 32.708333 | 75 | 0.709554 | [
"Apache-2.0"
] | ellisnet/CodeBrix | Source/Core/CodeBrix.Core/Models/PhotoResolution.cs | 787 | C# |
// Enum generated by TankLibHelper.EnumBuilder
// ReSharper disable All
namespace TankLib.STU.Types.Enums {
[STUEnumAttribute(0xF8834A55)]
public enum Enum_F8834A55 : uint {
[STUFieldAttribute(0xDA4C7382)]
xDA4C7382 = 0x0,
[STUFieldAttribute(0x0D35BE26)]
x0D35BE26 = 0x1,
[STUFieldAttribute(0x664D6972)]
x664D6972 = 0x2,
[STUFieldAttribute(0x97C9660B)]
x97C9660B = 0x3,
[STUFieldAttribute(0xABE5565D)]
xABE5565D = 0x4,
[STUFieldAttribute(0x74C75FDF)]
x74C75FDF = 0x5,
[STUFieldAttribute(0xD8F18C20)]
xD8F18C20 = 0x6,
[STUFieldAttribute(0x91AC7EE1)]
x91AC7EE1 = 0x7,
[STUFieldAttribute(0x77EDAD86)]
x77EDAD86 = 0x8,
[STUFieldAttribute(0x0505AFA1)]
x0505AFA1 = 0x9,
[STUFieldAttribute(0x38496D33)]
x38496D33 = 0xA,
[STUFieldAttribute(0xB978C9D8)]
xB978C9D8 = 0xB,
[STUFieldAttribute(0x1E148377)]
x1E148377 = 0xC,
}
}
| 29.6 | 46 | 0.624517 | [
"MIT"
] | Mike111177/OWLib | TankLib/STU/Types/Enums/Enum_F8834A55.cs | 1,036 | 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;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Mvc.Core;
using Microsoft.AspNet.Mvc.Infrastructure;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Routing.Internal;
using Microsoft.AspNet.Routing.Template;
using Microsoft.AspNet.Routing.Tree;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
namespace Microsoft.AspNet.Mvc.Routing
{
public class AttributeRoute : IRouter
{
private readonly IRouter _target;
private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;
private readonly IInlineConstraintResolver _constraintResolver;
private readonly ObjectPool<UriBuildingContext> _contextPool;
private readonly UrlEncoder _urlEncoder;
private readonly ILoggerFactory _loggerFactory;
private TreeRouter _router;
public AttributeRoute(
IRouter target,
IActionDescriptorCollectionProvider actionDescriptorCollectionProvider,
IInlineConstraintResolver constraintResolver,
ObjectPool<UriBuildingContext> contextPool,
UrlEncoder urlEncoder,
ILoggerFactory loggerFactory)
{
if (target == null)
{
throw new ArgumentNullException(nameof(target));
}
if (actionDescriptorCollectionProvider == null)
{
throw new ArgumentNullException(nameof(actionDescriptorCollectionProvider));
}
if (constraintResolver == null)
{
throw new ArgumentNullException(nameof(constraintResolver));
}
if (contextPool == null)
{
throw new ArgumentNullException(nameof(contextPool));
}
if (urlEncoder == null)
{
throw new ArgumentNullException(nameof(urlEncoder));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
_target = target;
_actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
_constraintResolver = constraintResolver;
_contextPool = contextPool;
_urlEncoder = urlEncoder;
_loggerFactory = loggerFactory;
}
/// <inheritdoc />
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
var router = GetTreeRouter();
return router.GetVirtualPath(context);
}
/// <inheritdoc />
public Task RouteAsync(RouteContext context)
{
var router = GetTreeRouter();
return router.RouteAsync(context);
}
private TreeRouter GetTreeRouter()
{
var actions = _actionDescriptorCollectionProvider.ActionDescriptors;
// This is a safe-race. We'll never set router back to null after initializing
// it on startup.
if (_router == null || _router.Version != actions.Version)
{
_router = BuildRoute(actions);
}
return _router;
}
private TreeRouter BuildRoute(ActionDescriptorCollection actions)
{
var routeBuilder = new TreeRouteBuilder(_target, _loggerFactory);
var routeInfos = GetRouteInfos(_constraintResolver, actions.Items);
// We're creating one AttributeRouteGenerationEntry per action. This allows us to match the intended
// action by expected route values, and then use the TemplateBinder to generate the link.
foreach (var routeInfo in routeInfos)
{
routeBuilder.Add(new TreeRouteLinkGenerationEntry()
{
Binder = new TemplateBinder(_urlEncoder, _contextPool, routeInfo.ParsedTemplate, routeInfo.Defaults),
Defaults = routeInfo.Defaults,
Constraints = routeInfo.Constraints,
Order = routeInfo.Order,
GenerationPrecedence = routeInfo.GenerationPrecedence,
RequiredLinkValues = routeInfo.ActionDescriptor.RouteValueDefaults,
RouteGroup = routeInfo.RouteGroup,
Template = routeInfo.ParsedTemplate,
Name = routeInfo.Name,
});
}
// We're creating one AttributeRouteMatchingEntry per group, so we need to identify the distinct set of
// groups. It's guaranteed that all members of the group have the same template and precedence,
// so we only need to hang on to a single instance of the RouteInfo for each group.
var distinctRouteInfosByGroup = GroupRouteInfosByGroupId(routeInfos);
foreach (var routeInfo in distinctRouteInfosByGroup)
{
routeBuilder.Add(new TreeRouteMatchingEntry()
{
Order = routeInfo.Order,
Precedence = routeInfo.MatchPrecedence,
Target = _target,
RouteName = routeInfo.Name,
RouteTemplate = TemplateParser.Parse(routeInfo.RouteTemplate),
TemplateMatcher = new TemplateMatcher(
routeInfo.ParsedTemplate,
new RouteValueDictionary(StringComparer.OrdinalIgnoreCase)
{
{ TreeRouter.RouteGroupKey, routeInfo.RouteGroup }
}),
Constraints = routeInfo.Constraints
});
}
return routeBuilder.Build(actions.Version);
}
private static IEnumerable<RouteInfo> GroupRouteInfosByGroupId(List<RouteInfo> routeInfos)
{
var routeInfosByGroupId = new Dictionary<string, RouteInfo>(StringComparer.OrdinalIgnoreCase);
foreach (var routeInfo in routeInfos)
{
if (!routeInfosByGroupId.ContainsKey(routeInfo.RouteGroup))
{
routeInfosByGroupId.Add(routeInfo.RouteGroup, routeInfo);
}
}
return routeInfosByGroupId.Values;
}
private static List<RouteInfo> GetRouteInfos(
IInlineConstraintResolver constraintResolver,
IReadOnlyList<ActionDescriptor> actions)
{
var routeInfos = new List<RouteInfo>();
var errors = new List<RouteInfo>();
// This keeps a cache of 'Template' objects. It's a fairly common case that multiple actions
// will use the same route template string; thus, the `Template` object can be shared.
//
// For a relatively simple route template, the `Template` object will hold about 500 bytes
// of memory, so sharing is worthwhile.
var templateCache = new Dictionary<string, RouteTemplate>(StringComparer.OrdinalIgnoreCase);
var attributeRoutedActions = actions.Where(a => a.AttributeRouteInfo != null &&
a.AttributeRouteInfo.Template != null);
foreach (var action in attributeRoutedActions)
{
var routeInfo = GetRouteInfo(constraintResolver, templateCache, action);
if (routeInfo.ErrorMessage == null)
{
routeInfos.Add(routeInfo);
}
else
{
errors.Add(routeInfo);
}
}
if (errors.Count > 0)
{
var allErrors = string.Join(
Environment.NewLine + Environment.NewLine,
errors.Select(
e => Resources.FormatAttributeRoute_IndividualErrorMessage(
e.ActionDescriptor.DisplayName,
Environment.NewLine,
e.ErrorMessage)));
var message = Resources.FormatAttributeRoute_AggregateErrorMessage(Environment.NewLine, allErrors);
throw new InvalidOperationException(message);
}
return routeInfos;
}
private static RouteInfo GetRouteInfo(
IInlineConstraintResolver constraintResolver,
Dictionary<string, RouteTemplate> templateCache,
ActionDescriptor action)
{
var constraint = action.RouteConstraints
.Where(c => c.RouteKey == TreeRouter.RouteGroupKey)
.FirstOrDefault();
if (constraint == null ||
constraint.KeyHandling != RouteKeyHandling.RequireKey ||
constraint.RouteValue == null)
{
// This can happen if an ActionDescriptor has a route template, but doesn't have one of our
// special route group constraints. This is a good indication that the user is using a 3rd party
// routing system, or has customized their ADs in a way that we can no longer understand them.
//
// We just treat this case as an 'opt-out' of our attribute routing system.
return null;
}
var routeInfo = new RouteInfo()
{
ActionDescriptor = action,
RouteGroup = constraint.RouteValue,
RouteTemplate = action.AttributeRouteInfo.Template,
};
try
{
RouteTemplate parsedTemplate;
if (!templateCache.TryGetValue(action.AttributeRouteInfo.Template, out parsedTemplate))
{
// Parsing with throw if the template is invalid.
parsedTemplate = TemplateParser.Parse(action.AttributeRouteInfo.Template);
templateCache.Add(action.AttributeRouteInfo.Template, parsedTemplate);
}
routeInfo.ParsedTemplate = parsedTemplate;
}
catch (Exception ex)
{
routeInfo.ErrorMessage = ex.Message;
return routeInfo;
}
foreach (var kvp in action.RouteValueDefaults)
{
foreach (var parameter in routeInfo.ParsedTemplate.Parameters)
{
if (string.Equals(kvp.Key, parameter.Name, StringComparison.OrdinalIgnoreCase))
{
routeInfo.ErrorMessage = Resources.FormatAttributeRoute_CannotContainParameter(
routeInfo.RouteTemplate,
kvp.Key,
kvp.Value);
return routeInfo;
}
}
}
routeInfo.Order = action.AttributeRouteInfo.Order;
routeInfo.MatchPrecedence = RoutePrecedence.ComputeMatched(routeInfo.ParsedTemplate);
routeInfo.GenerationPrecedence = RoutePrecedence.ComputeGenerated(routeInfo.ParsedTemplate);
routeInfo.Name = action.AttributeRouteInfo.Name;
var constraintBuilder = new RouteConstraintBuilder(constraintResolver, routeInfo.RouteTemplate);
foreach (var parameter in routeInfo.ParsedTemplate.Parameters)
{
if (parameter.InlineConstraints != null)
{
if (parameter.IsOptional)
{
constraintBuilder.SetOptional(parameter.Name);
}
foreach (var inlineConstraint in parameter.InlineConstraints)
{
constraintBuilder.AddResolvedConstraint(parameter.Name, inlineConstraint.Constraint);
}
}
}
routeInfo.Constraints = constraintBuilder.Build();
routeInfo.Defaults = new RouteValueDictionary();
foreach (var parameter in routeInfo.ParsedTemplate.Parameters)
{
if (parameter.DefaultValue != null)
{
routeInfo.Defaults.Add(parameter.Name, parameter.DefaultValue);
}
}
return routeInfo;
}
private class RouteInfo
{
public ActionDescriptor ActionDescriptor { get; set; }
public IDictionary<string, IRouteConstraint> Constraints { get; set; }
public RouteValueDictionary Defaults { get; set; }
public string ErrorMessage { get; set; }
public RouteTemplate ParsedTemplate { get; set; }
public int Order { get; set; }
public decimal MatchPrecedence { get; set; }
public decimal GenerationPrecedence { get; set; }
public string RouteGroup { get; set; }
public string RouteTemplate { get; set; }
public string Name { get; set; }
}
}
}
| 39.093567 | 121 | 0.58003 | [
"Apache-2.0"
] | corefan/Mvc | src/Microsoft.AspNet.Mvc.Core/Routing/AttributeRoute.cs | 13,370 | C# |
# CS_ARCH_MIPS, CS_MODE_MIPS32+CS_MODE_BIG_ENDIAN, None
0x78,0x1c,0x9f,0x1b = fadd.w $w28, $w19, $w28
0x78,0x3d,0x13,0x5b = fadd.d $w13, $w2, $w29
0x78,0x19,0x5b,0x9a = fcaf.w $w14, $w11, $w25
0x78,0x33,0x08,0x5a = fcaf.d $w1, $w1, $w19
0x78,0x90,0xb8,0x5a = fceq.w $w1, $w23, $w16
0x78,0xb0,0x40,0x1a = fceq.d $w0, $w8, $w16
0x79,0x98,0x4c,0x1a = fcle.w $w16, $w9, $w24
0x79,0xa1,0x76,0xda = fcle.d $w27, $w14, $w1
0x79,0x08,0x47,0x1a = fclt.w $w28, $w8, $w8
0x79,0x2b,0xcf,0x9a = fclt.d $w30, $w25, $w11
0x78,0xd7,0x90,0x9c = fcne.w $w2, $w18, $w23
0x78,0xef,0xa3,0x9c = fcne.d $w14, $w20, $w15
0x78,0x59,0x92,0x9c = fcor.w $w10, $w18, $w25
0x78,0x6b,0xcc,0x5c = fcor.d $w17, $w25, $w11
0x78,0xd5,0x13,0x9a = fcueq.w $w14, $w2, $w21
0x78,0xe7,0x1f,0x5a = fcueq.d $w29, $w3, $w7
0x79,0xc3,0x2c,0x5a = fcule.w $w17, $w5, $w3
0x79,0xfe,0x0f,0xda = fcule.d $w31, $w1, $w30
0x79,0x49,0xc9,0x9a = fcult.w $w6, $w25, $w9
0x79,0x71,0x46,0xda = fcult.d $w27, $w8, $w17
0x78,0x48,0xa1,0x1a = fcun.w $w4, $w20, $w8
0x78,0x63,0x5f,0x5a = fcun.d $w29, $w11, $w3
0x78,0x93,0x93,0x5c = fcune.w $w13, $w18, $w19
0x78,0xb5,0xd4,0x1c = fcune.d $w16, $w26, $w21
0x78,0xc2,0xc3,0x5b = fdiv.w $w13, $w24, $w2
0x78,0xf9,0x24,0xdb = fdiv.d $w19, $w4, $w25
0x7a,0x10,0x02,0x1b = fexdo.h $w8, $w0, $w16
0x7a,0x3b,0x68,0x1b = fexdo.w $w0, $w13, $w27
0x79,0xc3,0x04,0x5b = fexp2.w $w17, $w0, $w3
0x79,0xea,0x05,0x9b = fexp2.d $w22, $w0, $w10
0x79,0x17,0x37,0x5b = fmadd.w $w29, $w6, $w23
0x79,0x35,0xe2,0xdb = fmadd.d $w11, $w28, $w21
0x7b,0x8d,0xb8,0x1b = fmax.w $w0, $w23, $w13
0x7b,0xa8,0x96,0x9b = fmax.d $w26, $w18, $w8
0x7b,0xca,0x82,0x9b = fmax_a.w $w10, $w16, $w10
0x7b,0xf6,0x4f,0x9b = fmax_a.d $w30, $w9, $w22
0x7b,0x1e,0x0e,0x1b = fmin.w $w24, $w1, $w30
0x7b,0x2a,0xde,0xdb = fmin.d $w27, $w27, $w10
0x7b,0x54,0xea,0x9b = fmin_a.w $w10, $w29, $w20
0x7b,0x78,0xf3,0x5b = fmin_a.d $w13, $w30, $w24
0x79,0x40,0xcc,0x5b = fmsub.w $w17, $w25, $w0
0x79,0x70,0x92,0x1b = fmsub.d $w8, $w18, $w16
0x78,0x8f,0x78,0xdb = fmul.w $w3, $w15, $w15
0x78,0xaa,0xf2,0x5b = fmul.d $w9, $w30, $w10
0x7a,0x0a,0x2e,0x5a = fsaf.w $w25, $w5, $w10
0x7a,0x3d,0x1e,0x5a = fsaf.d $w25, $w3, $w29
0x7a,0x8d,0x8a,0xda = fseq.w $w11, $w17, $w13
0x7a,0xbf,0x07,0x5a = fseq.d $w29, $w0, $w31
0x7b,0x9f,0xff,0x9a = fsle.w $w30, $w31, $w31
0x7b,0xb8,0xbc,0x9a = fsle.d $w18, $w23, $w24
0x7b,0x06,0x2b,0x1a = fslt.w $w12, $w5, $w6
0x7b,0x35,0xd4,0x1a = fslt.d $w16, $w26, $w21
0x7a,0xcc,0x0f,0x9c = fsne.w $w30, $w1, $w12
0x7a,0xf7,0x6b,0x9c = fsne.d $w14, $w13, $w23
0x7a,0x5b,0x6e,0xdc = fsor.w $w27, $w13, $w27
0x7a,0x6b,0xc3,0x1c = fsor.d $w12, $w24, $w11
0x78,0x41,0xd7,0xdb = fsub.w $w31, $w26, $w1
0x78,0x7b,0x8c,0xdb = fsub.d $w19, $w17, $w27
0x7a,0xd9,0xc4,0x1a = fsueq.w $w16, $w24, $w25
0x7a,0xee,0x74,0x9a = fsueq.d $w18, $w14, $w14
0x7b,0xcd,0xf5,0xda = fsule.w $w23, $w30, $w13
0x7b,0xfa,0x58,0x9a = fsule.d $w2, $w11, $w26
0x7b,0x56,0xd2,0xda = fsult.w $w11, $w26, $w22
0x7b,0x7e,0xb9,0x9a = fsult.d $w6, $w23, $w30
0x7a,0x5c,0x90,0xda = fsun.w $w3, $w18, $w28
0x7a,0x73,0x5c,0x9a = fsun.d $w18, $w11, $w19
0x7a,0x82,0xfc,0x1c = fsune.w $w16, $w31, $w2
0x7a,0xb1,0xd0,0xdc = fsune.d $w3, $w26, $w17
0x7a,0x98,0x24,0x1b = ftq.h $w16, $w4, $w24
0x7a,0xb9,0x29,0x5b = ftq.w $w5, $w5, $w25
0x79,0x4a,0xa4,0x1c = madd_q.h $w16, $w20, $w10
0x79,0x69,0x17,0x1c = madd_q.w $w28, $w2, $w9
0x7b,0x49,0x92,0x1c = maddr_q.h $w8, $w18, $w9
0x7b,0x70,0x67,0x5c = maddr_q.w $w29, $w12, $w16
0x79,0x8a,0xd6,0x1c = msub_q.h $w24, $w26, $w10
0x79,0xbc,0xf3,0x5c = msub_q.w $w13, $w30, $w28
0x7b,0x8b,0xab,0x1c = msubr_q.h $w12, $w21, $w11
0x7b,0xb4,0x70,0x5c = msubr_q.w $w1, $w14, $w20
0x79,0x1e,0x81,0x9c = mul_q.h $w6, $w16, $w30
0x79,0x24,0x0c,0x1c = mul_q.w $w16, $w1, $w4
0x7b,0x13,0xa1,0x9c = mulr_q.h $w6, $w20, $w19
0x7b,0x34,0x0e,0xdc = mulr_q.w $w27, $w1, $w20
| 45.464286 | 55 | 0.65436 | [
"BSD-3-Clause"
] | 02107/Lilu | capstone/suite/MC/Mips/test_3rf.s.cs | 3,819 | C# |
using System;
using _Game.GameActions;
using _Game.ShopSystem;
using _Game.Towers;
using _Game.UI.Towers;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace _Game.UI.Builder
{
//TODO: Should inherit ActionButton
public class BuildTowerButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
[SerializeField] private TMP_Text nameLabel = default;
[SerializeField] private Image image = default;
[SerializeField] private Button button = default;
[SerializeField] private TransactionUi transactionUi = default;
[SerializeField] protected AbstractAction action = default;
[SerializeField] private TMP_Text descriptionLabel = default;
private TowerGeneralData currentTower;
public void Init(TowerGeneralData tower)
{
currentTower = tower;
nameLabel.text = tower.DisplayName;
descriptionLabel.text = tower.ShortDescription;
image.sprite = tower.Sprite;
button.onClick.AddListener(OnPressed);
}
public void OnPointerEnter(PointerEventData eventData)
{
//base.OnPointerEnter(eventData);
transactionUi.Init(currentTower.TowerPrefab, action);
}
public void OnPointerExit(PointerEventData eventData)
{
//base.OnPointerExit(eventData);
transactionUi.Hide();
}
private void OnPressed()
{
var builder = FindObjectOfType<TowerBuilder>();
builder.TryBuildMode(currentTower);
}
}
} | 31.462963 | 93 | 0.636845 | [
"MIT"
] | MarcoElz/ggj22 | Assets/_Game/Scripts/UI/Builder/BuildTowerButton.cs | 1,701 | C# |
using System;
using System.Threading.Tasks;
using Confluent.Kafka;
using Kafker.Configurations;
using McMaster.Extensions.CommandLineUtils;
namespace Kafker.Kafka
{
public class RecordsProducer : IDisposable
{
private readonly IConsole _console;
private readonly KafkaTopicConfiguration _config;
private IProducer<string, string> _producer;
public RecordsProducer(IConsole console, KafkaTopicConfiguration config)
{
_console = console;
_config = config;
var producerConfig = new ProducerConfig
{
BootstrapServers = string.Join(',', config.Brokers)
};
var producerBuilder = new ProducerBuilder<string, string>(producerConfig);
_producer = producerBuilder.Build();
console.WriteLine($"Created a producer:");
console.WriteLine($" brokers: {producerConfig.BootstrapServers}");
console.WriteLine($" topic: {config.Topic}");
}
/// <inheritdoc />
public void Dispose()
{
_producer.Flush();
_producer.Dispose();
_producer = null;
}
public async Task ProduceAsync(string record)
{
var message = new Message<string, string>
{
Key = string.Empty,
Value = record
};
await _producer.ProduceAsync(_config.Topic, message);
}
}
} | 30.36 | 86 | 0.575758 | [
"MIT"
] | xtrmstep/Kafker | src/Kafker/Kafka/RecordsProducer.cs | 1,520 | C# |
using CaraDotNetCore5V2.Application.DTOs.Identity;
using CaraDotNetCore5V2.Application.DTOs.Mail;
using CaraDotNetCore5V2.Application.DTOs.Settings;
using CaraDotNetCore5V2.Application.Enums;
using CaraDotNetCore5V2.Application.Exceptions;
using CaraDotNetCore5V2.Application.Interfaces;
using CaraDotNetCore5V2.Application.Interfaces.Shared;
using CaraDotNetCore5V2.Infrastructure.Identity.Models;
using AspNetCoreHero.Results;
using AspNetCoreHero.ThrowR;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace CaraDotNetCore5V2.Infrastructure.Identity.Services
{
public class IdentityService : IIdentityService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly JWTSettings _jwtSettings;
private readonly IDateTimeService _dateTimeService;
private readonly IMailService _mailService;
public IdentityService(UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
IOptions<JWTSettings> jwtSettings,
IDateTimeService dateTimeService,
SignInManager<ApplicationUser> signInManager, IMailService mailService)
{
_userManager = userManager;
_roleManager = roleManager;
_jwtSettings = jwtSettings.Value;
_dateTimeService = dateTimeService;
_signInManager = signInManager;
_mailService = mailService;
}
public async Task<Result<TokenResponse>> GetTokenAsync(TokenRequest request, string ipAddress)
{
var user = await _userManager.FindByEmailAsync(request.Email);
Throw.Exception.IfNull(user, nameof(user), $"No Accounts Registered with {request.Email}.");
var result = await _signInManager.PasswordSignInAsync(user.UserName, request.Password, false, lockoutOnFailure: false);
Throw.Exception.IfFalse(user.EmailConfirmed, $"Email is not confirmed for '{request.Email}'.");
Throw.Exception.IfFalse(user.IsActive, $"Account for '{request.Email}' is not active. Please contact the Administrator.");
Throw.Exception.IfFalse(result.Succeeded, $"Invalid Credentials for '{request.Email}'.");
JwtSecurityToken jwtSecurityToken = await GenerateJWToken(user, ipAddress);
var response = new TokenResponse();
response.Id = user.Id;
response.JWToken = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
response.IssuedOn = jwtSecurityToken.ValidFrom.ToLocalTime();
response.ExpiresOn = jwtSecurityToken.ValidTo.ToLocalTime();
response.Email = user.Email;
response.UserName = user.UserName;
var rolesList = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
response.Roles = rolesList.ToList();
response.IsVerified = user.EmailConfirmed;
var refreshToken = GenerateRefreshToken(ipAddress);
response.RefreshToken = refreshToken.Token;
return Result<TokenResponse>.Success(response, "Authenticated");
}
private async Task<JwtSecurityToken> GenerateJWToken(ApplicationUser user, string ipAddress)
{
var userClaims = await _userManager.GetClaimsAsync(user);
var roles = await _userManager.GetRolesAsync(user);
var roleClaims = new List<Claim>();
for (int i = 0; i < roles.Count; i++)
{
roleClaims.Add(new Claim("roles", roles[i]));
}
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim("uid", user.Id),
new Claim("first_name", user.FirstName),
new Claim("last_name", user.LastName),
new Claim("full_name", $"{user.FirstName} {user.LastName}"),
new Claim("ip", ipAddress)
}
.Union(userClaims)
.Union(roleClaims);
return JWTGeneration(claims);
}
private JwtSecurityToken JWTGeneration(IEnumerable<Claim> claims)
{
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Key));
var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
var jwtSecurityToken = new JwtSecurityToken(
issuer: _jwtSettings.Issuer,
audience: _jwtSettings.Audience,
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddMinutes(_jwtSettings.DurationInMinutes),
signingCredentials: signingCredentials);
return jwtSecurityToken;
}
private string RandomTokenString()
{
using var rngCryptoServiceProvider = new RNGCryptoServiceProvider();
var randomBytes = new byte[40];
rngCryptoServiceProvider.GetBytes(randomBytes);
// convert random bytes to hex string
return BitConverter.ToString(randomBytes).Replace("-", "");
}
private RefreshToken GenerateRefreshToken(string ipAddress)
{
return new RefreshToken
{
Token = RandomTokenString(),
Expires = DateTime.UtcNow.AddDays(7),
Created = DateTime.UtcNow,
CreatedByIp = ipAddress
};
}
public async Task<Result<string>> RegisterAsync(RegisterRequest request, string origin)
{
var userWithSameUserName = await _userManager.FindByNameAsync(request.UserName);
if (userWithSameUserName != null)
{
throw new ApiException($"Username '{request.UserName}' is already taken.");
}
var user = new ApplicationUser
{
Email = request.Email,
FirstName = request.FirstName,
LastName = request.LastName,
UserName = request.UserName
};
var userWithSameEmail = await _userManager.FindByEmailAsync(request.Email);
if (userWithSameEmail == null)
{
var result = await _userManager.CreateAsync(user, request.Password);
if (result.Succeeded)
{
await _userManager.AddToRoleAsync(user, Roles.Basic.ToString());
var verificationUri = await SendVerificationEmail(user, origin);
//TODO: Attach Email Service here and configure it via appsettings
await _mailService.SendAsync(new MailRequest() { From = "mail@codewithmukesh.com", To = user.Email, Body = $"Please confirm your account by <a href='{verificationUri}'>clicking here</a>.", Subject = "Confirm Registration" });
return Result<string>.Success(user.Id, message: $"User Registered. Confirmation Mail has been delivered to your Mailbox. (DEV) Please confirm your account by visiting this URL {verificationUri}");
}
else
{
throw new ApiException($"{result.Errors}");
}
}
else
{
throw new ApiException($"Email {request.Email } is already registered.");
}
}
private async Task<string> SendVerificationEmail(ApplicationUser user, string origin)
{
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var route = "api/identity/confirm-email/";
var _enpointUri = new Uri(string.Concat($"{origin}/", route));
var verificationUri = QueryHelpers.AddQueryString(_enpointUri.ToString(), "userId", user.Id);
verificationUri = QueryHelpers.AddQueryString(verificationUri, "code", code);
//Email Service Call Here
return verificationUri;
}
public async Task<Result<string>> ConfirmEmailAsync(string userId, string code)
{
var user = await _userManager.FindByIdAsync(userId);
code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
var result = await _userManager.ConfirmEmailAsync(user, code);
if (result.Succeeded)
{
return Result<string>.Success(user.Id, message: $"Account Confirmed for {user.Email}. You can now use the /api/identity/token endpoint to generate JWT.");
}
else
{
throw new ApiException($"An error occured while confirming {user.Email}.");
}
}
public async Task ForgotPassword(ForgotPasswordRequest model, string origin)
{
var account = await _userManager.FindByEmailAsync(model.Email);
// always return ok response to prevent email enumeration
if (account == null) return;
var code = await _userManager.GeneratePasswordResetTokenAsync(account);
var route = "api/identity/reset-password/";
var _enpointUri = new Uri(string.Concat($"{origin}/", route));
var emailRequest = new MailRequest()
{
Body = $"You reset token is - {code}",
To = model.Email,
Subject = "Reset Password",
};
//await _mailService.SendAsync(emailRequest);
}
public async Task<Result<string>> ResetPassword(ResetPasswordRequest model)
{
var account = await _userManager.FindByEmailAsync(model.Email);
if (account == null) throw new ApiException($"No Accounts Registered with {model.Email}.");
var result = await _userManager.ResetPasswordAsync(account, model.Token, model.Password);
if (result.Succeeded)
{
return Result<string>.Success(model.Email, message: $"Password Resetted.");
}
else
{
throw new ApiException($"Error occured while reseting the password.");
}
}
}
} | 47.012987 | 245 | 0.630295 | [
"MIT"
] | rosdisulaiman/CaraDotNetCore5V2 | CaraDotNetCore5V2.Infrastructure/Identity/Services/IdentityService.cs | 10,862 | C# |
using System;
using NUnit.Framework;
// ReSharper disable InvokeAsExtensionMethod
namespace BitFn.Core.Tests.Extensions.ForString
{
[TestFixture]
public class RemoveDiacritics
{
[TestCase("à la mode", Result = "a la mode")]
[TestCase("cañón", Result = "canon")]
[TestCase("daïs", Result = "dais")]
[TestCase("El Niño", Result = "El Nino")]
[TestCase("façade", Result = "facade")]
[TestCase("phở", Result = "pho")]
[TestCase("tête-à-tête", Result = "tete-a-tete")]
[TestCase("zoölogy", Result = "zoology")]
public string WhenGivenDiacritics_ReturnsStripped(string s)
{
return Core.Extensions.ForString.RemoveDiacritics(s);
}
[Test]
public void WhenGivenEmptyString_ReturnsEmpty()
{
// Arrange
var expected = string.Empty;
// Act
var actual = Core.Extensions.ForString.RemoveDiacritics(string.Empty);
// Assert
Assert.AreEqual(expected, actual);
}
[Test]
public void WhenGivenNull_ThrowsArgumentNullException()
{
// Arrange
TestDelegate code = () => Core.Extensions.ForString.RemoveDiacritics(null);
// Act
// Assert
Assert.Throws<ArgumentNullException>(code);
}
}
} | 25.488889 | 78 | 0.692241 | [
"MIT"
] | BitFn/Core | Tests/Extensions/ForString/RemoveDiacritics.cs | 1,161 | C# |
using RedditRemindCrypto.Business.Interpreters.AbstractSyntaxTree;
using RedditRemindCrypto.Business.Interpreters.Enums;
using RedditRemindCrypto.Business.Interpreters.Exceptions;
using RedditRemindCrypto.Business.Interpreters.Models;
using System.Linq;
namespace RedditRemindCrypto.Business.Interpreters
{
public class Interpreter : NodeVisitor
{
private readonly Parser parser;
private readonly TokenConverter tokenConverter;
public Interpreter(Parser parser, TokenConverter tokenConverter)
{
this.parser = parser;
this.tokenConverter = tokenConverter;
}
public InterpreterResult Interpret()
{
var tree = parser.Parse();
return (InterpreterResult)Visit(tree);
}
public InterpreterResult VisitBinaryOperatorNode(BinaryOperatorNode node)
{
switch (node.Op.Type)
{
case TokenType.And:
return InterpreterResult.And(Visit(node.Left) as InterpreterResult, Visit(node.Right) as InterpreterResult);
case TokenType.Or:
return InterpreterResult.Or(Visit(node.Left) as InterpreterResult, Visit(node.Right) as InterpreterResult);
case TokenType.LargerThan:
return new InterpreterResult((decimal)Visit(node.Left) > (decimal)Visit(node.Right), null);
case TokenType.SmallerThan:
return new InterpreterResult((decimal)Visit(node.Left) < (decimal)Visit(node.Right), null);
default:
throw new InvalidSyntaxException("Error syntax");
}
}
public object VisitMethodNode(MethodNode node)
{
var methodToken = node.Token as MethodToken;
switch (methodToken.Method)
{
case Method.After:
{
if (node.Parameters.Count() != 1)
throw new InvalidSyntaxException($"Method '{nameof(Method.MarketCap)}' received an invalid amount of parameters");
var stringToken = node.Parameters[0].Token as StringToken;
return tokenConverter.IsAfterDateTime(stringToken);
}
case Method.Before:
{
if (node.Parameters.Count() != 1)
throw new InvalidSyntaxException($"Method '{nameof(Method.MarketCap)}' received an invalid amount of parameters");
var stringToken = node.Parameters[0].Token as StringToken;
return tokenConverter.IsBeforeDateTime(stringToken);
}
case Method.MarketCap:
{
if (node.Parameters.Count() != 1)
throw new InvalidSyntaxException($"Method '{nameof(Method.MarketCap)}' received an invalid amount of parameters");
var currencyToken = node.Parameters[0].Token as CurrencyToken;
return tokenConverter.ToUsdMarketCap(currencyToken);
}
case Method.Price:
{
if (node.Parameters.Count() != 1)
throw new InvalidSyntaxException($"Method '{nameof(Method.Price)}' received an invalid amount of parameters");
var currencyToken = node.Parameters[0].Token as CurrencyToken;
return tokenConverter.ToUsdPrice(currencyToken);
}
case Method.HasRankOrHigher:
{
if (node.Parameters.Count() != 2)
throw new InvalidSyntaxException($"Method '{nameof(Method.HasRankOrHigher)}' received an invalid amount of parameters");
var rank = node.Parameters[0].Token as NumberToken;
var currencyToken = node.Parameters[1].Token as CurrencyToken;
return tokenConverter.HasRankOrHigher(rank, currencyToken);
}
case Method.Volume:
{
if (node.Parameters.Count() != 1)
throw new InvalidSyntaxException($"Method '{nameof(Method.Volume)}' received an invalid amount of parameters");
var currencyToken = node.Parameters[0].Token as CurrencyToken;
return tokenConverter.ToUsdVolume(currencyToken);
}
default:
throw new InvalidSyntaxException("Error syntax");
}
}
public decimal VisitNumberNode(NumberNode node)
{
switch (node.token.Type)
{
case TokenType.CurrencyAmount:
return tokenConverter.ToUSD(node.token as CurrencyAmountToken);
default:
throw new InvalidSyntaxException("Error syntax");
}
}
}
}
| 44.833333 | 148 | 0.55586 | [
"MIT"
] | parijsy/RedditRemindCrypto | RedditRemindCrypto/RedditRemindCrypto.Business/Interpreters/Interpreter.cs | 5,113 | C# |
// Copyright (c) 2017 Leacme (http://leac.me). View LICENSE.md for more information.
using System;
using System.Collections.Generic;
using LiteDB;
namespace Leacme.Lib.Notables {
public class Library {
private LiteDatabase db = new LiteDatabase(typeof(Library).Namespace + ".Settings.db");
private LiteCollection<Notable> notableCollection;
public Library() {
notableCollection = db.GetCollection<Notable>(nameof(notableCollection));
}
/// <summary>
/// Add an example notable to an unitialized database.
/// /// </summary>
public void AddInitialExampleNotable() {
if (!db.CollectionExists(nameof(notableCollection))) {
notableCollection.Insert(new Notable(DateTime.Now, "Example Notable Title", "Example Notable Text"));
}
}
/// <summary>
/// Store the <c>Notable</c> entity in the database.
/// /// </summary>
/// <param name="notable"></param>
/// <returns>The generated id of the stored entity.</returns>
public int StoreNotable(Notable notable) {
return notableCollection.Insert(notable);
}
/// <summary>
/// Retrieve all stored <c>Notable</c> entities from the database.
/// /// </summary>
/// <returns>The <c>Notable</c> entities.</returns>
public IEnumerable<Notable> GetStoredNotables() {
return notableCollection.FindAll();
}
/// <summary>
/// Delete the <c>Notable</c> entity from the database via its id.
/// /// </summary>
/// <param name="notable"></param>
/// <returns>If the entity was deleted.</returns>
public bool DeleteNotable(Notable notable) {
return notableCollection.Delete(notable.Id);
}
}
} | 30.320755 | 105 | 0.687617 | [
"MIT"
] | dekterov/Leacme.Notables | Leacme.Lib.Notables/Library.cs | 1,607 | C# |
namespace KNXLib.Addressing
{
using Exceptions;
public class KnxIndividualAddress : KnxAddress
{
public int Area { get; set; }
public int Line { get; set; }
public int Participant { get; set; }
public KnxIndividualAddress(int area, int line, int participant)
{
Area = area;
Line = line;
Participant = participant;
}
public KnxIndividualAddress(string address) => InternalParse(address);
public KnxIndividualAddress(byte[] address) => InternalParse(address);
// +-----------------------------------------------+
// 16 bits | INDIVIDUAL ADDRESS |
// +-----------------------+-----------------------+
// | OCTET 0 (high byte) | OCTET 1 (low byte) |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// bits | 7| 6| 5| 4| 3| 2| 1| 0| 7| 6| 5| 4| 3| 2| 1| 0|
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | Area | Line | Participant |
// +-----------------------+-----------------------+
public override byte[] GetAddress()
{
if (!IsValid())
throw new InvalidKnxAddressException(ToString());
var addr = new byte[2];
addr[0] = (byte)(Area << 4);
addr[0] = (byte)(addr[0] | Line);
addr[1] = (byte)Participant;
return addr;
}
public override bool IsValid()
{
// 0.0.0 is not allowed
// see https://support.knx.org/hc/en-us/articles/115003185789-Individual-Address
if (Area == 0 && Line == 0 && Participant == 0)
return false;
// Check range for Area 0-15
if (Area < 0 || Area > 15)
return false;
// Check range for Line 0-15
if (Line < 0 || Line > 15)
return false;
// Check range for Participant 0-255
if (Participant < 0 || Participant > 255)
return false;
return true;
}
protected override void InternalParse(string address)
{
var addressParts = address.Split('.');
// Check if individual address consists of 3 parts
if (addressParts.Length != 3)
return;
if (!int.TryParse(addressParts[0], out int area) ||
!int.TryParse(addressParts[1], out int line) ||
!int.TryParse(addressParts[2], out int participant))
return;
Area = area;
Line = line;
Participant = participant;
}
protected override void InternalParse(byte[] address)
{
if (address.Length != 2)
return;
Area = address[0] >> 4;
Line = address[0] & 0x0F;
Participant = address[1];
}
public override string ToString() => $"{Area}.{Line}.{Participant}";
public new static KnxIndividualAddress Parse(string address) => new KnxIndividualAddress(address);
public static KnxIndividualAddress Parse(byte[] address) => new KnxIndividualAddress(address);
public bool Equals(int area, int line, int participant)
=> Area == area && Line == line && Participant == participant;
public override bool Equals(object obj) => obj is KnxIndividualAddress && base.Equals(obj);
public override int GetHashCode() => base.GetHashCode();
}
}
| 34.327273 | 107 | 0.454714 | [
"MIT"
] | CumpsD/knx.net | src/KNXLib/Addressing/KnxIndividualAddress.cs | 3,778 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WebAPI
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.481481 | 70 | 0.642442 | [
"MIT"
] | 03012021-dotnet-uta/MatthewGrimsley_p1 | WebAPI/Program.cs | 688 | C# |
/**
* Author
* Pierre Bouillon - https://github.com/pBouillon
*
* Repository
* UrlShortener - https://github.com/pBouillon/UrlShortener
*
* License
* MIT - https://github.com/pBouillon/UrlShortener/blob/master/LICENSE
*/
namespace UrlShortener.Common.Contracts.Configuration
{
/// <summary>
/// References Swagger project header's data
/// </summary>
public class ProjectDto
{
/// <summary>
/// API version
/// </summary>
public string ApiVersion { get; set; }
/// <summary>
/// Author's contact
/// </summary>
public ContactDto Contact { get; set; }
/// <summary>
/// Project's description
/// </summary>
public string Description { get; set; }
/// <summary>
/// License information
/// </summary>
public LicenseDto License { get; set; }
/// <summary>
/// Terms of service of the API
/// </summary>
public string TermsOfService { get; set; }
/// <summary>
/// API's title
/// </summary>
public string Title { get; set; }
/// <summary>
/// API's version
/// </summary>
public string Version { get; set; }
}
}
| 24.418182 | 76 | 0.504095 | [
"MIT"
] | pBouillon/UrlShortener | Core/UrlShortener.Common/Contracts/Configuration/ProjectDto.cs | 1,345 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using KeyPayV2.Au.Models.Common;
using KeyPayV2.Au.Enums;
namespace KeyPayV2.Au.Models.Reporting
{
public class AuRosterTimesheetComparisonReportExportModel
{
public string EmploymentType { get; set; }
public int EmployeeId { get; set; }
public string EmployeeFirstName { get; set; }
public string EmployeeSurname { get; set; }
public string EmployeeExternalId { get; set; }
public string EmployeeDefaultLocation { get; set; }
public string PayScheduleName { get; set; }
public int? RosteredId { get; set; }
public string RosteredStatus { get; set; }
public string RosteredLocation { get; set; }
public string RosteredWorkType { get; set; }
public DateTime? RosteredStart { get; set; }
public TimeSpan? RosteredStartTime { get; set; }
public DateTime? RosteredEnd { get; set; }
public TimeSpan? RosteredEndTime { get; set; }
public TimeSpan? RosteredDuration { get; set; }
public TimeSpan? RosteredBreaks { get; set; }
public decimal? RosteredCost { get; set; }
public int? TimesheetId { get; set; }
public string TimesheetStatus { get; set; }
public string TimesheetLocation { get; set; }
public string TimesheetWorkType { get; set; }
public DateTime? TimesheetStart { get; set; }
public TimeSpan? TimesheetStartTime { get; set; }
public DateTime? TimesheetEnd { get; set; }
public TimeSpan? TimesheetEndTime { get; set; }
public TimeSpan? TimesheetDuration { get; set; }
public TimeSpan? TimesheetBreaks { get; set; }
public decimal? TimesheetUnits { get; set; }
public string TimesheetUnitType { get; set; }
public decimal? TimesheetCost { get; set; }
public TimeSpan TimeVariance { get; set; }
public decimal CostVariance { get; set; }
}
}
| 44.456522 | 62 | 0.636675 | [
"MIT"
] | KeyPay/keypay-dotnet-v2 | src/keypay-dotnet/Au/Models/Reporting/AuRosterTimesheetComparisonReportExportModel.cs | 2,045 | C# |
using System.Collections.Generic;
namespace SendMail.WebApi.Models.Validators
{
public interface IRemotePropertyValidator
{
string Url { get; }
string ErrorText { get; }
IEnumerable<string> AdditionalFields { get; }
}
} | 23.272727 | 53 | 0.675781 | [
"MIT"
] | AngeloDotNet/FacileBudget-2 | src/FacileBudget/Backend/SendMail.WebApi/Models/Validators/IRemotePropertyValidator.cs | 256 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace DataAccessLayer.Migrations
{
public partial class migration_writer_blog_relation : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "WriterId",
table: "Blogs",
type: "int",
nullable: true,
defaultValue: 0);
migrationBuilder.CreateIndex(
name: "IX_Blogs_WriterId",
table: "Blogs",
column: "WriterId");
migrationBuilder.AddForeignKey(
name: "FK_Blogs_Writers_WriterId",
table: "Blogs",
column: "WriterId",
principalTable: "Writers",
principalColumn: "WriterId",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Blogs_Writers_WriterId",
table: "Blogs");
migrationBuilder.DropIndex(
name: "IX_Blogs_WriterId",
table: "Blogs");
migrationBuilder.DropColumn(
name: "WriterId",
table: "Blogs");
}
}
}
| 29.913043 | 71 | 0.53125 | [
"MIT"
] | murat1347/DotNet-Core-Blog | DataAccessLayer/Migrations/20220120192726_migration_writer_blog_relation.cs | 1,378 | C# |
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleTo("GameEngine.Tests")] | 30 | 49 | 0.833333 | [
"MIT"
] | spinesheath/Spines.Mahjong | Ai/Game/Properties/AssemblyInfo.cs | 92 | C# |
namespace Observatory.Framework.Files.Journal
{
public class FSSSignalDiscovered : JournalBase
{
public string SignalName { get; init; }
public string SignalName_Localised { get; init; }
public string SpawningState { get; init; }
public string SpawningState_Localised { get; init; }
public string SpawningFaction { get; init; }
public string SpawningFaction_Localised { get; init; }
public float TimeRemaining { get; init; }
public ulong SystemAddress { get; init; }
public int ThreatLevel { get; init; }
public string USSType { get; init; }
public string USSType_Localised { get; init; }
public bool IsStation { get; init; }
}
}
| 38.894737 | 62 | 0.648173 | [
"MIT"
] | Xjph/ObservatoryCore | ObservatoryFramework/Files/Journal/Exploration/FSSSignalDiscovered.cs | 741 | C# |
using Bongo.DataAccess.Repository.IRepository;
using Bongo.Models.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bongo.DataAccess.Repository
{
public class StudyRoomBookingRepository : IStudyRoomBookingRepository
{
private readonly ApplicationDbContext _context;
public StudyRoomBookingRepository(ApplicationDbContext context)
{
_context = context;
}
public IEnumerable<StudyRoomBooking> GetAll(DateTime? date)
{
if (date != null)
{
return _context.StudyRoomBookings.Where(x => x.Date == date).OrderBy(x => x.BookingId).ToList();
}
return _context.StudyRoomBookings.OrderBy(x => x.BookingId).ToList();
}
public void Book(StudyRoomBooking booking)
{
_context.StudyRoomBookings.Add(booking);
_context.SaveChanges();
}
}
}
| 27.324324 | 112 | 0.641939 | [
"MIT"
] | Redwoodcutter/FirstUnitTestC- | Bongo_InitialSetup (.NET 6)/Bongo.DataAccess/Repository/StudyRoomBookingRepository.cs | 1,013 | C# |
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
namespace VoipProjectEntities.Identity.Models
{
public class Customer : IdentityUser
{
public string CustomerName { get; set; }
public bool ISMigrated { get; set; }
public int CustomerTypeID { get; set; } //enum
public bool ISTrialBalanceOpted { get; set; }
public string OrganisationName { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public List<RefreshToken> RefreshTokens { get; set; }
}
}
| 31.736842 | 61 | 0.666667 | [
"Apache-2.0"
] | Anagha1009/VoIPCustomerWebPortal-1 | src/Infrastructure/VoipProjectEntities.Identity/Models/Customer.cs | 603 | C# |
using System;
using System.IO;
using System.IO.Compression;
namespace _6.ZipAndExtract
{
class Program
{
static void Main(string[] args)
{
using ZipArchive zipFile = ZipFile.Open("../../../zipfile.zip", ZipArchiveMode.Create);
ZipArchiveEntry zipArchiveEntry = zipFile.CreateEntryFromFile("../../../copyMe.png", "result.png");
}
}
}
| 24.6875 | 111 | 0.620253 | [
"MIT"
] | HNochev/SoftUni-CSharp-Software-Engineering | C# Advanced/C# ADVANCED/Exercise 4 - Streams, Files and Directories/6.ZipAndExtract/Program.cs | 397 | C# |
// Copyright by the contributors to the Dafny Project
// SPDX-License-Identifier: MIT
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Bpl = Microsoft.Boogie;
using IToken = Microsoft.Boogie.IToken;
namespace Microsoft.Dafny
{
public abstract class IRewriter
{
protected readonly ErrorReporter reporter;
public IRewriter(ErrorReporter reporter) {
Contract.Requires(reporter != null);
this.reporter = reporter;
}
internal virtual void PreResolve(ModuleDefinition m) {
Contract.Requires(m != null);
}
internal virtual void PostResolve(ModuleDefinition m) {
Contract.Requires(m != null);
}
// After SCC/Cyclicity/Recursivity analysis:
internal virtual void PostCyclicityResolve(ModuleDefinition m) {
Contract.Requires(m != null);
}
// After SCC/Cyclicity/Recursivity analysis and after application of default decreases:
internal virtual void PostDecreasesResolve(ModuleDefinition m) {
Contract.Requires(m != null);
}
}
public class AutoGeneratedToken : TokenWrapper
{
public AutoGeneratedToken(Boogie.IToken wrappedToken)
: base(wrappedToken)
{
Contract.Requires(wrappedToken != null);
}
}
public class TriggerGeneratingRewriter : IRewriter {
internal TriggerGeneratingRewriter(ErrorReporter reporter) : base(reporter) {
Contract.Requires(reporter != null);
}
internal override void PostCyclicityResolve(ModuleDefinition m) {
var finder = new Triggers.QuantifierCollector(reporter);
foreach (var decl in ModuleDefinition.AllCallables(m.TopLevelDecls)) {
finder.Visit(decl, null);
}
var triggersCollector = new Triggers.TriggersCollector(finder.exprsInOldContext);
foreach (var quantifierCollection in finder.quantifierCollections) {
quantifierCollection.ComputeTriggers(triggersCollector);
quantifierCollection.CommitTriggers();
}
}
}
internal class QuantifierSplittingRewriter : IRewriter {
internal QuantifierSplittingRewriter(ErrorReporter reporter) : base(reporter) {
Contract.Requires(reporter != null);
}
internal override void PostResolve(ModuleDefinition m) {
var splitter = new Triggers.QuantifierSplitter();
foreach (var decl in ModuleDefinition.AllCallables(m.TopLevelDecls)) {
splitter.Visit(decl);
}
splitter.Commit();
}
}
// write out the quantifier for ForallStmt
public class ForallStmtRewriter : IRewriter
{
public ForallStmtRewriter(ErrorReporter reporter) : base(reporter) {
Contract.Requires(reporter != null);
}
internal override void PostResolve(ModuleDefinition m) {
var forallvisiter = new ForAllStmtVisitor(reporter);
foreach (var decl in ModuleDefinition.AllCallables(m.TopLevelDecls)) {
forallvisiter.Visit(decl, true);
if (decl is ExtremeLemma) {
var prefixLemma = ((ExtremeLemma)decl).PrefixLemma;
if (prefixLemma != null) {
forallvisiter.Visit(prefixLemma, true);
}
}
}
}
internal class ForAllStmtVisitor : TopDownVisitor<bool>
{
readonly ErrorReporter reporter;
public ForAllStmtVisitor(ErrorReporter reporter) {
Contract.Requires(reporter != null);
this.reporter = reporter;
}
protected override bool VisitOneStmt(Statement stmt, ref bool st) {
if (stmt is ForallStmt && ((ForallStmt)stmt).CanConvert) {
ForallStmt s = (ForallStmt)stmt;
if (s.Kind == ForallStmt.BodyKind.Proof) {
Expression term = s.Ens.Count != 0 ? s.Ens[0].E : Expression.CreateBoolLiteral(s.Tok, true);
for (int i = 1; i < s.Ens.Count; i++) {
term = new BinaryExpr(s.Tok, BinaryExpr.ResolvedOpcode.And, term, s.Ens[i].E);
}
List<Expression> exprList = new List<Expression>();
ForallExpr expr = new ForallExpr(s.Tok, s.BoundVars, s.Range, term, s.Attributes);
expr.Type = Type.Bool; // resolve here
expr.Bounds = s.Bounds;
exprList.Add(expr);
s.ForallExpressions = exprList;
} else if (s.Kind == ForallStmt.BodyKind.Assign) {
if (s.BoundVars.Count != 0) {
var s0 = (AssignStmt)s.S0;
if (s0.Rhs is ExprRhs) {
List<Expression> exprList = new List<Expression>();
Expression Fi = null;
Func<Expression, Expression> lhsBuilder = null;
var lhs = s0.Lhs.Resolved;
var i = s.BoundVars[0];
if (s.BoundVars.Count == 1) {
//var lhsContext = null;
// Detect the following cases:
// 0: forall i | R(i) { F(i).f := E(i); }
// 1: forall i | R(i) { A[F(i)] := E(i); }
// 2: forall i | R(i) { F(i)[N] := E(i); }
if (lhs is MemberSelectExpr) {
var ll = (MemberSelectExpr)lhs;
Fi = ll.Obj;
lhsBuilder = e => {
var l = new MemberSelectExpr(ll.tok, e, ll.MemberName);
l.Member = ll.Member;
l.TypeApplication_AtEnclosingClass = ll.TypeApplication_AtEnclosingClass;
l.TypeApplication_JustMember = ll.TypeApplication_JustMember;
l.Type = ll.Type;
return l; };
} else if (lhs is SeqSelectExpr) {
var ll = (SeqSelectExpr)lhs;
Contract.Assert(ll.SelectOne);
if (!Translator.ContainsFreeVariable(ll.Seq, false, i)) {
Fi = ll.E0;
lhsBuilder = e => { var l = new SeqSelectExpr(ll.tok, true, ll.Seq, e, null); l.Type = ll.Type; return l; };
} else if (!Translator.ContainsFreeVariable(ll.E0, false, i)) {
Fi = ll.Seq;
lhsBuilder = e => { var l = new SeqSelectExpr(ll.tok, true, e, ll.E0, null); l.Type = ll.Type; return l; };
}
}
}
var rhs = ((ExprRhs)s0.Rhs).Expr;
bool usedInversion = false;
if (Fi != null) {
var j = new BoundVar(i.tok, i.Name + "#inv", Fi.Type);
var jj = Expression.CreateIdentExpr(j);
var jList = new List<BoundVar>() { j };
var range = Expression.CreateAnd(Resolver.GetImpliedTypeConstraint(i, i.Type), s.Range);
var vals = InvertExpression(i, j, range, Fi);
#if DEBUG_PRINT
Console.WriteLine("DEBUG: Trying to invert:");
Console.WriteLine("DEBUG: " + Printer.ExprToString(s.Range) + " && " + j.Name + " == " + Printer.ExprToString(Fi));
if (vals == null) {
Console.WriteLine("DEBUG: Can't");
} else {
Console.WriteLine("DEBUG: The inverse is the disjunction of the following:");
foreach (var val in vals) {
Console.WriteLine("DEBUG: " + Printer.ExprToString(val.Range) + " && " + Printer.ExprToString(val.FInverse) + " == " + i.Name);
}
}
#endif
if (vals != null) {
foreach (var val in vals) {
lhs = lhsBuilder(jj);
Attributes attributes = new Attributes("trigger", new List<Expression>() { lhs }, s.Attributes);
var newRhs = Substitute(rhs, i, val.FInverse);
var msg = string.Format("rewrite: forall {0}: {1} {2}| {3} {{ {4} := {5}; }}",
j.Name,
j.Type.ToString(),
Printer.AttributesToString(attributes),
Printer.ExprToString(val.Range),
Printer.ExprToString(lhs),
Printer.ExprToString(newRhs));
reporter.Info(MessageSource.Resolver, stmt.Tok, msg);
var expr = new ForallExpr(s.Tok, jList, val.Range, new BinaryExpr(s.Tok, BinaryExpr.ResolvedOpcode.EqCommon, lhs, newRhs), attributes);
expr.Type = Type.Bool; //resolve here
exprList.Add(expr);
}
usedInversion = true;
}
}
if (!usedInversion) {
var expr = new ForallExpr(s.Tok, s.BoundVars, s.Range, new BinaryExpr(s.Tok, BinaryExpr.ResolvedOpcode.EqCommon, lhs, rhs), s.Attributes);
expr.Type = Type.Bool; // resolve here
expr.Bounds = s.Bounds;
exprList.Add(expr);
}
s.ForallExpressions = exprList;
}
}
} else if (s.Kind == ForallStmt.BodyKind.Call) {
var s0 = (CallStmt)s.S0;
var argsSubstMap = new Dictionary<IVariable, Expression>(); // maps formal arguments to actuals
Contract.Assert(s0.Method.Ins.Count == s0.Args.Count);
for (int i = 0; i < s0.Method.Ins.Count; i++) {
argsSubstMap.Add(s0.Method.Ins[i], s0.Args[i]);
}
var substituter = new Translator.AlphaConverting_Substituter(s0.Receiver, argsSubstMap, s0.MethodSelect.TypeArgumentSubstitutionsWithParents());
// Strengthen the range of the "forall" statement with the precondition of the call, suitably substituted with the actual parameters.
if (Attributes.Contains(s.Attributes, "_autorequires")) {
var range = s.Range;
foreach (var req in s0.Method.Req) {
var p = substituter.Substitute(req.E); // substitute the call's actuals for the method's formals
range = Expression.CreateAnd(range, p);
}
s.Range = range;
}
// substitute the call's actuals for the method's formals
Expression term = s0.Method.Ens.Count != 0 ? substituter.Substitute(s0.Method.Ens[0].E) : Expression.CreateBoolLiteral(s.Tok, true);
for (int i = 1; i < s0.Method.Ens.Count; i++) {
term = new BinaryExpr(s.Tok, BinaryExpr.ResolvedOpcode.And, term, substituter.Substitute(s0.Method.Ens[i].E));
}
List<Expression> exprList = new List<Expression>();
ForallExpr expr = new ForallExpr(s.Tok, s.BoundVars, s.Range, term, s.Attributes);
expr.Type = Type.Bool; // resolve here
expr.Bounds = s.Bounds;
exprList.Add(expr);
s.ForallExpressions = exprList;
} else {
Contract.Assert(false); // unexpected kind
}
}
return true; //visit the sub-parts with the same "st"
}
internal class ForallStmtTranslationValues
{
public readonly Expression Range;
public readonly Expression FInverse;
public ForallStmtTranslationValues(Expression range, Expression fInverse) {
Contract.Requires(range != null);
Contract.Requires(fInverse != null);
Range = range;
FInverse = fInverse;
}
public ForallStmtTranslationValues Subst(IVariable j, Expression e) {
Contract.Requires(j != null);
Contract.Requires(e != null);
Dictionary<TypeParameter, Type> typeMap = new Dictionary<TypeParameter, Type>();
var substMap = new Dictionary<IVariable, Expression>();
substMap.Add(j, e);
Translator.Substituter sub = new Translator.Substituter(null, substMap, typeMap);
var v = new ForallStmtTranslationValues(sub.Substitute(Range), sub.Substitute(FInverse));
return v;
}
}
/// <summary>
/// Find piecewise inverse of F under R. More precisely, find lists of expressions P and F-1
/// such that
/// R(i) && j == F(i)
/// holds iff the disjunction of the following predicates holds:
/// P_0(j) && F-1_0(j) == i
/// ...
/// P_{n-1}(j) && F-1_{n-1}(j) == i
/// If no such disjunction is found, return null.
/// If such a disjunction is found, return for each disjunct:
/// * The predicate P_k(j), which is an expression that may have free occurrences of j (but no free occurrences of i)
/// * The expression F-1_k(j), which also may have free occurrences of j but not of i
/// </summary>
private List<ForallStmtTranslationValues> InvertExpression(BoundVar i, BoundVar j, Expression R, Expression F) {
Contract.Requires(i != null);
Contract.Requires(j != null);
Contract.Requires(R != null);
Contract.Requires(F != null);
var vals = new List<ForallStmtTranslationValues>(InvertExpressionIter(i, j, R, F));
if (vals.Count == 0) {
return null;
} else {
return vals;
}
}
/// <summary>
/// See InvertExpression.
/// </summary>
private IEnumerable<ForallStmtTranslationValues> InvertExpressionIter(BoundVar i, BoundVar j, Expression R, Expression F) {
Contract.Requires(i != null);
Contract.Requires(j != null);
Contract.Requires(R != null);
Contract.Requires(F != null);
F = F.Resolved;
if (!Translator.ContainsFreeVariable(F, false, i)) {
// We're looking at R(i) && j == K.
// We cannot invert j == K, but if we're lucky, R(i) contains a conjunct i==G.
Expression r = Expression.CreateBoolLiteral(R.tok, true);
Expression G = null;
foreach (var c in Expression.Conjuncts(R)) {
if (G == null && c is BinaryExpr) {
var bin = (BinaryExpr)c;
if (BinaryExpr.IsEqualityOp(bin.ResolvedOp)) {
var id = bin.E0.Resolved as IdentifierExpr;
if (id != null && id.Var == i) {
G = bin.E1;
continue;
}
id = bin.E1.Resolved as IdentifierExpr;
if (id != null && id.Var == i) {
G = bin.E0;
continue;
}
}
}
r = Expression.CreateAnd(r, c);
}
if (G != null) {
var jIsK = Expression.CreateEq(Expression.CreateIdentExpr(j), F, j.Type);
var rr = Substitute(r, i, G);
yield return new ForallStmtTranslationValues(Expression.CreateAnd(rr, jIsK), G);
}
} else if (F is IdentifierExpr) {
var e = (IdentifierExpr)F;
if (e.Var == i) {
// We're looking at R(i) && j == i, which is particularly easy to invert: R(j) && j == i
var jj = Expression.CreateIdentExpr(j);
yield return new ForallStmtTranslationValues(Substitute(R, i, jj), jj);
}
} else if (F is BinaryExpr) {
var bin = (BinaryExpr)F;
if (bin.ResolvedOp == BinaryExpr.ResolvedOpcode.Add && (bin.E0.Type.IsIntegerType || bin.E0.Type.IsRealType)) {
if (!Translator.ContainsFreeVariable(bin.E1, false, i)) {
// We're looking at: R(i) && j == f(i) + K.
// By a recursive call, we'll ask to invert: R(i) && j' == f(i).
// For each P_0(j') && f-1_0(j') == i we get back, we yield:
// P_0(j - K) && f-1_0(j - K) == i
var jMinusK = Expression.CreateSubtract(Expression.CreateIdentExpr(j), bin.E1);
foreach (var val in InvertExpression(i, j, R, bin.E0)) {
yield return val.Subst(j, jMinusK);
}
} else if (!Translator.ContainsFreeVariable(bin.E0, false, i)) {
// We're looking at: R(i) && j == K + f(i)
// Do as in previous case, but with operands reversed.
var jMinusK = Expression.CreateSubtract(Expression.CreateIdentExpr(j), bin.E0);
foreach (var val in InvertExpression(i, j, R, bin.E1)) {
yield return val.Subst(j, jMinusK);
}
}
} else if (bin.ResolvedOp == BinaryExpr.ResolvedOpcode.Sub && (bin.E0.Type.IsIntegerType || bin.E0.Type.IsRealType)) {
if (!Translator.ContainsFreeVariable(bin.E1, false, i)) {
// We're looking at: R(i) && j == f(i) - K
// Recurse on f(i) and then replace j := j + K
var jPlusK = Expression.CreateAdd(Expression.CreateIdentExpr(j), bin.E1);
foreach (var val in InvertExpression(i, j, R, bin.E0)) {
yield return val.Subst(j, jPlusK);
}
} else if (!Translator.ContainsFreeVariable(bin.E0, false, i)) {
// We're looking at: R(i) && j == K - f(i)
// Recurse on f(i) and then replace j := K - j
var kMinusJ = Expression.CreateSubtract(bin.E0, Expression.CreateIdentExpr(j));
foreach (var val in InvertExpression(i, j, R, bin.E1)) {
yield return val.Subst(j, kMinusJ);
}
}
}
} else if (F is ITEExpr) {
var ife = (ITEExpr)F;
// We're looking at R(i) && j == if A(i) then B(i) else C(i), which is equivalent to the disjunction of:
// R(i) && A(i) && j == B(i)
// R(i) && !A(i) && j == C(i)
// We recurse on each one, yielding the results
var r = Expression.CreateAnd(R, ife.Test);
var valsThen = InvertExpression(i, j, r, ife.Thn);
if (valsThen != null) {
r = Expression.CreateAnd(R, Expression.CreateNot(ife.tok, ife.Test));
var valsElse = InvertExpression(i, j, r, ife.Els);
if (valsElse != null) {
foreach (var val in valsThen) { yield return val; }
foreach (var val in valsElse) { yield return val; }
}
}
}
}
Expression Substitute(Expression expr, IVariable v, Expression e) {
Dictionary<IVariable, Expression/*!*/> substMap = new Dictionary<IVariable, Expression>();
Dictionary<TypeParameter, Type> typeMap = new Dictionary<TypeParameter, Type>();
substMap.Add(v, e);
Translator.Substituter sub = new Translator.Substituter(null, substMap, typeMap);
return sub.Substitute(expr);
}
}
}
/// <summary>
/// AutoContracts is an experimental feature that will fill much of the dynamic-frames boilerplate
/// into a class. From the user's perspective, what needs to be done is simply:
/// - mark the class with {:autocontracts}
/// - declare a function (or predicate) called Valid()
///
/// AutoContracts will then:
///
/// Declare, unless there already exist members with these names:
/// ghost var Repr: set(object)
/// predicate Valid()
///
/// For function/predicate Valid(), insert:
/// reads this, Repr
/// ensures Valid() ==> this in Repr
/// Into body of Valid(), insert (at the beginning of the body):
/// this in Repr && null !in Repr
/// and also insert, for every array-valued field A declared in the class:
/// (A != null ==> A in Repr) &&
/// and for every field F of a class type T where T has a field called Repr, also insert:
/// (F != null ==> F in Repr && F.Repr SUBSET Repr && this !in Repr && F.Valid())
/// Except, if A or F is declared with {:autocontracts false}, then the implication will not
/// be added.
///
/// For every constructor, add:
/// ensures Valid() && fresh(Repr)
/// At the end of the body of the constructor, add:
/// Repr := {this};
/// if (A != null) { Repr := Repr + {A}; }
/// if (F != null) { Repr := Repr + {F} + F.Repr; }
///
/// In all the following cases, no "modifies" clause or "reads" clause is added if the user
/// has given one.
///
/// For every non-static non-ghost method that is not a "simple query method",
/// add:
/// requires Valid()
/// modifies Repr
/// ensures Valid() && fresh(Repr - old(Repr))
/// At the end of the body of the method, add:
/// if (A != null && !(A in Repr)) { Repr := Repr + {A}; }
/// if (F != null && !(F in Repr && F.Repr SUBSET Repr)) { Repr := Repr + {F} + F.Repr; }
/// For every non-static non-twostate method that is either ghost or is a "simple query method",
/// add:
/// requires Valid()
/// For every non-static twostate method, add:
/// requires old(Valid())
///
/// For every non-"Valid" non-static function, add:
/// requires Valid()
/// reads Repr
/// </summary>
public class AutoContractsRewriter : IRewriter
{
readonly BuiltIns builtIns;
public AutoContractsRewriter(ErrorReporter reporter, BuiltIns builtIns)
: base(reporter) {
Contract.Requires(reporter != null);
Contract.Requires(builtIns != null);
this.builtIns = builtIns;
}
internal override void PreResolve(ModuleDefinition m) {
foreach (var d in m.TopLevelDecls) {
bool sayYes = true;
if (d is ClassDecl && Attributes.ContainsBool(d.Attributes, "autocontracts", ref sayYes) && sayYes) {
ProcessClassPreResolve((ClassDecl)d);
}
}
}
void ProcessClassPreResolve(ClassDecl cl) {
// Add: ghost var Repr: set<object>
// ...unless a field with that name is already present
if (!cl.Members.Exists(member => member is Field && member.Name == "Repr")) {
Type ty = new SetType(true, builtIns.ObjectQ());
var repr = new Field(new AutoGeneratedToken(cl.tok), "Repr", true, ty, null);
cl.Members.Add(repr);
AddHoverText(cl.tok, "{0}", Printer.FieldToString(repr));
}
// Add: predicate Valid()
// ...unless an instance function with that name is already present
if (!cl.Members.Exists(member => member is Function && member.Name == "Valid" && !member.IsStatic)) {
var valid = new Predicate(cl.tok, "Valid", false, true, new List<TypeParameter>(), new List<Formal>(),
new List<AttributedExpression>(), new List<FrameExpression>(), new List<AttributedExpression>(), new Specification<Expression>(new List<Expression>(), null),
null, Predicate.BodyOriginKind.OriginalOrInherited, null, null);
cl.Members.Add(valid);
// It will be added to hover text later
}
foreach (var member in cl.Members) {
bool sayYes = true;
if (Attributes.ContainsBool(member.Attributes, "autocontracts", ref sayYes) && !sayYes) {
// the user has excluded this member
continue;
}
if (member.RefinementBase != null) {
// member is inherited from a module where it was already processed
continue;
}
Boogie.IToken tok = new AutoGeneratedToken(member.tok);
if (member is Function && member.Name == "Valid" && !member.IsStatic) {
var valid = (Function)member;
// reads this, Repr
var r0 = new ThisExpr(tok);
var r1 = new MemberSelectExpr(tok, new ImplicitThisExpr(tok), "Repr");
valid.Reads.Add(new FrameExpression(tok, r0, null));
valid.Reads.Add(new FrameExpression(tok, r1, null));
// ensures Valid() ==> this in Repr
var post = new BinaryExpr(tok, BinaryExpr.Opcode.Imp,
new FunctionCallExpr(tok, "Valid", new ImplicitThisExpr(tok), tok, new List<Expression>()),
new BinaryExpr(tok, BinaryExpr.Opcode.In,
new ThisExpr(tok),
new MemberSelectExpr(tok, new ImplicitThisExpr(tok), "Repr")));
valid.Ens.Insert(0, new AttributedExpression(post));
if (member.tok == cl.tok) {
// We added this function above, so produce a hover text for the entire function signature
AddHoverText(cl.tok, "{0}", Printer.FunctionSignatureToString(valid));
} else {
AddHoverText(member.tok, $"reads {r0}, {r1}\nensures {post}");
}
} else if (member is Function && !member.IsStatic) {
var f = (Function)member;
// requires Valid()
var valid = new FunctionCallExpr(tok, "Valid", new ImplicitThisExpr(tok), tok, new List<Expression>());
f.Req.Insert(0, new AttributedExpression(valid));
var format = "requires {0}";
var repr = new MemberSelectExpr(tok, new ImplicitThisExpr(tok), "Repr");
if (f.Reads.Count == 0) {
// reads Repr
f.Reads.Add(new FrameExpression(tok, repr, null));
format += "\nreads {1}";
}
AddHoverText(member.tok, format, valid, repr);
} else if (member is Constructor) {
var ctor = (Constructor)member;
// ensures Valid();
var valid = new FunctionCallExpr(tok, "Valid", new ImplicitThisExpr(tok), tok, new List<Expression>());
ctor.Ens.Insert(0, new AttributedExpression(valid));
// ensures fresh(Repr);
var freshness = new UnaryOpExpr(tok, UnaryOpExpr.Opcode.Fresh,
new MemberSelectExpr(tok, new ImplicitThisExpr(tok), "Repr"));
ctor.Ens.Insert(1, new AttributedExpression(freshness));
var m0 = new ThisExpr(tok);
AddHoverText(member.tok, "modifies {0}\nensures {1} && {2}", m0, valid, freshness);
}
}
}
internal override void PostResolve(ModuleDefinition m) {
foreach (var d in m.TopLevelDecls) {
bool sayYes = true;
if (d is ClassDecl && Attributes.ContainsBool(d.Attributes, "autocontracts", ref sayYes) && sayYes) {
ProcessClassPostResolve((ClassDecl)d);
}
}
}
void ProcessClassPostResolve(ClassDecl cl) {
// Find all fields of a reference type, and make a note of whether or not the reference type has a Repr field.
// Also, find the Repr field and the function Valid in class "cl"
Field ReprField = null;
Function Valid = null;
var subobjects = new List<Tuple<Field, Field, Function>>();
foreach (var member in cl.Members) {
var field = member as Field;
if (field != null) {
bool sayYes = true;
if (field.Name == "Repr") {
ReprField = field;
} else if (Attributes.ContainsBool(field.Attributes, "autocontracts", ref sayYes) && !sayYes) {
// ignore this field
} else if (field.Type.IsRefType) {
var rcl = (ClassDecl)((UserDefinedType)field.Type.NormalizeExpand()).ResolvedClass;
Field rRepr = null;
Function rValid = null;
foreach (var memb in rcl.Members) {
if (memb is Field && memb.Name == "Repr") {
var f = (Field)memb;
var t = f.Type.AsSetType;
if (t != null && t.Arg.IsObjectQ) {
rRepr = f;
}
} else if (memb is Function && memb.Name == "Valid" && !memb.IsStatic) {
var f = (Function)memb;
if (f.Formals.Count == 0 && f.ResultType.IsBoolType) {
rValid = f;
}
}
if (rRepr != null && rValid != null) {
break;
}
}
subobjects.Add(new Tuple<Field, Field, Function>(field, rRepr, rValid));
}
} else if (member is Function && member.Name == "Valid" && !member.IsStatic) {
var fn = (Function)member;
if (fn.Formals.Count == 0 && fn.ResultType.IsBoolType) {
Valid = fn;
}
}
}
Contract.Assert(ReprField != null); // we expect there to be a "Repr" field, since we added one in PreResolve
Boogie.IToken clTok = new AutoGeneratedToken(cl.tok);
Type ty = Resolver.GetThisType(clTok, cl);
var self = new ThisExpr(clTok);
self.Type = ty;
var implicitSelf = new ImplicitThisExpr(clTok);
implicitSelf.Type = ty;
var Repr = new MemberSelectExpr(clTok, implicitSelf, ReprField);
foreach (var member in cl.Members) {
bool sayYes = true;
if (Attributes.ContainsBool(member.Attributes, "autocontracts", ref sayYes) && !sayYes) {
continue;
}
Boogie.IToken tok = new AutoGeneratedToken(member.tok);
if (member is Function && member.Name == "Valid" && !member.IsStatic) {
var valid = (Function)member;
var validConjuncts = new List<Expression>();
if (valid.IsGhost && valid.ResultType.IsBoolType) {
if (valid.RefinementBase == null) {
var c0 = BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.InSet, self, Repr); // this in Repr
var c1 = BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.NotInSet, new LiteralExpr(tok) { Type = builtIns.ObjectQ() }, Repr); // null !in Repr
var c = BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.And, c0, c1);
validConjuncts.Add(c);
}
foreach (var ff in subobjects) {
if (ff.Item1.RefinementBase != null) {
// the field has been inherited from a refined module, so don't include it here
continue;
}
var F = new MemberSelectExpr(tok, implicitSelf, ff.Item1);
var c0 = IsNotNull(tok, F);
var c1 = BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.InSet, F, Repr);
if (ff.Item2 == null) {
// F != null ==> F in Repr (so, nothing else to do)
} else {
// F != null ==> F in Repr && F.Repr <= Repr && this !in F.Repr && F.Valid()
var FRepr = new MemberSelectExpr(tok, F, ff.Item2);
var c2 = BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.Subset, FRepr, Repr);
var c3 = BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.NotInSet, self, FRepr);
c1 = BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.And, c1,
BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.And, c2, c3));
if (ff.Item3 != null) {
// F.Valid()
c1 = BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.And, c1,
ValidCall(tok, F, ff.Item3, valid));
}
}
validConjuncts.Add(Expression.CreateImplies(c0, c1));
}
var hoverText = "";
var sep = "";
if (valid.Body == null) {
valid.Body = Expression.CreateBoolLiteral(tok, true);
if (validConjuncts.Count == 0) {
hoverText = "true";
sep = "\n";
}
}
for (int i = validConjuncts.Count; 0 <= --i; ) {
var c = validConjuncts[i];
valid.Body = BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.And, c, valid.Body);
hoverText = Printer.ExprToString(c) + sep + hoverText;
sep = "\n";
}
AddHoverText(valid.tok, "{0}", hoverText);
}
} else if (member is Constructor) {
var ctor = (Constructor)member;
if (ctor.Body != null) {
var sbs = (DividedBlockStmt)ctor.Body;
var n = sbs.Body.Count;
if (ctor.RefinementBase == null) {
// Repr := {this};
var e = new SetDisplayExpr(tok, true, new List<Expression>() { self });
e.Type = new SetType(true, builtIns.ObjectQ());
Statement s = new AssignStmt(tok, tok, Repr, new ExprRhs(e));
s.IsGhost = true;
sbs.AppendStmt(s);
}
AddSubobjectReprs(tok, ctor.BodyEndTok, subobjects, sbs, n, implicitSelf, Repr);
}
} else if (member is Method && !member.IsStatic && Valid != null) {
var m = (Method)member;
var addStatementsToUpdateRepr = false;
if (member.IsGhost || IsSimpleQueryMethod(m)) {
if (m.RefinementBase == null) {
// requires Valid()
var valid = ValidCall(tok, implicitSelf, Valid, m);
if (m is TwoStateLemma) {
// Instead use: requires old(Valid())
valid = new OldExpr(tok, valid);
valid.Type = Type.Bool;
}
m.Req.Insert(0, new AttributedExpression(valid));
AddHoverText(member.tok, "requires {0}", valid);
}
} else if (m.RefinementBase == null) {
// requires Valid()
var valid = ValidCall(tok, implicitSelf, Valid, m);
m.Req.Insert(0, new AttributedExpression(valid));
var format = "requires {0}";
if (m.Mod.Expressions.Count == 0) {
// modifies Repr
m.Mod.Expressions.Add(new FrameExpression(Repr.tok, Repr, null));
format += "\nmodifies {1}";
addStatementsToUpdateRepr = true;
}
// ensures Valid()
m.Ens.Insert(0, new AttributedExpression(valid));
// ensures fresh(Repr - old(Repr));
var e0 = new OldExpr(tok, Repr);
e0.Type = Repr.Type;
var e1 = new BinaryExpr(tok, BinaryExpr.Opcode.Sub, Repr, e0);
e1.ResolvedOp = BinaryExpr.ResolvedOpcode.SetDifference;
e1.Type = Repr.Type;
var freshness = new UnaryOpExpr(tok, UnaryOpExpr.Opcode.Fresh, e1);
freshness.Type = Type.Bool;
m.Ens.Insert(1, new AttributedExpression(freshness));
AddHoverText(m.tok, format + "\nensures {0} && {2}", valid, Repr, freshness);
} else {
addStatementsToUpdateRepr = true;
}
if (addStatementsToUpdateRepr && m.Body != null) {
var methodBody = (BlockStmt)m.Body;
AddSubobjectReprs(tok, methodBody.EndTok, subobjects, methodBody, methodBody.Body.Count, implicitSelf, Repr);
}
}
}
}
void AddSubobjectReprs(IToken tok, IToken endCurlyTok, List<Tuple<Field, Field, Function>> subobjects, BlockStmt block, int hoverTextFromHere,
Expression implicitSelf, Expression Repr) {
Contract.Requires(tok != null);
Contract.Requires(endCurlyTok != null);
Contract.Requires(subobjects != null);
Contract.Requires(block != null);
Contract.Requires(0 <= hoverTextFromHere && hoverTextFromHere <= block.Body.Count);
Contract.Requires(implicitSelf != null);
Contract.Requires(Repr != null);
// TODO: these assignments should be included on every return path
foreach (var ff in subobjects) {
var F = new MemberSelectExpr(tok, implicitSelf, ff.Item1); // create a resolved MemberSelectExpr
Expression e = new SetDisplayExpr(tok, true, new List<Expression>() { F }) {
Type = new SetType(true, builtIns.ObjectQ()) // resolve here
};
var rhs = new BinaryExpr(tok, BinaryExpr.Opcode.Add, Repr, e) {
ResolvedOp = BinaryExpr.ResolvedOpcode.Union,
Type = Repr.Type
};
Expression nguard = BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.InSet, F, Repr); // F in Repr
if (ff.Item2 == null) {
// Repr := Repr + {F} (so, nothing else to do)
} else {
// Repr := Repr + {F} + F.Repr
var FRepr = new MemberSelectExpr(tok, F, ff.Item2); // create resolved MemberSelectExpr
rhs = new BinaryExpr(tok, BinaryExpr.Opcode.Add, rhs, FRepr) {
ResolvedOp = BinaryExpr.ResolvedOpcode.Union,
Type = Repr.Type
};
var ng = BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.Subset, FRepr, Repr); // F.Repr <= Repr
nguard = Expression.CreateAnd(nguard, ng);
}
// Repr := Repr + ...;
Statement s = new AssignStmt(tok, tok, Repr, new ExprRhs(rhs));
s.IsGhost = true;
// wrap if statement around s
e = Expression.CreateAnd(IsNotNull(tok, F), Expression.CreateNot(tok, nguard));
var thn = new BlockStmt(tok, tok, new List<Statement>() { s });
thn.IsGhost = true;
s = new IfStmt(tok, tok, false, e, thn, null);
s.IsGhost = true;
// finally, add s to the block
block.AppendStmt(s);
}
if (hoverTextFromHere != block.Body.Count) {
var hoverText = "";
var sep = "";
for (int i = hoverTextFromHere; i < block.Body.Count; i++) {
hoverText += sep + Printer.StatementToString(block.Body[i]);
sep = "\n";
}
AddHoverText(endCurlyTok, "{0}", hoverText);
}
}
/// <summary>
/// Returns an expression denoting "expr != null". If the type
/// of "expr" already implies "expr" is non-null, then an expression
/// denoting "true" is returned.
/// </summary>
Expression IsNotNull(IToken tok, Expression expr) {
Contract.Requires(tok != null);
Contract.Requires(expr != null);
if (expr.Type.IsNonNullRefType) {
return Expression.CreateBoolLiteral(tok, true);
} else {
var cNull = new LiteralExpr(tok);
cNull.Type = expr.Type;
return BinBoolExpr(tok, BinaryExpr.ResolvedOpcode.NeqCommon, expr, cNull);
}
}
bool IsSimpleQueryMethod(Method m) {
// A simple query method has out parameters, its body has no effect other than to assign to them,
// and the postcondition does not explicitly mention the pre-state.
return m.Outs.Count != 0 && m.Body != null && LocalAssignsOnly(m.Body) &&
m.Ens.TrueForAll(mfe => !MentionsOldState(mfe.E));
}
bool LocalAssignsOnly(Statement s) {
Contract.Requires(s != null);
if (s is AssignStmt) {
var ss = (AssignStmt)s;
return ss.Lhs.Resolved is IdentifierExpr;
} else if (s is ConcreteUpdateStatement) {
var ss = (ConcreteUpdateStatement)s;
return ss.Lhss.TrueForAll(e => e.Resolved is IdentifierExpr);
} else if (s is CallStmt) {
return false;
} else {
foreach (var ss in s.SubStatements) {
if (!LocalAssignsOnly(ss)) {
return false;
}
}
}
return true;
}
/// <summary>
/// Returns true iff 'expr' is a two-state expression, that is, if it mentions "old/fresh/unchanged(...)".
/// </summary>
static bool MentionsOldState(Expression expr) {
Contract.Requires(expr != null);
if (expr is OldExpr || expr is UnchangedExpr) {
return true;
} else if (expr is UnaryOpExpr && ((UnaryOpExpr)expr).Op == UnaryOpExpr.Opcode.Fresh) {
return true;
}
foreach (var ee in expr.SubExpressions) {
if (MentionsOldState(ee)) {
return true;
}
}
return false;
}
/// <summary>
/// Returns a resolved expression of the form "receiver.Valid()"
/// </summary>
public static Expression ValidCall(IToken tok, Expression receiver, Function Valid, ICallable callingContext) {
Contract.Requires(tok != null);
Contract.Requires(receiver != null);
Contract.Requires(Valid != null);
Contract.Requires(callingContext != null);
Contract.Requires(receiver.Type.NormalizeExpand() is UserDefinedType && ((UserDefinedType)receiver.Type.NormalizeExpand()).ResolvedClass == Valid.EnclosingClass);
Contract.Requires(receiver.Type.NormalizeExpand().TypeArgs.Count == Valid.EnclosingClass.TypeArgs.Count);
var call = new FunctionCallExpr(tok, Valid.Name, receiver, tok, new List<Expression>());
call.Function = Valid;
call.Type = Type.Bool;
call.TypeApplication_AtEnclosingClass = receiver.Type.TypeArgs;
call.TypeApplication_JustFunction = new List<Type>();
callingContext.EnclosingModule.CallGraph.AddEdge((ICallable)CodeContextWrapper.Unwrap(callingContext), Valid);
return call;
}
public static BinaryExpr BinBoolExpr(Boogie.IToken tok, BinaryExpr.ResolvedOpcode rop, Expression e0, Expression e1) {
var p = new BinaryExpr(tok, BinaryExpr.ResolvedOp2SyntacticOp(rop), e0, e1);
p.ResolvedOp = rop; // resolve here
p.Type = Type.Bool; // resolve here
return p;
}
void AddHoverText(IToken tok, string format, params object[] args) {
Contract.Requires(tok != null);
Contract.Requires(format != null);
Contract.Requires(args != null);
for (int i = 0; i < args.Length; i++) {
if (args[i] is Expression) {
args[i] = Printer.ExprToString((Expression)args[i]);
}
}
var s = "autocontracts:\n" + string.Format(format, args);
reporter.Info(MessageSource.Rewriter, tok, s.Replace("\n", "\n "));
}
}
/// <summary>
/// For any function foo() with the :opaque attribute,
/// hide the body, so that it can only be seen within its
/// recursive clique (if any), or if the programmer
/// specifically asks to see it via the reveal_foo() lemma
/// </summary>
public class OpaqueFunctionRewriter : IRewriter {
protected Dictionary<Function, Function> fullVersion; // Given an opaque function, retrieve the full
protected Dictionary<Function, Function> original; // Given a full version of an opaque function, find the original opaque version
protected Dictionary<Method, Function> revealOriginal; // Map reveal_* lemmas (or two-state lemmas) back to their original functions
public OpaqueFunctionRewriter(ErrorReporter reporter)
: base(reporter) {
Contract.Requires(reporter != null);
fullVersion = new Dictionary<Function, Function>();
original = new Dictionary<Function, Function>();
revealOriginal = new Dictionary<Method, Function>();
}
internal override void PreResolve(ModuleDefinition m) {
foreach (var d in m.TopLevelDecls) {
if (d is TopLevelDeclWithMembers) {
ProcessOpaqueClassFunctions((TopLevelDeclWithMembers)d);
}
}
}
internal override void PostResolve(ModuleDefinition m) {
foreach (var decl in ModuleDefinition.AllCallables(m.TopLevelDecls)) {
if (decl is Lemma || decl is TwoStateLemma) {
var lem = (Method)decl;
if (revealOriginal.ContainsKey(lem)) {
Function fn = revealOriginal[lem];
AnnotateRevealFunction(lem, fn);
}
}
}
}
protected void AnnotateRevealFunction(Method lemma, Function f) {
Contract.Requires(lemma is Lemma || lemma is TwoStateLemma);
Expression receiver;
if (f.IsStatic) {
receiver = new StaticReceiverExpr(f.tok, (TopLevelDeclWithMembers)f.EnclosingClass, true);
} else {
receiver = new ImplicitThisExpr(f.tok);
//receiver.Type = GetThisType(expr.tok, (TopLevelDeclWithMembers)member.EnclosingClass); // resolve here
}
var typeApplication = new List<Type>();
var typeApplication_JustForMember = new List<Type>();
for (int i = 0; i < f.TypeArgs.Count; i++) {
// doesn't matter what type, just so we have it to make the resolver happy when resolving function member of
// the fuel attribute. This might not be needed after fixing codeplex issue #172.
typeApplication.Add(new IntType());
typeApplication_JustForMember.Add(new IntType());
}
var nameSegment = new NameSegment(f.tok, f.Name, f.TypeArgs.Count == 0 ? null : typeApplication);
var rr = new MemberSelectExpr(f.tok, receiver, f.Name);
rr.Member = f;
rr.TypeApplication_AtEnclosingClass = typeApplication;
rr.TypeApplication_JustMember = typeApplication_JustForMember;
List<Type> args = new List<Type>();
for (int i = 0; i < f.Formals.Count; i++) {
args.Add(new IntType());
}
rr.Type = new ArrowType(f.tok, args, new IntType());
nameSegment.ResolvedExpression = rr;
nameSegment.Type = rr.Type;
LiteralExpr low = new LiteralExpr(f.tok, 1);
LiteralExpr hi = new LiteralExpr(f.tok, 2);
lemma.Attributes = new Attributes("fuel", new List<Expression>() { nameSegment, low, hi }, lemma.Attributes);
}
// Tells the function to use 0 fuel by default
protected void ProcessOpaqueClassFunctions(TopLevelDeclWithMembers c) {
Contract.Requires(c != null);
List<MemberDecl> newDecls = new List<MemberDecl>();
foreach (MemberDecl member in c.Members) {
if (member is Function) {
var f = (Function)member;
if (!Attributes.Contains(f.Attributes, "opaque")) {
// Nothing to do
} else if (!RefinementToken.IsInherited(f.tok, c.EnclosingModuleDefinition)) {
RewriteOpaqueFunctionUseFuel(f, newDecls);
}
}
}
c.Members.AddRange(newDecls);
}
private void RewriteOpaqueFunctionUseFuel(Function f, List<MemberDecl> newDecls) {
// mark the opaque function with {:fuel, 0, 0}
LiteralExpr amount = new LiteralExpr(f.tok, 0);
f.Attributes = new Attributes("fuel", new List<Expression>() { amount, amount }, f.Attributes);
// That is, given:
// function {:opaque} foo(x:int, y:int) : int
// requires 0 <= x < 5;
// requires 0 <= y < 5;
// ensures foo(x, y) < 10;
// { x + y }
// We produce:
// lemma {:axiom} {:auto_generated} {:fuel foo, 1, 2 } reveal_foo()
//
// If "foo" is a two-state function, then "reveal_foo" will be declared as a two-state lemma.
//
// The translator, in AddMethod, then adds ensures clauses to bump up the fuel parameters appropriately
var cloner = new Cloner();
List<TypeParameter> typeVars = new List<TypeParameter>();
List<Type> optTypeArgs = new List<Type>();
foreach (TypeParameter tp in f.TypeArgs) {
typeVars.Add(cloner.CloneTypeParam(tp));
// doesn't matter what type, just so we have it to make the resolver happy when resolving function member of
// the fuel attribute. This might not be needed after fixing codeplex issue #172.
optTypeArgs.Add(new IntType());
}
// Add an axiom attribute so that the compiler won't complain about the lemma's lack of a body
Attributes lemma_attrs = BuiltIns.AxiomAttribute();
lemma_attrs = new Attributes("auto_generated", new List<Expression>(), lemma_attrs);
lemma_attrs = new Attributes("opaque_reveal", new List<Expression>(), lemma_attrs);
lemma_attrs = new Attributes("verify", new List<Expression>() { new LiteralExpr(f.tok, false)}, lemma_attrs);
Method reveal;
if (f is TwoStateFunction) {
reveal = new TwoStateLemma(f.tok, "reveal_" + f.Name, f.HasStaticKeyword, new List<TypeParameter>(), new List<Formal>(), new List<Formal>(), new List<AttributedExpression>(),
new Specification<FrameExpression>(new List<FrameExpression>(), null), /* newEnsuresList*/new List<AttributedExpression>(),
new Specification<Expression>(new List<Expression>(), null), null, lemma_attrs, null);
} else {
reveal = new Lemma(f.tok, "reveal_" + f.Name, f.HasStaticKeyword, new List<TypeParameter>(), new List<Formal>(), new List<Formal>(), new List<AttributedExpression>(),
new Specification<FrameExpression>(new List<FrameExpression>(), null), /* newEnsuresList*/new List<AttributedExpression>(),
new Specification<Expression>(new List<Expression>(), null), null, lemma_attrs, null);
}
newDecls.Add(reveal);
revealOriginal[reveal] = f;
reveal.InheritVisibility(f, true);
}
class OpaqueFunctionVisitor : TopDownVisitor<bool> {
protected override bool VisitOneExpr(Expression expr, ref bool context) {
return true;
}
}
}
/// <summary>
/// Automatically accumulate requires for function calls within a function body,
/// if requested via {:autoreq}
/// </summary>
public class AutoReqFunctionRewriter : IRewriter {
Function parentFunction;
bool containsMatch; // TODO: Track this per-requirement, rather than per-function
public AutoReqFunctionRewriter(ErrorReporter reporter)
: base(reporter) {
Contract.Requires(reporter != null);
}
internal override void PostResolve(ModuleDefinition m) {
var components = m.CallGraph.TopologicallySortedComponents();
foreach (var scComponent in components) { // Visit the call graph bottom up, so anything we call already has its prequisites calculated
if (scComponent is Function) {
Function fn = (Function)scComponent;
if (Attributes.ContainsBoolAtAnyLevel(fn, "autoReq")) {
parentFunction = fn; // Remember where the recursion started
containsMatch = false; // Assume no match statements are involved
List<AttributedExpression> auto_reqs = new List<AttributedExpression>();
// First handle all of the requirements' preconditions
foreach (AttributedExpression req in fn.Req) {
foreach (Expression e in generateAutoReqs(req.E)) {
auto_reqs.Add(new AttributedExpression(e, req.Attributes));
}
}
fn.Req.InsertRange(0, auto_reqs); // Need to come before the actual requires
addAutoReqToolTipInfoToFunction("pre", fn, auto_reqs);
// Then the body itself, if any
if (fn.Body != null) {
auto_reqs = new List<AttributedExpression>();
foreach (Expression e in generateAutoReqs(fn.Body)) {
auto_reqs.Add(new AttributedExpression(e));
}
fn.Req.AddRange(auto_reqs);
addAutoReqToolTipInfoToFunction("post", fn, auto_reqs);
}
}
}
else if (scComponent is Method)
{
Method method = (Method)scComponent;
if (Attributes.ContainsBoolAtAnyLevel(method, "autoReq"))
{
parentFunction = null;
containsMatch = false; // Assume no match statements are involved
List<AttributedExpression> auto_reqs = new List<AttributedExpression>();
foreach (AttributedExpression req in method.Req)
{
List<Expression> local_auto_reqs = generateAutoReqs(req.E);
foreach (Expression local_auto_req in local_auto_reqs)
{
auto_reqs.Add(new AttributedExpression(local_auto_req));
}
}
method.Req.InsertRange(0, auto_reqs); // Need to come before the actual requires
addAutoReqToolTipInfoToMethod("pre", method, auto_reqs);
}
}
}
}
Expression subVars(List<Formal> formals, List<Expression> values, Expression e, Expression f_this) {
Contract.Assert(formals != null);
Contract.Assert(values != null);
Contract.Assert(formals.Count == values.Count);
Dictionary<IVariable, Expression/*!*/> substMap = new Dictionary<IVariable, Expression>();
Dictionary<TypeParameter, Type> typeMap = new Dictionary<TypeParameter, Type>();
for (int i = 0; i < formals.Count; i++) {
substMap.Add(formals[i], values[i]);
}
Translator.Substituter sub = new Translator.Substituter(f_this, substMap, typeMap);
return sub.Substitute(e);
}
public void addAutoReqToolTipInfoToFunction(string label, Function f, List<AttributedExpression> reqs) {
string prefix = "auto requires " + label + " ";
string tip = "";
string sep = "";
foreach (var req in reqs) {
if (containsMatch) { // Pretty print the requirements
tip += sep + prefix + Printer.ExtendedExprToString(req.E) + ";";
} else {
tip += sep + prefix + Printer.ExprToString(req.E) + ";";
}
sep = "\n";
}
if (!tip.Equals("")) {
reporter.Info(MessageSource.Rewriter, f.tok, tip);
if (DafnyOptions.O.AutoReqPrintFile != null) {
using (System.IO.TextWriter writer = new System.IO.StreamWriter(DafnyOptions.O.AutoReqPrintFile, true)) {
writer.WriteLine(f.Name);
writer.WriteLine("\t" + tip);
}
}
}
}
public void addAutoReqToolTipInfoToMethod(string label, Method method, List<AttributedExpression> reqs) {
string tip = "";
foreach (var req in reqs) {
string prefix = "auto ";
prefix += " requires " + label + " ";
if (containsMatch) { // Pretty print the requirements
tip += prefix + Printer.ExtendedExprToString(req.E) + ";\n";
} else {
tip += prefix + Printer.ExprToString(req.E) + ";\n";
}
}
if (!tip.Equals("")) {
reporter.Info(MessageSource.Rewriter, method.tok, tip);
if (DafnyOptions.O.AutoReqPrintFile != null) {
using (System.IO.TextWriter writer = new System.IO.StreamWriter(DafnyOptions.O.AutoReqPrintFile, true)) {
writer.WriteLine(method.Name);
writer.WriteLine("\t" + tip);
}
}
}
}
// Stitch a list of expressions together with logical ands
Expression andify(Bpl.IToken tok, List<Expression> exprs) {
Expression ret = Expression.CreateBoolLiteral(tok, true);
foreach (var expr in exprs) {
ret = Expression.CreateAnd(ret, expr);
}
return ret;
}
List<Expression> gatherReqs(Function f, List<Expression> args, Expression f_this) {
List<Expression> translated_f_reqs = new List<Expression>();
if (f.Req.Count > 0) {
Dictionary<IVariable, Expression/*!*/> substMap = new Dictionary<IVariable,Expression>();
Dictionary<TypeParameter, Type> typeMap = new Dictionary<TypeParameter,Type>();
for (int i = 0; i < f.Formals.Count; i++) {
substMap.Add(f.Formals[i], args[i]);
}
foreach (var req in f.Req) {
Translator.Substituter sub = new Translator.Substituter(f_this, substMap, typeMap);
translated_f_reqs.Add(sub.Substitute(req.E));
}
}
return translated_f_reqs;
}
List<Expression> generateAutoReqs(Expression expr) {
List<Expression> reqs = new List<Expression>();
if (expr is LiteralExpr) {
} else if (expr is ThisExpr) {
} else if (expr is IdentifierExpr) {
} else if (expr is SetDisplayExpr) {
SetDisplayExpr e = (SetDisplayExpr)expr;
foreach (var elt in e.Elements) {
reqs.AddRange(generateAutoReqs(elt));
}
} else if (expr is MultiSetDisplayExpr) {
MultiSetDisplayExpr e = (MultiSetDisplayExpr)expr;
foreach (var elt in e.Elements) {
reqs.AddRange(generateAutoReqs(elt));
}
} else if (expr is SeqDisplayExpr) {
SeqDisplayExpr e = (SeqDisplayExpr)expr;
foreach (var elt in e.Elements) {
reqs.AddRange(generateAutoReqs(elt));
}
} else if (expr is MapDisplayExpr) {
MapDisplayExpr e = (MapDisplayExpr)expr;
foreach (ExpressionPair p in e.Elements) {
reqs.AddRange(generateAutoReqs(p.A));
reqs.AddRange(generateAutoReqs(p.B));
}
} else if (expr is MemberSelectExpr) {
MemberSelectExpr e = (MemberSelectExpr)expr;
Contract.Assert(e.Member != null && e.Member is Field);
reqs.AddRange(generateAutoReqs(e.Obj));
} else if (expr is SeqSelectExpr) {
SeqSelectExpr e = (SeqSelectExpr)expr;
reqs.AddRange(generateAutoReqs(e.Seq));
if (e.E0 != null) {
reqs.AddRange(generateAutoReqs(e.E0));
}
if (e.E1 != null) {
reqs.AddRange(generateAutoReqs(e.E1));
}
} else if (expr is SeqUpdateExpr) {
SeqUpdateExpr e = (SeqUpdateExpr)expr;
reqs.AddRange(generateAutoReqs(e.Seq));
reqs.AddRange(generateAutoReqs(e.Index));
reqs.AddRange(generateAutoReqs(e.Value));
} else if (expr is DatatypeUpdateExpr) {
foreach (var ee in expr.SubExpressions) {
reqs.AddRange(generateAutoReqs(ee));
}
} else if (expr is FunctionCallExpr) {
FunctionCallExpr e = (FunctionCallExpr)expr;
// All of the arguments need to be satisfied
foreach (var arg in e.Args) {
reqs.AddRange(generateAutoReqs(arg));
}
if (parentFunction != null && ModuleDefinition.InSameSCC(e.Function, parentFunction)) {
// We're making a call within the same SCC, so don't descend into this function
} else {
reqs.AddRange(gatherReqs(e.Function, e.Args, e.Receiver));
}
} else if (expr is DatatypeValue) {
DatatypeValue dtv = (DatatypeValue)expr;
Contract.Assert(dtv.Ctor != null); // since dtv has been successfully resolved
for (int i = 0; i < dtv.Arguments.Count; i++) {
Expression arg = dtv.Arguments[i];
reqs.AddRange(generateAutoReqs(arg));
}
} else if (expr is OldExpr) {
} else if (expr is MatchExpr) {
MatchExpr e = (MatchExpr)expr;
containsMatch = true;
reqs.AddRange(generateAutoReqs(e.Source));
List<MatchCaseExpr> newMatches = new List<MatchCaseExpr>();
foreach (MatchCaseExpr caseExpr in e.Cases) {
//MatchCaseExpr c = new MatchCaseExpr(caseExpr.tok, caseExpr.Id, caseExpr.Arguments, andify(caseExpr.tok, generateAutoReqs(caseExpr.Body)));
//c.Ctor = caseExpr.Ctor; // resolve here
MatchCaseExpr c = Expression.CreateMatchCase(caseExpr, andify(caseExpr.tok, generateAutoReqs(caseExpr.Body)));
newMatches.Add(c);
}
reqs.Add(Expression.CreateMatch(e.tok, e.Source, newMatches, e.Type));
} else if (expr is SeqConstructionExpr) {
var e = (SeqConstructionExpr)expr;
reqs.AddRange(generateAutoReqs(e.N));
reqs.AddRange(generateAutoReqs(e.Initializer));
} else if (expr is MultiSetFormingExpr) {
MultiSetFormingExpr e = (MultiSetFormingExpr)expr;
reqs.AddRange(generateAutoReqs(e.E));
} else if (expr is UnaryExpr) {
UnaryExpr e = (UnaryExpr)expr;
Expression arg = e.E;
reqs.AddRange(generateAutoReqs(arg));
} else if (expr is BinaryExpr) {
BinaryExpr e = (BinaryExpr)expr;
switch (e.ResolvedOp) {
case BinaryExpr.ResolvedOpcode.Imp:
case BinaryExpr.ResolvedOpcode.And:
reqs.AddRange(generateAutoReqs(e.E0));
foreach (var req in generateAutoReqs(e.E1)) {
// We only care about this req if E0 is true, since And short-circuits
reqs.Add(Expression.CreateImplies(e.E0, req));
}
break;
case BinaryExpr.ResolvedOpcode.Or:
reqs.AddRange(generateAutoReqs(e.E0));
foreach (var req in generateAutoReqs(e.E1)) {
// We only care about this req if E0 is false, since Or short-circuits
reqs.Add(Expression.CreateImplies(Expression.CreateNot(e.E1.tok, e.E0), req));
}
break;
default:
reqs.AddRange(generateAutoReqs(e.E0));
reqs.AddRange(generateAutoReqs(e.E1));
break;
}
} else if (expr is TernaryExpr) {
var e = (TernaryExpr)expr;
reqs.AddRange(generateAutoReqs(e.E0));
reqs.AddRange(generateAutoReqs(e.E1));
reqs.AddRange(generateAutoReqs(e.E2));
} else if (expr is LetExpr) {
var e = (LetExpr)expr;
if (e.Exact) {
foreach (var rhs in e.RHSs) {
reqs.AddRange(generateAutoReqs(rhs));
}
var new_reqs = generateAutoReqs(e.Body);
if (new_reqs.Count > 0) {
reqs.Add(Expression.CreateLet(e.tok, e.LHSs, e.RHSs, andify(e.tok, new_reqs), e.Exact));
}
} else {
// TODO: Still need to figure out what the right choice is here:
// Given: var x :| g(x); f(x, y) do we:
// 1) Update the original statement to be: var x :| g(x) && WP(f(x,y)); f(x, y)
// 2) Add forall x :: g(x) ==> WP(f(x, y)) to the function's requirements
// 3) Current option -- do nothing. Up to the spec writer to fix
}
} else if (expr is QuantifierExpr) {
QuantifierExpr e = (QuantifierExpr)expr;
// See LetExpr for issues with the e.Range
var auto_reqs = generateAutoReqs(e.Term);
if (auto_reqs.Count > 0) {
Expression allReqsSatisfied = andify(e.Term.tok, auto_reqs);
Expression allReqsSatisfiedAndTerm = Expression.CreateAnd(allReqsSatisfied, e.Term);
e.UpdateTerm(allReqsSatisfiedAndTerm);
reporter.Info(MessageSource.Rewriter, e.tok, "autoreq added (" + Printer.ExtendedExprToString(allReqsSatisfied) + ") &&");
}
} else if (expr is SetComprehension) {
var e = (SetComprehension)expr;
// Translate "set xs | R :: T"
// See LetExpr for issues with the e.Range
//reqs.AddRange(generateAutoReqs(e.Range));
var auto_reqs = generateAutoReqs(e.Term);
if (auto_reqs.Count > 0) {
reqs.Add(Expression.CreateQuantifier(new ForallExpr(e.tok, new List<TypeParameter>(), e.BoundVars, e.Range, andify(e.Term.tok, auto_reqs), e.Attributes), true));
}
} else if (expr is MapComprehension) {
var e = (MapComprehension)expr;
// Translate "map x | R :: T" into
// See LetExpr for issues with the e.Range
//reqs.AddRange(generateAutoReqs(e.Range));
var auto_reqs = new List<Expression>();
if (e.TermLeft != null) {
auto_reqs.AddRange(generateAutoReqs(e.TermLeft));
}
auto_reqs.AddRange(generateAutoReqs(e.Term));
if (auto_reqs.Count > 0) {
reqs.Add(Expression.CreateQuantifier(new ForallExpr(e.tok, new List<TypeParameter>(), e.BoundVars, e.Range, andify(e.Term.tok, auto_reqs), e.Attributes), true));
}
} else if (expr is StmtExpr) {
var e = (StmtExpr)expr;
reqs.AddRange(generateAutoReqs(e.E));
} else if (expr is ITEExpr) {
ITEExpr e = (ITEExpr)expr;
reqs.AddRange(generateAutoReqs(e.Test));
reqs.Add(Expression.CreateITE(e.Test, andify(e.Thn.tok, generateAutoReqs(e.Thn)), andify(e.Els.tok, generateAutoReqs(e.Els))));
} else if (expr is NestedMatchExpr) {
// Generate autoReq on e.ResolvedExpression, but also on the unresolved body in case something (e.g. another cloner) clears the resolved expression
var e = (NestedMatchExpr)expr;
var autoReqs = generateAutoReqs(e.ResolvedExpression);
var newMatch = new NestedMatchExpr(e.tok, e.Source, e.Cases, e.UsesOptionalBraces);
newMatch.ResolvedExpression = andify(e.tok, autoReqs);
reqs.Add(newMatch);
} else if (expr is ConcreteSyntaxExpression) {
var e = (ConcreteSyntaxExpression)expr;
reqs.AddRange(generateAutoReqs(e.ResolvedExpression));
} else {
//Contract.Assert(false); throw new cce.UnreachableException(); // unexpected expression
}
return reqs;
}
}
public class ProvideRevealAllRewriter : IRewriter {
public ProvideRevealAllRewriter(ErrorReporter reporter)
: base(reporter) {
Contract.Requires(reporter != null);
}
internal override void PreResolve(ModuleDefinition m) {
var declarations = m.TopLevelDecls;
foreach (var d in declarations) {
if (d is ModuleExportDecl me) {
var revealAll = me.RevealAll || DafnyOptions.O.DisableScopes;
HashSet<string> explicitlyRevealedTopLevelIDs = null;
if (!revealAll) {
explicitlyRevealedTopLevelIDs = new HashSet<string>();
foreach (var esig in me.Exports) {
if (esig.ClassId == null && !esig.Opaque) {
explicitlyRevealedTopLevelIDs.Add(esig.Id);
}
}
}
if (revealAll || me.ProvideAll) {
foreach (var newt in declarations) {
if (!newt.CanBeExported()) {
continue;
}
if (!(newt is DefaultClassDecl)) {
me.Exports.Add(new ExportSignature(newt.tok, newt.Name, !revealAll || !newt.CanBeRevealed()));
}
if (newt is TopLevelDeclWithMembers) {
var cl = (TopLevelDeclWithMembers)newt;
var newtIsRevealed = revealAll || explicitlyRevealedTopLevelIDs.Contains(newt.Name);
foreach (var mem in cl.Members) {
var opaque = !revealAll || !mem.CanBeRevealed();
if (newt is DefaultClassDecl) {
// add everything from the default class
me.Exports.Add(new ExportSignature(mem.tok, mem.Name, opaque));
} else if (mem is Constructor && !newtIsRevealed) {
// "provides *" does not pick up class constructors, unless the class is to be revealed
} else if (opaque && mem is Field field && !(mem is ConstantField) && !newtIsRevealed) {
// "provides *" does not pick up mutable fields, unless the class is to be revealed
} else {
me.Exports.Add(new ExportSignature(cl.tok, cl.Name, mem.tok, mem.Name, opaque));
}
}
}
}
}
}
}
}
}
/// <summary>
/// Replace all occurrences of attribute {:timeLimitMultiplier X} with {:timeLimit Y}
/// where Y = X*default-time-limit or Y = X*command-line-time-limit
/// </summary>
public class TimeLimitRewriter : IRewriter
{
public TimeLimitRewriter(ErrorReporter reporter)
: base(reporter) {
Contract.Requires(reporter != null);
}
internal override void PreResolve(ModuleDefinition m) {
foreach (var d in m.TopLevelDecls) {
if (d is ClassDecl) {
var c = (ClassDecl)d;
foreach (MemberDecl member in c.Members) {
if (member is Function || member is Method) {
// Check for the timeLimitMultiplier attribute
if (Attributes.Contains(member.Attributes, "timeLimitMultiplier")) {
Attributes attrs = member.Attributes;
foreach (var attr in attrs.AsEnumerable()) {
if (attr.Name == "timeLimitMultiplier") {
if (attr.Args.Count == 1 && attr.Args[0] is LiteralExpr) {
var arg = attr.Args[0] as LiteralExpr;
System.Numerics.BigInteger value = (System.Numerics.BigInteger)arg.Value;
if (value.Sign > 0) {
if (DafnyOptions.O.ResourceLimit > 0) {
// Interpret this as multiplying the resource limit
int current_limit = DafnyOptions.O.ResourceLimit;
attr.Args[0] = new LiteralExpr(attr.Args[0].tok, value * current_limit);
attr.Name = "rlimit";
} else {
// Interpret this as multiplying the time limit
int current_limit = DafnyOptions.O.TimeLimit > 0 ? DafnyOptions.O.TimeLimit : 10; // Default to 10 seconds
attr.Args[0] = new LiteralExpr(attr.Args[0].tok, value * current_limit);
attr.Name = "timeLimit";
}
}
}
}
}
}
}
}
}
}
}
}
class MatchCaseExprSubstituteCloner : Cloner
{
private List<Tuple<CasePattern<BoundVar>, BoundVar>> patternSubst;
private BoundVar oldvar;
private BoundVar var;
// the cloner is called after resolving the body of matchexpr, trying
// to replace casepattern in the body that has been replaced by bv
public MatchCaseExprSubstituteCloner(List<Tuple<CasePattern<BoundVar>, BoundVar>> subst) {
this.patternSubst = subst;
this.oldvar = null;
this.var = null;
}
public MatchCaseExprSubstituteCloner(BoundVar oldvar, BoundVar var) {
this.patternSubst = null;
this.oldvar = oldvar;
this.var = var;
}
public override BoundVar CloneBoundVar(BoundVar bv) {
// replace bv with this.var if bv == oldvar
BoundVar bvNew;
if (oldvar != null && bv.Name.Equals(oldvar.Name)) {
bvNew = new BoundVar(new AutoGeneratedToken(bv.tok), var.Name, CloneType(bv.Type));
} else {
bvNew = new BoundVar(Tok(bv.tok), bv.Name, CloneType(bv.Type));
}
bvNew.IsGhost = bv.IsGhost;
return bvNew;
}
public override NameSegment CloneNameSegment(Expression expr) {
var e = (NameSegment)expr;
if (oldvar != null && e.Name.Equals(oldvar.Name)) {
return new NameSegment(new AutoGeneratedToken(e.tok), var.Name, e.OptTypeArguments == null ? null : e.OptTypeArguments.ConvertAll(CloneType));
} else {
return new NameSegment(Tok(e.tok), e.Name, e.OptTypeArguments == null ? null : e.OptTypeArguments.ConvertAll(CloneType));
}
}
public override Expression CloneApplySuffix(ApplySuffix e) {
// if the ApplySuffix matches the CasePattern, then replace it with the BoundVar.
CasePattern<BoundVar> cp = null;
BoundVar bv = null;
if (FindMatchingPattern(e, out cp, out bv)) {
if (bv.tok is MatchCaseToken) {
Contract.Assert(e.Args.Count == cp.Arguments.Count);
for (int i = 0; i < e.Args.Count; i++) {
((MatchCaseToken)bv.tok).AddVar(e.Args[i].tok, cp.Arguments[i].Var, false);
}
}
return new NameSegment(new AutoGeneratedToken(e.tok), bv.Name, null);
} else {
return new ApplySuffix(Tok(e.tok), e.AtTok == null ? null : Tok(e.AtTok), CloneExpr(e.Lhs), e.Args.ConvertAll(CloneExpr));
}
}
private bool FindMatchingPattern(ApplySuffix e, out CasePattern<BoundVar> pattern, out BoundVar bv) {
pattern = null;
bv = null;
if (patternSubst == null) {
return false;
}
Expression lhs = e.Lhs;
if (!(lhs is NameSegment)) {
return false;
}
string applyName = ((NameSegment)lhs).Name;
foreach (Tuple<CasePattern<BoundVar>, BoundVar> pair in patternSubst) {
var cp = pair.Item1;
string ctorName = cp.Id;
if (!(applyName.Equals(ctorName)) || (e.Args.Count != cp.Arguments.Count)) {
continue;
}
bool found = true;
for (int i = 0; i < e.Args.Count; i++) {
var arg1 = e.Args[i];
var arg2 = cp.Arguments[i];
if (arg1.Resolved is IdentifierExpr) {
var bv1 = ((IdentifierExpr)arg1.Resolved).Var;
if (bv1 != arg2.Var) {
found = false;
}
} else {
found = false;
}
}
if (found) {
pattern = cp;
bv = pair.Item2;
return true;
}
}
return false;
}
}
// MatchCaseToken is used to record BoundVars that are consolidated due to rewrite of
// nested match patterns. We want to record the original BoundVars that are consolidated
// so that they will show up in the IDE correctly.
public class MatchCaseToken : AutoGeneratedToken
{
public readonly List<Tuple<IToken, BoundVar, bool>> varList;
public MatchCaseToken(IToken tok)
: base(tok) {
varList = new List<Tuple<IToken, BoundVar, bool>>();
}
public void AddVar(IToken tok, BoundVar var, bool isDefinition) {
varList.Add(new Tuple<IToken, BoundVar, bool>(tok, var, isDefinition));
}
}
// A cloner that replace the original token with AutoGeneratedToken.
class AutoGeneratedTokenCloner : Cloner
{
public override IToken Tok(IToken tok) {
return new AutoGeneratedToken(tok);
}
}
// ===========================================================================================
public class InductionRewriter : IRewriter {
internal InductionRewriter(ErrorReporter reporter) : base(reporter) {
Contract.Requires(reporter != null);
}
internal override void PostDecreasesResolve(ModuleDefinition m) {
if (DafnyOptions.O.Induction == 0) {
// Don't bother inferring :induction attributes. This will also have the effect of not warning about malformed :induction attributes
} else {
foreach (var decl in m.TopLevelDecls) {
if (decl is TopLevelDeclWithMembers) {
var cl = (TopLevelDeclWithMembers)decl;
foreach (var member in cl.Members) {
if (member is ExtremeLemma) {
var method = (ExtremeLemma)member;
ProcessMethodExpressions(method);
ComputeLemmaInduction(method.PrefixLemma);
ProcessMethodExpressions(method.PrefixLemma);
} else if (member is Method) {
var method = (Method)member;
ComputeLemmaInduction(method);
ProcessMethodExpressions(method);
} else if (member is ExtremePredicate) {
var function = (ExtremePredicate)member;
ProcessFunctionExpressions(function);
ProcessFunctionExpressions(function.PrefixPredicate);
} else if (member is Function) {
var function = (Function)member;
ProcessFunctionExpressions(function);
}
}
}
if (decl is NewtypeDecl) {
var nt = (NewtypeDecl)decl;
if (nt.Constraint != null) {
var visitor = new Induction_Visitor(this);
visitor.Visit(nt.Constraint);
}
}
}
}
}
void ProcessMethodExpressions(Method method) {
Contract.Requires(method != null);
var visitor = new Induction_Visitor(this);
method.Req.ForEach(mfe => visitor.Visit(mfe.E));
method.Ens.ForEach(mfe => visitor.Visit(mfe.E));
if (method.Body != null) {
visitor.Visit(method.Body);
}
}
void ProcessFunctionExpressions(Function function) {
Contract.Requires(function != null);
var visitor = new Induction_Visitor(this);
function.Req.ForEach(visitor.Visit);
function.Ens.ForEach(visitor.Visit);
if (function.Body != null) {
visitor.Visit(function.Body);
}
}
void ComputeLemmaInduction(Method method) {
Contract.Requires(method != null);
if (method.Body != null && method.IsGhost && method.Mod.Expressions.Count == 0 && method.Outs.Count == 0 && !(method is ExtremeLemma)) {
var specs = new List<Expression>();
method.Req.ForEach(mfe => specs.Add(mfe.E));
method.Ens.ForEach(mfe => specs.Add(mfe.E));
ComputeInductionVariables(method.tok, method.Ins, specs, method, ref method.Attributes);
}
}
void ComputeInductionVariables<VarType>(IToken tok, List<VarType> boundVars, List<Expression> searchExprs, Method lemma, ref Attributes attributes) where VarType : class, IVariable {
Contract.Requires(tok != null);
Contract.Requires(boundVars != null);
Contract.Requires(searchExprs != null);
Contract.Requires(DafnyOptions.O.Induction != 0);
var args = Attributes.FindExpressions(attributes, "induction"); // we only look at the first one we find, since it overrides any other ones
if (args == null) {
if (DafnyOptions.O.Induction < 2) {
// No explicit induction variables and we're asked not to infer anything, so we're done
return;
} else if (DafnyOptions.O.Induction == 2 && lemma != null) {
// We're asked to infer induction variables only for quantifiers, not for lemmas
return;
} else if (DafnyOptions.O.Induction == 4 && lemma == null) {
// We're asked to infer induction variables only for lemmas, not for quantifiers
return;
}
// GO INFER below (only select boundVars)
} else if (args.Count == 0) {
// {:induction} is treated the same as {:induction true}, which says to automatically infer induction variables
// GO INFER below (all boundVars)
} else if (args.Count == 1 && args[0] is LiteralExpr && ((LiteralExpr)args[0]).Value is bool) {
// {:induction false} or {:induction true}
if (!(bool)((LiteralExpr)args[0]).Value) {
// we're told not to infer anything
return;
}
// GO INFER below (all boundVars)
} else {
// Here, we're expecting the arguments to {:induction args} to be a sublist of "this;boundVars", where "this" is allowed only
// if "lemma" denotes an instance lemma.
var goodArguments = new List<Expression>();
var i = lemma != null && !lemma.IsStatic ? -1 : 0; // -1 says it's okay to see "this" or any other parameter; 0 <= i says it's okay to see parameter i or higher
foreach (var arg in args) {
var ie = arg.Resolved as IdentifierExpr;
if (ie != null) {
var j = boundVars.FindIndex(v => v == ie.Var);
if (0 <= j && i <= j) {
goodArguments.Add(ie);
i = j + 1;
continue;
}
if (0 <= j) {
reporter.Warning(MessageSource.Rewriter, arg.tok, "{0}s given as :induction arguments must be given in the same order as in the {1}; ignoring attribute",
lemma != null ? "lemma parameter" : "bound variable", lemma != null ? "lemma" : "quantifier");
return;
}
// fall through for j < 0
} else if (lemma != null && arg.Resolved is ThisExpr) {
if (i < 0) {
goodArguments.Add(arg.Resolved);
i = 0;
continue;
}
reporter.Warning(MessageSource.Rewriter, arg.tok, "lemma parameters given as :induction arguments must be given in the same order as in the lemma; ignoring attribute");
return;
}
reporter.Warning(MessageSource.Rewriter, arg.tok, "invalid :induction attribute argument; expected {0}{1}; ignoring attribute",
i == 0 ? "'false' or 'true' or " : "",
lemma != null ? "lemma parameter" : "bound variable");
return;
}
// The argument list was legal, so let's use it for the _induction attribute
attributes = new Attributes("_induction", goodArguments, attributes);
return;
}
// Okay, here we go, coming up with good induction setting for the given situation
var inductionVariables = new List<Expression>();
if (lemma != null && !lemma.IsStatic) {
if (args != null || searchExprs.Exists(expr => Translator.ContainsFreeVariable(expr, true, null))) {
inductionVariables.Add(new ThisExpr(lemma));
}
}
foreach (IVariable n in boundVars) {
if (!(n.Type.IsTypeParameter || n.Type.IsInternalTypeSynonym) && (args != null || searchExprs.Exists(expr => VarOccursInArgumentToRecursiveFunction(expr, n)))) {
inductionVariables.Add(new IdentifierExpr(n.Tok, n));
}
}
if (inductionVariables.Count != 0) {
// We found something usable, so let's record that in an attribute
attributes = new Attributes("_induction", inductionVariables, attributes);
// And since we're inferring something, let's also report that in a hover text.
var s = Printer.OneAttributeToString(attributes, "induction");
if (lemma is PrefixLemma) {
s = lemma.Name + " " + s;
}
reporter.Info(MessageSource.Rewriter, tok, s);
}
}
class Induction_Visitor : BottomUpVisitor
{
readonly InductionRewriter IndRewriter;
public Induction_Visitor(InductionRewriter inductionRewriter) {
Contract.Requires(inductionRewriter != null);
IndRewriter = inductionRewriter;
}
protected override void VisitOneExpr(Expression expr) {
var q = expr as QuantifierExpr;
if (q != null && q.SplitQuantifier == null) {
IndRewriter.ComputeInductionVariables(q.tok, q.BoundVars, new List<Expression>() { q.LogicalBody() }, null, ref q.Attributes);
}
}
void VisitInductionStmt(Statement stmt) {
Contract.Requires(stmt != null);
// visit a selection of subexpressions
if (stmt is AssertStmt) {
var s = (AssertStmt)stmt;
Visit(s.Expr);
}
// recursively visit all substatements
foreach (var s in stmt.SubStatements) {
VisitInductionStmt(s);
}
}
}
/// <summary>
/// Returns 'true' iff by looking at 'expr' the Induction Heuristic determines that induction should be applied to 'n'.
/// More precisely:
/// DafnyInductionHeuristic Return 'true'
/// ----------------------- -------------
/// 0 always
/// 1 if 'n' occurs as any subexpression (of 'expr')
/// 2 if 'n' occurs as any subexpression of any index argument of an array/sequence select expression or any argument to a recursive function
/// 3 if 'n' occurs as a prominent subexpression of any index argument of an array/sequence select expression or any argument to a recursive function
/// 4 if 'n' occurs as any subexpression of any argument to a recursive function
/// 5 if 'n' occurs as a prominent subexpression of any argument to a recursive function
/// 6 if 'n' occurs as a prominent subexpression of any decreases-influencing argument to a recursive function
/// </summary>
public static bool VarOccursInArgumentToRecursiveFunction(Expression expr, IVariable n) {
switch (DafnyOptions.O.InductionHeuristic) {
case 0: return true;
case 1: return Translator.ContainsFreeVariable(expr, false, n);
default: return VarOccursInArgumentToRecursiveFunction(expr, n, false);
}
}
/// <summary>
/// Worker routine for VarOccursInArgumentToRecursiveFunction(expr,n), where the additional parameter 'exprIsProminent' says whether or
/// not 'expr' has prominent status in its context.
/// DafnyInductionHeuristic cases 0 and 1 are assumed to be handled elsewhere (i.e., a precondition of this method is DafnyInductionHeuristic is at least 2).
/// </summary>
static bool VarOccursInArgumentToRecursiveFunction(Expression expr, IVariable n, bool exprIsProminent) {
Contract.Requires(expr != null);
Contract.Requires(n != null);
// The following variable is what gets passed down to recursive calls if the subexpression does not itself acquire prominent status.
var subExprIsProminent = DafnyOptions.O.InductionHeuristic == 2 || DafnyOptions.O.InductionHeuristic == 4 ? /*once prominent, always prominent*/exprIsProminent : /*reset the prominent status*/false;
if (expr is IdentifierExpr) {
var e = (IdentifierExpr)expr;
return exprIsProminent && e.Var == n;
} else if (expr is SeqSelectExpr) {
var e = (SeqSelectExpr)expr;
var q = DafnyOptions.O.InductionHeuristic < 4 || subExprIsProminent;
return VarOccursInArgumentToRecursiveFunction(e.Seq, n, subExprIsProminent) || // this subexpression does not acquire "prominent" status
(e.E0 != null && VarOccursInArgumentToRecursiveFunction(e.E0, n, q)) || // this one does (unless arrays/sequences are excluded)
(e.E1 != null && VarOccursInArgumentToRecursiveFunction(e.E1, n, q)); // ditto
} else if (expr is MultiSelectExpr) {
var e = (MultiSelectExpr)expr;
var q = DafnyOptions.O.InductionHeuristic < 4 || subExprIsProminent;
return VarOccursInArgumentToRecursiveFunction(e.Array, n, subExprIsProminent) ||
e.Indices.Exists(exp => VarOccursInArgumentToRecursiveFunction(exp, n, q));
} else if (expr is FunctionCallExpr) {
var e = (FunctionCallExpr)expr;
// For recursive functions: arguments are "prominent"
// For non-recursive function: arguments are "prominent" if the call is
var rec = e.Function.IsRecursive && e.CoCall != FunctionCallExpr.CoCallResolution.Yes;
var decr = e.Function.Decreases.Expressions;
bool variantArgument;
if (DafnyOptions.O.InductionHeuristic < 6) {
variantArgument = rec;
} else {
// The receiver is considered to be "variant" if the function is recursive and the receiver participates
// in the effective decreases clause of the function. The receiver participates if it's a free variable
// of a term in the explicit decreases clause.
variantArgument = rec && decr.Exists(ee => Translator.ContainsFreeVariable(ee, true, null));
}
if (VarOccursInArgumentToRecursiveFunction(e.Receiver, n, variantArgument || subExprIsProminent)) {
return true;
}
Contract.Assert(e.Function.Formals.Count == e.Args.Count);
for (int i = 0; i < e.Function.Formals.Count; i++) {
var f = e.Function.Formals[i];
var exp = e.Args[i];
if (DafnyOptions.O.InductionHeuristic < 6) {
variantArgument = rec;
} else if (rec) {
// The argument position is considered to be "variant" if the function is recursive and...
// ... it has something to do with why the callee is well-founded, which happens when...
if (f is ImplicitFormal) {
// ... it is the argument is the implicit _k parameter, which is always first in the effective decreases clause of a prefix lemma, or
variantArgument = true;
} else if (decr.Exists(ee => Translator.ContainsFreeVariable(ee, false, f))) {
// ... it participates in the effective decreases clause of the function, which happens when it is
// a free variable of a term in the explicit decreases clause, or
variantArgument = true;
} else {
// ... the callee is a prefix predicate.
variantArgument = true;
}
}
if (VarOccursInArgumentToRecursiveFunction(exp, n, variantArgument || subExprIsProminent)) {
return true;
}
}
return false;
} else if (expr is TernaryExpr) {
var e = (TernaryExpr)expr;
switch (e.Op) {
case TernaryExpr.Opcode.PrefixEqOp:
case TernaryExpr.Opcode.PrefixNeqOp:
return VarOccursInArgumentToRecursiveFunction(e.E0, n, true) ||
VarOccursInArgumentToRecursiveFunction(e.E1, n, subExprIsProminent) ||
VarOccursInArgumentToRecursiveFunction(e.E2, n, subExprIsProminent);
default:
Contract.Assert(false); throw new cce.UnreachableException(); // unexpected ternary expression
}
} else if (expr is DatatypeValue) {
var e = (DatatypeValue)expr;
var q = n.Type.IsDatatype ? exprIsProminent : subExprIsProminent; // prominent status continues, if we're looking for a variable whose type is a datatype
return e.Arguments.Exists(exp => VarOccursInArgumentToRecursiveFunction(exp, n, q));
} else if (expr is UnaryExpr) {
var e = (UnaryExpr)expr;
// both Not and SeqLength preserve prominence
return VarOccursInArgumentToRecursiveFunction(e.E, n, exprIsProminent);
} else if (expr is BinaryExpr) {
var e = (BinaryExpr)expr;
bool q;
switch (e.ResolvedOp) {
case BinaryExpr.ResolvedOpcode.Add:
case BinaryExpr.ResolvedOpcode.Sub:
case BinaryExpr.ResolvedOpcode.Mul:
case BinaryExpr.ResolvedOpcode.Div:
case BinaryExpr.ResolvedOpcode.Mod:
case BinaryExpr.ResolvedOpcode.LeftShift:
case BinaryExpr.ResolvedOpcode.RightShift:
case BinaryExpr.ResolvedOpcode.BitwiseAnd:
case BinaryExpr.ResolvedOpcode.BitwiseOr:
case BinaryExpr.ResolvedOpcode.BitwiseXor:
case BinaryExpr.ResolvedOpcode.Union:
case BinaryExpr.ResolvedOpcode.Intersection:
case BinaryExpr.ResolvedOpcode.SetDifference:
case BinaryExpr.ResolvedOpcode.Concat:
// these operators preserve prominence
q = exprIsProminent;
break;
default:
// whereas all other binary operators do not
q = subExprIsProminent;
break;
}
return VarOccursInArgumentToRecursiveFunction(e.E0, n, q) ||
VarOccursInArgumentToRecursiveFunction(e.E1, n, q);
} else if (expr is StmtExpr) {
var e = (StmtExpr)expr;
// ignore the statement
return VarOccursInArgumentToRecursiveFunction(e.E, n);
} else if (expr is ITEExpr) {
var e = (ITEExpr)expr;
return VarOccursInArgumentToRecursiveFunction(e.Test, n, subExprIsProminent) || // test is not "prominent"
VarOccursInArgumentToRecursiveFunction(e.Thn, n, exprIsProminent) || // but the two branches are
VarOccursInArgumentToRecursiveFunction(e.Els, n, exprIsProminent);
} else if (expr is OldExpr ||
expr is ConcreteSyntaxExpression ||
expr is BoxingCastExpr ||
expr is UnboxingCastExpr) {
foreach (var exp in expr.SubExpressions) {
if (VarOccursInArgumentToRecursiveFunction(exp, n, exprIsProminent)) { // maintain prominence
return true;
}
}
return false;
} else {
// in all other cases, reset the prominence status and recurse on the subexpressions
foreach (var exp in expr.SubExpressions) {
if (VarOccursInArgumentToRecursiveFunction(exp, n, subExprIsProminent)) {
return true;
}
}
return false;
}
}
}
}
| 44.737778 | 204 | 0.592236 | [
"MIT"
] | secure-foundations/dafny | Source/Dafny/Rewriter.cs | 90,594 | C# |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using Microsoft.Azure.Management.Network.Models;
namespace Microsoft.Azure.Management.Network.Models
{
/// <summary>
/// Response for PutVirtualNetworkGatewayConnectionSharedKey Api servive
/// call
/// </summary>
public partial class ConnectionSharedKeyPutResponse : UpdateOperationResponse
{
private ConnectionSharedKey _connectionSharedKey;
/// <summary>
/// Optional. Puts the virtual network gateway connection shared key
/// that exists in a resource group
/// </summary>
public ConnectionSharedKey ConnectionSharedKey
{
get { return this._connectionSharedKey; }
set { this._connectionSharedKey = value; }
}
/// <summary>
/// Initializes a new instance of the ConnectionSharedKeyPutResponse
/// class.
/// </summary>
public ConnectionSharedKeyPutResponse()
{
}
}
}
| 32.418182 | 81 | 0.67751 | [
"Apache-2.0"
] | CerebralMischief/azure-sdk-for-net | src/ResourceManagement/Network/NetworkManagement/Generated/Models/ConnectionSharedKeyPutResponse.cs | 1,783 | 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.
==================================================================== */
namespace Npoi.Core.XWPF.UserModel
{
/**
* Specifies the Set of possible restart locations which may be used as to
* determine the next available line when a break's type attribute has a value
* of textWrapping.
*
* @author Gisella Bronzetti
*/
public enum BreakClear
{
/**
* Specifies that the text wrapping break shall advance the text to the next
* line in the WordProcessingML document, regardless of its position left to
* right or the presence of any floating objects which intersect with the
* line,
*
* This is the Setting for a typical line break in a document.
*/
NONE = (1),
/**
* Specifies that the text wrapping break shall behave as follows:
* <ul>
* <li> If this line is broken into multiple regions (a floating object in
* the center of the page has text wrapping on both sides:
* <ul>
* <li> If this is the leftmost region of text flow on this line, advance
* the text to the next position on the line </li>
* <li>Otherwise, treat this as a text wrapping break of type all. </li>
* </ul>
* </li>
* <li> If this line is not broken into multiple regions, then treat this
* break as a text wrapping break of type none. </li>
* </ul>
* <li> If the parent paragraph is right to left, then these behaviors are
* also reversed. </li>
*/
LEFT = (2),
/**
* Specifies that the text wrapping break shall behave as follows:
* <ul>
* <li> If this line is broken into multiple regions (a floating object in
* the center of the page has text wrapping on both sides:
* <ul>
* <li> If this is the rightmost region of text flow on this line, advance
* the text to the next position on the next line </li>
* <li> Otherwise, treat this as a text wrapping break of type all. </li>
* </ul>
* <li> If this line is not broken into multiple regions, then treat this
* break as a text wrapping break of type none. </li>
* <li> If the parent paragraph is right to left, then these beha viors are
* also reversed. </li>
* </ul>
*/
RIGHT = (3),
/**
* Specifies that the text wrapping break shall advance the text to the next
* line in the WordProcessingML document which spans the full width of the
* line.
*/
ALL = (4)
//private int value;
//private BreakClear(int val) {
// value = val;
//}
//public int GetValue() {
// return value;
//}
//private static Dictionary<int, BreakClear> imap = new Dictionary<int, BreakClear>();
//static {
// foreach (BreakClear p in values()) {
// imap.Put(new int(p.Value), p);
// }
//}
//public static BreakClear ValueOf(int type) {
// BreakClear bType = imap.Get(new int(type));
// if (bType == null)
// throw new ArgumentException("Unknown break clear type: "
// + type);
// return bType;
//}
}
} | 38.636364 | 94 | 0.578118 | [
"Apache-2.0"
] | Arch/Npoi.Core | src/Npoi.Core.Ooxml/XWPF/Usermodel/BreakClear.cs | 4,250 | C# |
namespace MassageStudioLorem.Infrastructure
{
using System.Security.Claims;
using static Areas.Client.ClientConstants;
using static Areas.Masseur.MasseurConstants;
using static Areas.Admin.AdminConstants;
public static class ClaimsPrincipalExtensions
{
public static string GetId(this ClaimsPrincipal user)
=> user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
public static bool IsClient(this ClaimsPrincipal user)
=> user.IsInRole(ClientRoleName);
public static bool IsMasseur(this ClaimsPrincipal user)
=> user.IsInRole(MasseurRoleName);
public static bool IsAdmin(this ClaimsPrincipal user)
=> user.IsInRole(AdminRoleName);
}
}
| 32.347826 | 64 | 0.706989 | [
"MIT"
] | lulzzz/MassageStudioLorem | MassageStudioLorem/Infrastructure/ClaimsPrincipalExtensions.cs | 746 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using RepositoryLayer;
namespace RepositoryLayer.Migrations
{
[DbContext(typeof(Project1Db))]
[Migration("20210618150842_migration2")]
partial class migration2
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.7")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("ModelsLibrary.Customers", b =>
{
b.Property<int>("CustomerID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("CustomerFirstName")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("nvarchar(20)");
b.Property<string>("CustomerLastName")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("nvarchar(20)");
b.HasKey("CustomerID");
b.ToTable("Customers");
});
modelBuilder.Entity("ModelsLibrary.Orders", b =>
{
b.Property<int>("OrderID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int?>("CustomerID")
.HasColumnType("int");
b.Property<string>("OrderTime")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("nvarchar(max)");
b.HasKey("OrderID");
b.HasIndex("CustomerID");
b.ToTable("Orders");
});
modelBuilder.Entity("ModelsLibrary.Orders", b =>
{
b.HasOne("ModelsLibrary.Customers", "Customer")
.WithMany()
.HasForeignKey("CustomerID");
b.Navigation("Customer");
});
#pragma warning restore 612, 618
}
}
}
| 35.85 | 125 | 0.535216 | [
"MIT"
] | 06012021-dotnet-uta/EthanBakerP1 | Project1Folder/RepositoryLayer/Migrations/20210618150842_migration2.Designer.cs | 2,870 | C# |
using System;
namespace CableCloud.Ui.Parsers.Exceptions
{
public class ParserException : Exception
{
public string ExceptionMessage { get; }
public ParserException(string message) : base($"Parse exception: {message}")
{
ExceptionMessage = message;
}
}
}
| 20.933333 | 84 | 0.627389 | [
"MIT"
] | batmatt/tsst-network | eon/CableCloud/src/Ui/Parsers/Exceptions/ParserException.cs | 316 | C# |
//
// Serializer for byps.test.api.remote.BRequest_RemoteInlineInstance_getPoint2DListList
//
// THIS FILE HAS BEEN GENERATED. DO NOT MODIFY.
//
using System;
using System.Collections.Generic;
using byps;
namespace byps.test.api.remote
{
public class BSerializer_1650554387 : BSerializer {
public readonly static BSerializer instance = new BSerializer_1650554387();
public BSerializer_1650554387()
: base(1650554387) {}
public BSerializer_1650554387(int typeId)
: base(typeId) {}
public override Object read(Object obj1, BInput bin1, long version)
{
BInputBin bin = (BInputBin)bin1;
BRequest_RemoteInlineInstance_getPoint2DListList obj = (BRequest_RemoteInlineInstance_getPoint2DListList)(obj1 != null ? obj1 : bin.onObjectCreated(new BRequest_RemoteInlineInstance_getPoint2DListList()));
BBufferBin bbuf = bin.bbuf;
return obj;
}
}
} // namespace
| 24.648649 | 208 | 0.75 | [
"MIT"
] | markusessigde/byps | csharp/bypstest-ser/src-ser/byps/test/api/remote/BSerializer_1650554387.cs | 914 | 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 Microsoft.AspNetCore.Builder;
namespace Microsoft.AspNetCore.SpaServices
{
/// <summary>
/// Defines a class that provides mechanisms for configuring the hosting
/// of a Single Page Application (SPA) and attaching middleware.
/// </summary>
public interface ISpaBuilder
{
/// <summary>
/// The <see cref="IApplicationBuilder"/> representing the middleware pipeline
/// in which the SPA is being hosted.
/// </summary>
IApplicationBuilder ApplicationBuilder { get; }
/// <summary>
/// Describes configuration options for hosting a SPA.
/// </summary>
SpaOptions Options { get; }
}
}
| 33.076923 | 111 | 0.656977 | [
"Apache-2.0"
] | 06b/AspNetCore | src/Middleware/SpaServices.Extensions/src/ISpaBuilder.cs | 862 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EasyNetQ;
using SimpleWebShop.Messages;
namespace SimpleWebShop.Web.Controllers
{
public class TestController : BaseController
{
public ActionResult Index()
{
return this.View();
}
[HttpPost]
public ActionResult Publish(string name, int age)
{
IBus bus = RabbitHutch.CreateBus("host=localhost");
var message = new TestMessage()
{
Age = age,
Name = name
};
bus.Publish(message);
return this.Content("Ok");
}
}
} | 22.21875 | 63 | 0.562588 | [
"MIT"
] | svetlimladenov/SimpleWebShop | src/SimpleWebShop/Web/SimpleWebShop.Web/Controllers/TestController.cs | 713 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
namespace Microsoft.Azure.PowerShell.Cmdlets.DnsResolver.Runtime.Json
{
internal sealed class XBinary : JsonNode
{
private readonly byte[] _value;
private readonly string _base64;
internal XBinary(byte[] value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
internal XBinary(string base64EncodedString)
{
_base64 = base64EncodedString ?? throw new ArgumentNullException(nameof(base64EncodedString));
}
internal override JsonType Type => JsonType.Binary;
internal byte[] Value => _value ?? Convert.FromBase64String(_base64);
#region #region Implicit Casts
public static implicit operator byte[] (XBinary data) => data.Value;
public static implicit operator XBinary(byte[] data) => new XBinary(data);
#endregion
public override int GetHashCode() => Value.GetHashCode();
public override string ToString() => _base64 ?? Convert.ToBase64String(_value);
}
} | 36.375 | 107 | 0.564948 | [
"MIT"
] | Agazoth/azure-powershell | src/DnsResolver/generated/runtime/Nodes/XBinary.cs | 1,418 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotVVM.Framework.ViewModel;
namespace DotVVM.Samples.ApplicationInsights.AspNetCore.ViewModels.Test
{
public class CommandExceptionViewModel : DotvvmViewModelBase
{
public void TestCommand()
{
throw new ArgumentException("Throwing exception in button command");
}
}
}
| 22.277778 | 80 | 0.740648 | [
"Apache-2.0"
] | AlexanderSemenyak/dotvvm | src/Samples/ApplicationInsights.AspNetCore/ViewModels/Test/CommandExceptionViewModel.cs | 401 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ForestPack
{
public class ChestDemo : MonoBehaviour
{
//This script goes on the ChestComplete prefab;
public Animator chestAnim; //Animator for the chest;
// Use this for initialization
void Awake()
{
//get the Animator component from the chest;
chestAnim = GetComponent<Animator>();
//start opening and closing the chest for demo purposes;
StartCoroutine(OpenCloseChest());
}
IEnumerator OpenCloseChest()
{
//play open animation;
chestAnim.SetTrigger("open");
//wait 2 seconds;
yield return new WaitForSeconds(2);
//play close animation;
chestAnim.SetTrigger("close");
//wait 2 seconds;
yield return new WaitForSeconds(2);
//Do it again;
StartCoroutine(OpenCloseChest());
}
}
} | 25.7 | 68 | 0.578794 | [
"MIT"
] | jschwarzwalder/OnlyOneCoin | Assets/AurynSky/Forest Pack/Scripts/ChestDemo.cs | 1,030 | C# |
namespace WalletWasabi.Fluent.ViewModels.Navigation
{
public interface INavigatable
{
void OnNavigatedTo(bool isInHistory);
void OnNavigatedFrom(bool isInHistory);
}
} | 19.444444 | 51 | 0.8 | [
"MIT"
] | 0racl3z/WalletWasabi | WalletWasabi.Fluent/ViewModels/Navigation/INavigatable.cs | 175 | C# |
using System.Collections.Generic;
namespace Lectern2.Interfaces
{
public interface IPluginManager
{
List<ILecternPlugin> LoadedPlugins { get; }
}
}
| 17 | 51 | 0.7 | [
"MIT"
] | jmazouri/lectern2 | Lectern2/Interfaces/IPluginManager.cs | 172 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.EntityFrameworkCore.Migrations
{
/// <summary>
/// <para>
/// A service representing an assembly containing EF Core Migrations.
/// </para>
/// <para>
/// The service lifetime is <see cref="ServiceLifetime.Scoped" />. This means that each
/// <see cref="DbContext" /> instance will use its own instance of this service.
/// The implementation may depend on other services registered with any lifetime.
/// The implementation does not need to be thread-safe.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-migrations">Database migrations</see> for more information.
/// </remarks>
public interface IMigrationsAssembly
{
/// <summary>
/// A dictionary mapping migration identifiers to the <see cref="TypeInfo" /> of the class
/// that represents the migration.
/// </summary>
IReadOnlyDictionary<string, TypeInfo> Migrations { get; }
/// <summary>
/// The snapshot of the <see cref="IModel" /> contained in the assembly.
/// </summary>
ModelSnapshot? ModelSnapshot { get; }
/// <summary>
/// The assembly that contains the migrations, snapshot, etc.
/// </summary>
Assembly Assembly { get; }
/// <summary>
/// Finds a migration identifier in the assembly with the given a full migration name or
/// just its identifier.
/// </summary>
/// <param name="nameOrId"> The name or identifier to lookup. </param>
/// <returns> The identifier of the migration, or <see langword="null" /> if none was found. </returns>
string? FindMigrationId(string nameOrId);
/// <summary>
/// Creates an instance of the migration class.
/// </summary>
/// <param name="migrationClass">
/// The <see cref="TypeInfo" /> for the migration class, as obtained from the <see cref="Migrations" /> dictionary.
/// </param>
/// <param name="activeProvider"> The name of the current database provider. </param>
/// <returns> The migration instance. </returns>
Migration CreateMigration(TypeInfo migrationClass, string activeProvider);
}
}
| 42.920635 | 127 | 0.623151 | [
"MIT"
] | CameronAavik/efcore | src/EFCore.Relational/Migrations/IMigrationsAssembly.cs | 2,704 | C# |
using System;
namespace Brickweave.Cqrs.Cli.Tests.Models
{
public class CreateFoo : ICommand<string>
{
public CreateFoo(int id, DateTime dateCreated, string bar = "bar")
{
Id = id;
Bar = bar;
DateCreated = dateCreated;
}
public int Id { get; }
public string Bar { get; }
public DateTime DateCreated { get; }
}
}
| 21.631579 | 74 | 0.547445 | [
"MIT"
] | agartee/Brickweave | tests/Brickweave.Cqrs.Cli.Tests/Models/CreateFoo.cs | 413 | C# |
using UnityEditor;
using UnityEngine;
namespace TSW
{
[CustomPropertyDrawer(typeof(BitMaskAttribute))]
public class EnumBitMaskPropertyDrawer : PropertyDrawer
{
public static int DrawBitMaskField(Rect aPosition, int aMask, System.Type aType, GUIContent aLabel)
{
string[] itemNames = System.Enum.GetNames(aType);
int[] itemValues = System.Enum.GetValues(aType) as int[];
int val = aMask;
int maskVal = 0;
for (int i = 0; i < itemValues.Length; i++)
{
if (itemValues[i] != 0)
{
if ((val & itemValues[i]) == itemValues[i])
{
maskVal |= 1 << i;
}
}
else if (val == 0)
{
maskVal |= 1 << i;
}
}
int newMaskVal = EditorGUI.MaskField(aPosition, aLabel, maskVal, itemNames);
int changes = maskVal ^ newMaskVal;
for (int i = 0; i < itemValues.Length; i++)
{
if ((changes & (1 << i)) != 0) // has this list item changed?
{
if ((newMaskVal & (1 << i)) != 0) // has it been set?
{
if (itemValues[i] == 0) // special case: if "0" is set, just set the val to 0
{
val = 0;
break;
}
else
{
val |= itemValues[i];
}
}
else // it has been reset
{
val &= ~itemValues[i];
}
}
}
return val;
}
public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label)
{
BitMaskAttribute typeAttr = attribute as BitMaskAttribute;
// Add the actual int value behind the field name
label.text = label.text + "(" + prop.intValue + ")";
prop.intValue = DrawBitMaskField(position, prop.intValue, typeAttr.propType, label);
}
}
} | 25.298507 | 101 | 0.571681 | [
"MIT"
] | vthem/PolyRace | Assets/Scripts/TSW.GameLib/Editor/EnumInspector/EnumBitMaskPropertyDrawer.cs | 1,695 | C# |
#if !NETSTANDARD13
/*
* 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 medialive-2017-10-14.normal.json service model.
*/
using Amazon.MediaLive;
using Amazon.MediaLive.Model;
using Moq;
using System;
using System.Linq;
using AWSSDK_DotNet35.UnitTests.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AWSSDK_DotNet35.UnitTests.PaginatorTests
{
[TestClass]
public class MediaLivePaginatorTests
{
private static Mock<AmazonMediaLiveClient> _mockClient;
[ClassInitialize()]
public static void ClassInitialize(TestContext a)
{
_mockClient = new Mock<AmazonMediaLiveClient>("access key", "secret", Amazon.RegionEndpoint.USEast1);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
public void DescribeScheduleTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<DescribeScheduleRequest>();
var firstResponse = InstantiateClassGenerator.Execute<DescribeScheduleResponse>();
var secondResponse = InstantiateClassGenerator.Execute<DescribeScheduleResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.DescribeSchedule(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.DescribeSchedule(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void DescribeScheduleTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<DescribeScheduleRequest>();
var response = InstantiateClassGenerator.Execute<DescribeScheduleResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.DescribeSchedule(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.DescribeSchedule(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
public void ListChannelsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListChannelsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListChannelsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListChannelsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListChannels(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListChannels(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListChannelsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListChannelsRequest>();
var response = InstantiateClassGenerator.Execute<ListChannelsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListChannels(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListChannels(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
public void ListInputDevicesTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListInputDevicesRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListInputDevicesResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListInputDevicesResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListInputDevices(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListInputDevices(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListInputDevicesTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListInputDevicesRequest>();
var response = InstantiateClassGenerator.Execute<ListInputDevicesResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListInputDevices(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListInputDevices(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
public void ListInputDeviceTransfersTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListInputDeviceTransfersRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListInputDeviceTransfersResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListInputDeviceTransfersResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListInputDeviceTransfers(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListInputDeviceTransfers(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListInputDeviceTransfersTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListInputDeviceTransfersRequest>();
var response = InstantiateClassGenerator.Execute<ListInputDeviceTransfersResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListInputDeviceTransfers(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListInputDeviceTransfers(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
public void ListInputsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListInputsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListInputsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListInputsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListInputs(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListInputs(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListInputsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListInputsRequest>();
var response = InstantiateClassGenerator.Execute<ListInputsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListInputs(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListInputs(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
public void ListInputSecurityGroupsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListInputSecurityGroupsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListInputSecurityGroupsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListInputSecurityGroupsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListInputSecurityGroups(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListInputSecurityGroups(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListInputSecurityGroupsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListInputSecurityGroupsRequest>();
var response = InstantiateClassGenerator.Execute<ListInputSecurityGroupsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListInputSecurityGroups(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListInputSecurityGroups(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
public void ListMultiplexesTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListMultiplexesRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListMultiplexesResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListMultiplexesResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListMultiplexes(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListMultiplexes(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListMultiplexesTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListMultiplexesRequest>();
var response = InstantiateClassGenerator.Execute<ListMultiplexesResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListMultiplexes(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListMultiplexes(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
public void ListMultiplexProgramsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListMultiplexProgramsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListMultiplexProgramsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListMultiplexProgramsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListMultiplexPrograms(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListMultiplexPrograms(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListMultiplexProgramsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListMultiplexProgramsRequest>();
var response = InstantiateClassGenerator.Execute<ListMultiplexProgramsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListMultiplexPrograms(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListMultiplexPrograms(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
public void ListOfferingsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListOfferingsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListOfferingsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListOfferingsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListOfferings(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListOfferings(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListOfferingsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListOfferingsRequest>();
var response = InstantiateClassGenerator.Execute<ListOfferingsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListOfferings(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListOfferings(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
public void ListReservationsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListReservationsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListReservationsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListReservationsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListReservations(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListReservations(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("MediaLive")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListReservationsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListReservationsRequest>();
var response = InstantiateClassGenerator.Execute<ListReservationsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListReservations(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListReservations(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
}
}
#endif | 41.843318 | 160 | 0.671916 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/test/Services/MediaLive/UnitTests/Generated/_bcl45+netstandard/Paginators/MediaLivePaginatorTests.cs | 18,160 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Service.Web
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.913043 | 70 | 0.614094 | [
"Unlicense"
] | VsevolodGus/ServiceWork | Web/Service.Web/Program.cs | 596 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class DeathHandler : MonoBehaviour
{
[SerializeField] BoolVariable isAlive;
[SerializeField] Canvas reticleCanvas;
[SerializeField] Canvas gameOverCanvas;
[SerializeField] private UnityEngine.InputSystem.PlayerInput playerInput;
[SerializeField] UnityStandardAssets.Characters.FirstPerson.RigidbodyFirstPersonController rbController;
private void Awake() {
gameOverCanvas.enabled = false;
reticleCanvas.enabled = true;
if (playerInput.currentActionMap.name != "Player") {
Cursor.lockState = CursorLockMode.Locked;
rbController.enabled = true;
playerInput.SwitchCurrentActionMap("UI");
}
}
public void HandleDeath() {
if (TryGetComponent(out UnityEngine.AI.NavMeshAgent agent)) {
agent.enabled = false;
}
reticleCanvas.enabled = false;
gameOverCanvas.enabled = true;
//Animation[] animations = gameOverCanvas.GetComponentsInChildren<Animation>();
//foreach (Animation animation in animations) {
// animation.Play();
//}
//Animator[] animators = gameOverCanvas.GetComponentsInChildren<Animator>();
//foreach (Animator animator in animators) {
// animator.enabled = true;
//}
Time.timeScale = .1f;
DisableWeaponScript();
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
rbController.enabled = false;
playerInput.SwitchCurrentActionMap("UI");
isAlive.Value = false;
Debug.Log("Player has died.");
}
private void DisableWeaponScript() {
Weapon[] weapons = GetComponentsInChildren<Weapon>();
for (int i = 0; i < weapons.Length; i++) {
weapons[i].enabled = false;
}
}
}
| 32.372881 | 108 | 0.64712 | [
"MIT"
] | TDM-GameDev/Zombie-Runner | Assets/Scripts/DeathHandler.cs | 1,910 | C# |
using Netduino.Foundation.Audio;
using System.Threading;
using N = SecretLabs.NETMF.Hardware.Netduino;
namespace PiezoSample
{
public class Program
{
public static void Main()
{
const int NUMBER_OF_NOTES = 16;
float[] melody = new float[NUMBER_OF_NOTES]
{
NoteFrequencies.NOTE_A3,
NoteFrequencies.NOTE_B3,
NoteFrequencies.NOTE_CS4,
NoteFrequencies.NOTE_D4,
NoteFrequencies.NOTE_E4,
NoteFrequencies.NOTE_FS4,
NoteFrequencies.NOTE_GS4,
NoteFrequencies.NOTE_A4,
NoteFrequencies.NOTE_A4,
NoteFrequencies.NOTE_GS4,
NoteFrequencies.NOTE_FS4,
NoteFrequencies.NOTE_E4,
NoteFrequencies.NOTE_D4,
NoteFrequencies.NOTE_CS4,
NoteFrequencies.NOTE_B3,
NoteFrequencies.NOTE_A3,
};
var piezo = new PiezoSpeaker(N.PWMChannels.PWM_PIN_D5);
while (true)
{
for(int i = 0; i < NUMBER_OF_NOTES; i++)
{
//PlayTone with a duration in synchronous
piezo.PlayTone(melody[i], 600);
Thread.Sleep(50);
}
Thread.Sleep(1000);
//PlayTone without a duration will return immediately and play the tone
piezo.PlayTone(NoteFrequencies.NOTE_A4);
Thread.Sleep(2000);
//call StopTone to end a tone started without a duration
piezo.StopTone();
Thread.Sleep(2000);
}
}
}
} | 30.894737 | 87 | 0.51448 | [
"Apache-2.0"
] | WildernessLabs/Netduino.Foundation | Source/Netduino.Foundation.Core.Samples/PiezoSample/Program.cs | 1,761 | C# |
using System;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Threading.Tasks;
using Acr.UserDialogs;
using Plugin.SpeechRecognition;
using Xamarin.Essentials;
namespace Plugin.SpeechDialogs
{
public class SpeechDialogs : ISpeechDialogs
{
readonly ISpeechRecognizer speech = CrossSpeechRecognition.Current;
readonly IUserDialogs dialogs = UserDialogs.Instance;
public IObservable<string> Choices(string question, string[] choices, bool speakChoices = false) => Observable.FromAsync(async ct =>
{
await TextToSpeech.SpeakAsync(question, ct);
var dialogTask = this.dialogs.ActionSheetAsync(question, "Cancel", null, ct, choices);
var speechTask = this.speech
.ListenForFirstKeyword(choices)
.ToTask(ct);
if (speakChoices)
{
Task.Run(async () =>
{
var i = 0;
while (!ct.IsCancellationRequested && i < choices.Length)
{
await TextToSpeech.SpeakAsync(choices[i], ct);
i++;
}
}, ct);
}
var finishTask = await Task.WhenAny(dialogTask, speechTask);
if (ct.IsCancellationRequested)
return null;
if (finishTask == dialogTask)
return dialogTask.Result;
if (finishTask == speechTask)
return speechTask.Result;
return null;
});
public IObservable<bool> Confirm(ConfirmConfig config) => Observable.FromAsync(async ct =>
{
TextToSpeech.SpeakAsync(config.Message, ct);
var confirmTask = this.dialogs.ConfirmAsync(config, ct);
var speechTask = this.speech
.ListenForFirstKeyword(config.OkText, config.CancelText)
.ToTask(ct);
var finishTask = await Task.WhenAny(confirmTask, speechTask);
if (ct.IsCancellationRequested)
return false;
if (finishTask == confirmTask)
return confirmTask.Result;
if (finishTask == speechTask)
return speechTask.Result.Equals(config.OkText, StringComparison.OrdinalIgnoreCase);
return false;
});
public IObservable<string> Question(PromptConfig config) => Observable.FromAsync<string>(async ct =>
{
TextToSpeech.SpeakAsync(config.Message, ct);
var promptTask = this.dialogs.PromptAsync(config, ct);
var speechTask = this.speech
.ListenUntilPause()
.ToTask(ct);
var finishTask = await Task.WhenAny(promptTask, speechTask);
if (ct.IsCancellationRequested)
return null;
if (finishTask == promptTask)
return promptTask.Result.Text;
if (finishTask == speechTask)
return speechTask.Result;
return null;
});
}
}
| 31.744898 | 140 | 0.568949 | [
"MIT"
] | aritchie/speechrecognition | Plugin.SpeechDialogs/SpeechDialogs.cs | 3,113 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Policy;
using UnityEngine;
[System.Serializable]
public class GenericObjectData
{
public List<Vector3Ser> transformData;
public float[] materialColor;
}
[System.Serializable]
public class SpiningCubeData : GenericObjectData
{
public float spin;
}
[System.Serializable]
public class Vector3Ser
{
public float a, b, c;
public Vector3Ser(Vector3 v)
{
Set(v);
}
public void Set(Vector3 v)
{
a = v.x;
b = v.y;
c = v.z;
}
public Vector3 toVector3()
{
return new Vector3(a, b, c);
}
} | 16.261905 | 49 | 0.635432 | [
"MIT"
] | Math-Man/ProvingGrounds | Assets/Prototypes/SaveLoadSystem/Scripts/GenericObjectData.cs | 685 | 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.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
using System.Security.Cryptography.Pkcs.Tests;
using System.Linq;
namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests
{
public abstract partial class DecryptTests
{
private bool _useExplicitPrivateKey;
public static bool SupportsIndefiniteLengthEncoding { get; } = !PlatformDetection.IsNetFramework;
public DecryptTests(bool useExplicitPrivateKey)
{
_useExplicitPrivateKey = useExplicitPrivateKey;
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_IssuerAndSerial()
{
byte[] content = { 5, 112, 233, 43 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_Ski()
{
byte[] content = { 6, 3, 128, 33, 44 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.SubjectKeyIdentifier);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_Capi()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_256()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha256KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_384()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha384KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_512()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha512KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop("Leaks key on disk if interrupted")]
public void Decrypt_512_FixedValue()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
byte[] message = (
"3082012506092A864886F70D010703A0820116308201120201003181CE3081CB" +
"02010030343020311E301C060355040313155253415368613531324B65795472" +
"616E736665723102102F5D9D58A5F41B844650AA233E68F105300D06092A8648" +
"86F70D01010105000481803163AA33F8F5E033DC03AE98CCEE158199589FC420" +
"19200DCC1D202309CCCAF79CC0278B9502B5709F1311E522DA325338136D3F1E" +
"A271FAEA978CC656A3CB94B1C6A8D7AFC836C3193DB693E8B8767472C2C23125" +
"BA11E7D0623E4C8B848826BBF99EB411CB88B4731740D1AD834F0E4076BAD0D4" +
"BA695CFE8CDB2DE3E77196303C06092A864886F70D010701301D060960864801" +
"650304012A0410280AC7A629BFC9FD6FB24F8A42F094B48010B78CDFECFF32A8" +
"E86D448989382A93E7"
).HexToByteArray();
VerifySimpleDecrypt(message, Certificates.RSASha512KeyTransfer1, new ContentInfo(content));
}
[Fact]
[OuterLoop("Leaks key on disk if interrupted")]
public void Decrypt_512_NoData_FixedValue()
{
// This is the Decrypt_512_FixedData test re-encoded to remove the
// encryptedContentInfo.encryptedContent optional value.
byte[] content = Array.Empty<byte>();
byte[] message = (
"3082011306092A864886F70D010703A0820104308201000201003181CE3081CB" +
"02010030343020311E301C060355040313155253415368613531324B65795472" +
"616E736665723102102F5D9D58A5F41B844650AA233E68F105300D06092A8648" +
"86F70D01010105000481803163AA33F8F5E033DC03AE98CCEE158199589FC420" +
"19200DCC1D202309CCCAF79CC0278B9502B5709F1311E522DA325338136D3F1E" +
"A271FAEA978CC656A3CB94B1C6A8D7AFC836C3193DB693E8B8767472C2C23125" +
"BA11E7D0623E4C8B848826BBF99EB411CB88B4731740D1AD834F0E4076BAD0D4" +
"BA695CFE8CDB2DE3E77196302A06092A864886F70D010701301D060960864801" +
"650304012A0410280AC7A629BFC9FD6FB24F8A42F094B4"
).HexToByteArray();
if (PlatformDetection.IsNetFramework)
{
// On .NET Framework when Array.Empty should be returned an array of 6 zeros is
// returned instead.
content = new byte[6];
}
VerifySimpleDecrypt(message, Certificates.RSASha512KeyTransfer1, new ContentInfo(content));
}
[Fact]
[OuterLoop("Leaks key on disk if interrupted")]
public void Decrypt_512_CekDoesNotDecrypt_FixedValue()
{
// This is the Decrypt_512_NoData_FixedValue test except that the last
// byte of the recipient encrypted key has been changed from 0x96 to 0x95
// (the sequence 7195 identifies the changed byte)
byte[] content = Array.Empty<byte>();
byte[] message = (
"3082011306092A864886F70D010703A0820104308201000201003181CE3081CB" +
"02010030343020311E301C060355040313155253415368613531324B65795472" +
"616E736665723102102F5D9D58A5F41B844650AA233E68F105300D06092A8648" +
"86F70D01010105000481803163AA33F8F5E033DC03AE98CCEE158199589FC420" +
"19200DCC1D202309CCCAF79CC0278B9502B5709F1311E522DA325338136D3F1E" +
"A271FAEA978CC656A3CB94B1C6A8D7AFC836C3193DB693E8B8767472C2C23125" +
"BA11E7D0623E4C8B848826BBF99EB411CB88B4731740D1AD834F0E4076BAD0D4" +
"BA695CFE8CDB2DE3E77195302A06092A864886F70D010701301D060960864801" +
"650304012A0410280AC7A629BFC9FD6FB24F8A42F094B4"
).HexToByteArray();
Assert.ThrowsAny<CryptographicException>(
() => VerifySimpleDecrypt(message, Certificates.RSASha512KeyTransfer1, new ContentInfo(content)));
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_SignedWithinEnveloped()
{
byte[] content =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_EnvelopedWithinEnveloped()
{
byte[] content =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818013"
+ "dc0eb2984a445d04a1f6246b8fe41f1d24507548d449d454d5bb5e0638d75ed101bf78c0155a5d208eb746755fbccbc86923"
+ "8443760a9ae94770d6373e0197be23a6a891f0c522ca96b3e8008bf23547474b7e24e7f32e8134df3862d84f4dea2470548e"
+ "c774dd74f149a56cdd966e141122900d00ad9d10ea1848541294a1302b06092a864886f70d010701301406082a864886f70d"
+ "030704089c8119f6cf6b174c8008bcea3a10d0737eb9").HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7SignedEnveloped), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
public void EncryptToNegativeSerialNumber()
{
CertLoader negativeSerial = Certificates.NegativeSerialNumber;
const string expectedSerial = "FD319CB1514B06AF49E00522277E43C8";
byte[] content = { 1, 2, 3 };
ContentInfo contentInfo = new ContentInfo(content);
EnvelopedCms cms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = negativeSerial.GetCertificate())
{
Assert.Equal(expectedSerial, cert.SerialNumber);
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
cms.Encrypt(recipient);
}
EnvelopedCms cms2 = new EnvelopedCms();
cms2.Decode(cms.Encode());
RecipientInfoCollection recipients = cms2.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, recipientInfo.RecipientIdentifier.Type);
X509IssuerSerial issuerSerial = (X509IssuerSerial)recipientInfo.RecipientIdentifier.Value;
Assert.Equal(expectedSerial, issuerSerial.SerialNumber);
using (X509Certificate2 cert = negativeSerial.TryGetCertificateWithPrivateKey())
{
Assert.Equal(expectedSerial, cert.SerialNumber);
cms2.Decrypt(new X509Certificate2Collection(cert));
}
Assert.Equal(content, cms2.ContentInfo.Content);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes128_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm is Aes128
byte[] encryptedMessage =
("3082011F06092A864886F70D010703A08201103082010C0201003181C83081C5020100302E301A311830160"
+ "603550403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D0609"
+ "2A864886F70D0101073000048180862175CD3B2932235A67C6A025F75CDA1A43B53E785370895BA9AC8D0DD"
+ "318EB36DFAE275B16ABD497FEBBFCF2D4B3F38C75B91DC40941A2CC1F7F47E701EEA2D5A770C485565F8726"
+ "DC0D59DDE17AA6DB0F9384C919FC8BC6CB561A980A9AE6095486FDF9F52249FB466B3676E4AEFE4035C15DC"
+ "EE769F25E4660D4BE664E7F303C06092A864886F70D010701301D060960864801650304010204100A068EE9"
+ "03E085EA5A03D1D8B4B73DD88010740E5DE9B798AA062B449F104D0F5D35").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes192_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes192
byte[] encryptedMessage =
("3082011F06092A864886F70D010703A08201103082010C0201003181C83081C5020100302E301A311830160"
+ "603550403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D0609"
+ "2A864886F70D010107300004818029B82454B4C301F277D7872A14695A41ED24FD37AC4C9942F9EE96774E0"
+ "C6ACC18E756993A38AB215E5702CD34F244E52402DA432E8B79DF748405135E8A6D8CB78D88D9E4C142565C"
+ "06F9FAFB32F5A9A4074E10FCCB0758A708CA758C12A17A4961969FCB3B2A6E6C9EB49F5E688D107E1B1DF3D"
+ "531BC684B944FCE6BD4550C303C06092A864886F70D010701301D06096086480165030401160410FD7CBBF5"
+ "6101854387E584C1B6EF3B08801034BD11C68228CB683E0A43AB5D27A8A4").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082011F06092A864886F70D010703A08201103082010C0201003181C83081C5020100302E301A311830160"
+ "603550403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D0609"
+ "2A864886F70D01010730000481800215BF7505BCD5D083F8EFDA01A4F91D61DE3967779B2F5E4360593D4CB"
+ "96474E36198531A5E20E417B04C5C7E3263C3301DF8FA888FFBECC796500D382858379059C986285AFD605C"
+ "B5DE125487CCA658DF261C836720E2E14440DA60E2F12D6D5E3992A0DB59973929DF6FC23D8E891F97CA956"
+ "2A7AD160B502FA3C10477AA303C06092A864886F70D010701301D060960864801650304012A04101287FE80"
+ "93F3C517AE86AFB95E599D7E80101823D88F47191857BE0743C4C730E39E").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleTripleDes_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is 3DES-CBC
byte[] encryptedMessage =
("3082010C06092A864886F70D010703A081FE3081FB0201003181C83081C5020100302E301A3118301606035"
+ "50403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D06092A86"
+ "4886F70D0101010500048180062F6F16637C8F35B73924AD85BA47D99DBB4800CB8F0C4094F6896050B7C1F"
+ "11CE79BEE55A638EAAE70F2C32C01FC24B8D09D9D574CB7373788C8BC3A4748124154338C74B644A2A11750"
+ "9E97D1B3535FAE70E4E7C8F2F866232CBFC6448E89CF9D72B948EDCF9C9FC9C153BCC7104680282A4BBBC1E"
+ "E367F094F627EE45FCD302B06092A864886F70D010701301406082A864886F70D030704081E3F12D42E4041"
+ "58800877A4A100165DD0F2").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_Ski()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type SubjectKeyIdentifier. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082010306092A864886F70D010703A081F53081F20201023181AE3081AB0201028014F2008AA9FA3742E83"
+ "70CB1674CE1D1582921DCC3300D06092A864886F70D010101050004818055F258073615B95426A7021E1B30"
+ "9CFE8DD135B58D29F174B9FE19AE80CFC84621BCE3DBD63A5422AF30A6FAA3E2DFC05CB1AB5AB4FBA6C84EB"
+ "1C2E17D5BE5C4959DBE8F96BF1A9701F55B697843032EEC7AFEC58A36815168F017DCFD70C74AD05C48B5E4"
+ "D9DDEE409FDC9DC3326B6C5BA9F433A9E031FF9B09473176637F50303C06092A864886F70D010701301D060"
+ "960864801650304012A0410314DA87435ED110DFE4F52FA70CEF7B080104DDA6C617338DEBDD10913A9141B"
+ "EE52").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaTransferCapi()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransferCapi1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012306092A864886F70D010703A0820114308201100201003181CC3081C90201003032301E311C301A0"
+ "60355040313135253414B65795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA"
+ "300D06092A864886F70D01010730000481804F3F4A6707B329AB9A7343C62F20D5C1EAF4E74ECBB2DC66D1C"
+ "642FC4AA3E40FC4C13547C6C9F73D525EE2FE4147B2043B8FEBF8604C0E4091C657B48DFD83A322F0879580"
+ "FA002C9B27AD1FCF9B8AF24EDDA927BB6728D11530B3F96EBFC859ED6B9F7B009F992171FACB587A7D05E8B"
+ "467B3A1DACC08B2F3341413A7E96576303C06092A864886F70D010701301D060960864801650304012A0410"
+ "6F911E14D9D991DAB93C0B7738D1EC208010044264D201501735F73052FFCA4B2A95").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransferCapi1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaSha256()
{
// Message encrypted on framework for a recipient using the certificate returned by
// Certificates.RSASha256KeyTransfer1.GetCertificate() and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012506092A864886F70D010703A0820116308201120201003181CE3081CB02010030343020311E301C0"
+ "60355040313155253415368613235364B65795472616E7366657231021072C6C7734916468C4D608253DA01"
+ "7676300D06092A864886F70D01010730000481805C32FA32EBDCFFC3595166EEDACFC9E9D60842105B581E1"
+ "8B85DE1409F4C999995637153480438530955EE4481A3B27B866FF4E106A525CDFFC6941BDD01EFECCC6CCC"
+ "82A3D7F743F7543AB20A61A7831FE4DFB24A1652B072B3758FE4B2588D3B94A29575B6422DC5EF52E432565"
+ "36CA25A11BB92817D61FEAFBDDDEC6EE331303C06092A864886F70D010701301D060960864801650304012A"
+ "041021D59FDB89C13A3EC3766EF32FB333D080105AE8DEB71DF50DD85F66FEA63C8113F4").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSASha256KeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaSha384()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSASha384KeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012506092A864886F70D010703A0820116308201120201003181CE3081CB02010030343020311E301C0"
+ "60355040313155253415368613338344B65795472616E736665723102103C724FB7A0159A9345CAAC9E3DF5"
+ "F136300D06092A864886F70D010107300004818011C1B85914331C005EA89E30D00364821B29BC0C459A22D"
+ "917494A1092CDBDA2022792E46C5E88BAD0EE3FD4927B856722311F9B17934FB29CAB8FE595C2AB2B20096B"
+ "9E2FC6F9D7B92125F571CBFC945C892EE4764D9B63369350FD2DAEFE455B367F48E100CB461F112808E792A"
+ "8AA49B66C79E511508A877530BBAA896696303C06092A864886F70D010701301D060960864801650304012A"
+ "0410D653E25E06BFF2EEB0BED4A90D00FE2680106B7EF143912ABA5C24F5E2C151E59D7D").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSASha384KeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaSha512()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSASha512KeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012506092A864886F70D010703A0820116308201120201003181CE3081CB02010030343020311E301C0"
+ "60355040313155253415368613531324B65795472616E736665723102102F5D9D58A5F41B844650AA233E68"
+ "F105300D06092A864886F70D01010730000481802156D42FF5ED2F0338302E7298EF79BA1D04E20E68B079D"
+ "B3239120E1FC03FEDA8B544F59142AACAFBC5E58205E8A0D124AAD17B5DCAA39BFC6BA634E820DE623BFDB6"
+ "582BC48AF1B3DEF6849A57D2033586AF01079D67C9AB3AA9F6B51754BCC479A19581D4045EBE23145370219"
+ "98ECB6F5E1BCF8D6BED6A75FE957A40077D303C06092A864886F70D010701301D060960864801650304012A"
+ "04100B696608E489E7C35914D0A3DB9EB27F80103D362181B54721FB2CB7CE461CB31030").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSASha512KeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimple_ExplicitSki()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer_ExplicitSki.GetCertificate()
// and of type SubjectKeyIdentifier. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082018806092A864886F70D010703A082017930820175020102318201303082012C020102801401952851C"
+ "55DB594B0C6167F5863C5B6B67AEFE6300D06092A864886F70D010101050004820100269EAF029262C87125"
+ "314DD3FB02302FA212EB3CC06F73DF1474382BBA2A92845F39FF5A7F5020482849C36B4BC6BC82F7AF0E2E3"
+ "9143548CC32B93B72EF0659C6895F77E6B5839962678532392185C9431658B34D1ABD31F64F4C4A9B348A77"
+ "56783D60244519ADDD33560405E9377A91617127C2EECF2BAE53AB930FC13AFD25723FB60DB763286EDF6F1"
+ "187D8124B6A569AA2BD19294A7D551A0D90F8436274690231520A2254C19EA9BF877FC99566059A29CDF503"
+ "6BEA1D517916BA2F20AC9F1D8F164B6E8ACDD52BA8B2650EBBCC2ED9103561E11AF422D10DF7405404195FA"
+ "EF79A1FDC680F3A3DC395E3E9C0B10394DF35AE134E6CB719E35152F8E5303C06092A864886F70D01070130"
+ "1D060960864801650304012A041085072D8771A2A2BB403E3236A7C60C2A80105C71A04E73C57FE75C1DEDD"
+ "94B57FD01").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer_ExplicitSki;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimple_Pkcs7Signed_GeneratedOnWindows()
{
byte[] expectedContent =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), expectedContent);
byte[] encodedMessage = Convert.FromBase64String(
"MIIERwYJKoZIhvcNAQcDoIIEODCCBDQCAQAxgcwwgckCAQAwMjAeMRwwGgYDVQQDExNSU0FLZXlU" +
"cmFuc2ZlckNhcGkxAhBdL//4Y7q8m008gKsXikzKMA0GCSqGSIb3DQEBAQUABIGAngdmU69zGsgJ" +
"mx+hXmTjlefr1oazKRK8VGOeqNMm++J3yHxwz68CLoN4FIEyS/HE3NQE6qb3M80HOpk5fmVVMw7Z" +
"3mrsZlPLOEjJIxEFqAC/JFEzvyE/BL+1OvwRoHpxHsAvZNlz5f9g18wQVE7X5TkkbOJV/6F2disK" +
"H0jik68wggNeBgkqhkiG9w0BBwIwHQYJYIZIAWUDBAEqBBDr3I8NYAnetX+2h9D/nVAggIIDMOlW" +
"7mDuuScuXhCXgZaPy0/zEWy/sYDzxhj1G1X2qBwhB7m6Ez6giibAEYwfRNYaOiVIitIJAUU9LSKg" +
"n0FL1o0eCcgvo04w+zoaBH8pFFk78kuR+T73kflz+O3Eno1pIFpy+2cz2B0QvQSC7lYikbZ4J+/C" +
"7F/uqRoK7sdafNdyUnKhDL+vvP6ToGf9C4g0TjoFEC2ycyJxIBh1F57pqjht6HMQcYm+/fQoBtkt" +
"NrvZxJPlBhbQad/9pSCd0G6NDoPnDuFAicaxGVa7yI2BbvGTCc6NSnbdCzv2EgvsI10Yko+XO4/i" +
"oPnk9pquZBzC3p61XRKbBDrd5RsbkvPDXUHJKD5NQ3W3z9Bnc3bjNyilgDSIB01dE4AcWzdg+RGb" +
"TA7iAbAQKp2zjxb/prmxw1mhO9g6OkDovSTqmQQt7MlHFYFcX9wH8yEe+huIechmiy7famofluJX" +
"vBIz4m3JozlodyNX0nu9QwW58WWcFu6OyoPjFhlB+tLIHUElq9/AAEgwwgfsAj6jEQaHiFG+CYSJ" +
"RjX9+DHFJXMDyzW+eJw8Z/mvbZzzKF553xlAGpfUHHq4CywTyVTHn4nu9HPOeFzoirj1lzFvqmQd" +
"Dgp3T8NOPrns9ZIUBmdNNs/vUxNZqEeN4d0nD5lBG4aZnjsxr4i25rR3Jpe3kKrFtJQ74efkRM37" +
"1ntz9HGiA95G41fuaMw7lgOOfTL+AENNvwRGRCAhinajvQLDkFEuX5ErTtmBxJWU3ZET46u/vRiK" +
"NiRteFiN0hLv1jy+RJK+d+B/QEH3FeVMm3Tz5ll2LfO2nn/QR51hth7qFsvtFpwQqkkhMac6dMf/" +
"bb62pZY15U3y2x5jSn+MZVrNbL4ZK/JO5JFomqKVRjLH1/IZ+kuFNaaTrKFWB4U2gxrMdcjMCZvx" +
"ylbuf01Ajxo74KhPY9sIRztG4BU8ZaE69Ke50wJTE3ulm+g6hzNECdQS/yjuA8AUReGRj2NH/U4M" +
"lEUiR/rMHB/Mq/Vj6lsRFEVxHJSzek6jvrQ4UzVgWGrH4KnP3Rca8CfBTQX79RcZPu+0kI3KI+4H" +
"0Q+UBbb72FHnWsw3uqPEyA==");
CertLoader certLoader = Certificates.RSAKeyTransferCapi1;
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimple_Pkcs7Signed_GeneratedOnLinux()
{
byte[] expectedContent =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), expectedContent);
byte[] encodedMessage = Convert.FromBase64String(
"MIIERwYJKoZIhvcNAQcDoIIEODCCBDQCAQAxgcwwgckCAQAwMjAeMRwwGgYDVQQDExNSU0FLZXlU" +
"cmFuc2ZlckNhcGkxAhBdL//4Y7q8m008gKsXikzKMA0GCSqGSIb3DQEBAQUABIGAfsH5F4ZlwIcH" +
"nzqn8sOn+ZwK884en7HZrQbgEfedy5ti0ituKn70yTDz4iuNJtpguukCfCAsOT/n3eQn+T6etIa9" +
"byRGQst3F6QtgjAzdb5P1N6c5Mpz1o6k0mbNP/f0FqAaNtuAOnYwlEMwWOz9x4eEYpOhhlc6agRG" +
"qWItNVgwggNeBgkqhkiG9w0BBwIwHQYJYIZIAWUDBAEqBBCA8qaTiT+6IkrO8Ks9WOBggIIDMIkr" +
"7OGlPd3CfzO2CfJA3Sis/1ulDm1ioMCS9V5kLHVx4GWDETORG/YTPA54luxJkvIdU5VwO86+QuXf" +
"rgaly38XHTLZv+RBxUwCaWI0pgvaykEki5CnDu4j9uRQxqz6iU5bY6SKxG3bwcnUzGhWFdQVcNJn" +
"xzuMEcbrix5zfqmoeqemaYyqVqgMPNOnc5kmMOqHrha76qMdbYOSpwx81zYwstBlg+S9+AgOMR+W" +
"qrV9aXJTovjiJEVHPEPJFx0v/wCthhXso51mSU091Cs8qVfvokzlzXcK2dPF5d8EdmZCcmHsoq35" +
"/DfAL4DkfKucwiP9W7rT1a2BmVMquFTMI+KXyDvNhMVasjhKq5eM2G+oUDc3kGa3akaPZ+hNEHA+" +
"BNAS7iIpRft2GMNfTqpkBqnS6pB0+SSf02/JVkcFuHXZ9oZJsvZRm8M1i4WdVauBJ34rInQBdhaO" +
"yaFDx69tBvolclYnMzvdHLiP2TZbiR6kM0vqD1DGjEHNDE+m/jxL7HXcNotW84J9CWlDnm9zaNhL" +
"sB4PJNiNjKhkAsO+2HaNWlEPrmgmWKvNi/Qyrz1qUryqz2/2HGrFDqmjTeEf1+yy35N3Pqv5uvAj" +
"f/ySihknnAh77nI0yOPy0Uto+hbO+xraeujrEifaII8izcz6UG6LHNPxOyscne7HNcqPSAFLsNFJ" +
"1oOlKO0SwhPkGQsk4W5tjVfvLvJiPNcL7SY/eof4vVsRRwX6Op5WUjhJIagY1Vij+4hOcn5TqdmU" +
"OZDh/FC3x4DI556BeMfbWxHNlGvptROQwQ6BasfdiVWCWzMHwLpz27Y47vKbMQ+8TL9668ilT83f" +
"6eo6mHZ590pzuDB+gFrjEK44ov0rvHBK5jHwnSObQvChN0ElizWBdMSUbx9SkcnReH6Fd29SSXdu" +
"RaVspnhmFNXWg7qGYHpEChnIGSr/WIKETZ84f7FRCxCNSYoQtrHs0SskiEGJYEbB6KDMFimEZ4YN" +
"b4cV8VLC9Pxa1Qe1Oa05FBzG2DAP2PfObeKR34afF5wo6vIZfQE0WWoPo9YS326vz1iA5rE0F6qw" +
"zCNmZl8+rW6x73MTEcWhvg==");
CertLoader certLoader = Certificates.RSAKeyTransferCapi1;
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaepSha256()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha256 --aes256 -keyopt rsa_oaep_md:sha256
byte[] encodedMessage = Convert.FromBase64String(
"MIIBUAYJKoZIhvcNAQcDoIIBQTCCAT0CAQAxgfkwgfYCAQAwNDAgMR4wHAYDVQQD" +
"ExVSU0FTaGEyNTZLZXlUcmFuc2ZlcjECEHLGx3NJFkaMTWCCU9oBdnYwOAYJKoZI" +
"hvcNAQEHMCugDTALBglghkgBZQMEAgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUD" +
"BAIBBIGAuobMSz1Q4OHRX2aX9AutOPdZX2phA6WATQTOKOWCD//LQwrHYtuNIPAG" +
"Tld+JTZ1EMQD9PoEMyxdkllyie2dn/PSvnE0q/WU+IrHzGzoWofuNs9M6g9Gvpg5" +
"qCGAXK9cL3WkZ9S+M1r6BqlCLwU03bJr6292PiLyjIH80CdMuRUwPAYJKoZIhvcN" +
"AQcBMB0GCWCGSAFlAwQBKgQQezbMDGrefOaUPpfIXBpw7oAQazcOoj9GkvzZMR9Z" +
"NU22nQ==");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
VerifySimpleDecrypt(encodedMessage, Certificates.RSASha256KeyTransfer1, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaepSha384()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha384 --aes256 -keyopt rsa_oaep_md:sha384
byte[] encodedMessage = Convert.FromBase64String(
"MIIB0AYJKoZIhvcNAQcDoIIBwTCCAb0CAQAxggF4MIIBdAIBADAxMCQxIjAgBgNV" +
"BAMMGVJTQTIwNDhTaGEyNTZLZXlUcmFuc2ZlcjECCQDc5NcqfzyljjA4BgkqhkiG" +
"9w0BAQcwK6ANMAsGCWCGSAFlAwQCAqEaMBgGCSqGSIb3DQEBCDALBglghkgBZQME" +
"AgIEggEAIqqdx5zCFnGSNzV+/N0Mu8S8CVABuPv+RcpV8fiFj5TLcHe84lYI/ptr" +
"F7FwyQRfHVDWgJrJqDS/wYfzD6Ar8qLRdfBswCotn/QYm/VLzBXNRLM402t3lWq+" +
"2pgucyGghpnf2I1aZo8U9hJGUOUPISQqkiol9I1O/JYfo9B7sBTW8Vp22W/c8nTI" +
"huQx+tOhzqGAMElrsd+cEaTiVqAMmNU20B2du0wWs0nckzg4KLbz2g/g8L699luU" +
"t8OluQclxfVgruLY28RY8R5w7OH2LZSEhyKxq3PG3KqXqR+E1MCkpdg8PhTJkeYO" +
"Msz1J70aVA8L8nrhtS9xXq0dd8jyfzA8BgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEq" +
"BBA/xHlg1Der3mxzmvPvUcqogBDEEZmz+ECEWMeNGBv/Cw82");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
VerifySimpleDecrypt(encodedMessage, Certificates.RSA2048Sha256KeyTransfer1, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaepSha512()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha512 --aes256 -keyopt rsa_oaep_md:sha512
byte[] encodedMessage = Convert.FromBase64String(
"MIIB0AYJKoZIhvcNAQcDoIIBwTCCAb0CAQAxggF4MIIBdAIBADAxMCQxIjAgBgNV" +
"BAMMGVJTQTIwNDhTaGEyNTZLZXlUcmFuc2ZlcjECCQDc5NcqfzyljjA4BgkqhkiG" +
"9w0BAQcwK6ANMAsGCWCGSAFlAwQCA6EaMBgGCSqGSIb3DQEBCDALBglghkgBZQME" +
"AgMEggEAc6QULhpkV7C63HhSbdYM7QFDTtRj8Wch3QHrFB0jIYlLGxcMuOB3Kw6f" +
"P1Q4W8qmVJgH+dyeKcpu2J6OrjlZVDtK166DrmKCflTMCGhCsPsmCMbKlpBihuXo" +
"7xQ13Fzs9QhudY/B/jUNjOTb3nONBqOdDJVLFsoMxm9cJqnDcdFPJVgIFl3IQW7X" +
"I1ZFdnS6FVKybR94jU4ASx8awQ+zDOgnCsyZ7t5cOwca2NgyQxZCf92WEJjdXqbl" +
"3ax/ULfSWD104Fp4N7lf8Z9BAkjIVJh3EeROzWgDkP5FQ9bDqkn3x+IlVKHfu+3r" +
"fmaUWI/sZCMXnUnLFEEILwCBcZlvBzA8BgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEq" +
"BBDJhteA5Rpug15ksuJ9o/9vgBDQzvGRyFU8AKtfSpF6jBkB");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
VerifySimpleDecrypt(encodedMessage, Certificates.RSA2048Sha256KeyTransfer1, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaepSha1_Default()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha1 --aes256 -keyopt rsa_oaep_md:sha1
byte[] encodedMessage = Convert.FromBase64String(
"MIIBJQYJKoZIhvcNAQcDoIIBFjCCARICAQAxgc4wgcsCAQAwNDAgMR4wHAYDVQQD" +
"ExVSU0FTaGEyNTZLZXlUcmFuc2ZlcjECEHLGx3NJFkaMTWCCU9oBdnYwDQYJKoZI" +
"hvcNAQEHMAAEgYCLNNE4H03P0aP1lBDwKrm549DajTVSeyseWxv7TDDdVVWOTNgh" +
"c5OEVT2lmzxWD6lq28aZqmV8PPxJhvOZl4mnY9ycA5hgwmFRdKyI2hBTWQL8GQcF" +
"nYKc54BMKNaJsfIUIwN89knw7AEYEchGF+USKgQY1qsvdag6ZNBuhs5uwTA8Bgkq" +
"hkiG9w0BBwEwHQYJYIZIAWUDBAEqBBB/OyPGgn42q2XoDE4o8+2ggBDRXtH4O1xQ" +
"BHevgmD2Ev8V");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
VerifySimpleDecrypt(encodedMessage, Certificates.RSASha256KeyTransfer1, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaep_MaskGenFunc_HashFunc_Mismatch()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha1 --aes256 -keyopt rsa_oaep_md:sha256
byte[] encodedMessage = Convert.FromBase64String(
"MIIBNAYJKoZIhvcNAQcDoIIBJTCCASECAQAxgd0wgdoCAQAwNDAgMR4wHAYDVQQD" +
"ExVSU0FTaGEyNTZLZXlUcmFuc2ZlcjECEHLGx3NJFkaMTWCCU9oBdnYwHAYJKoZI" +
"hvcNAQEHMA+gDTALBglghkgBZQMEAgEEgYCw85yDulRtibSZm0xy1mOTIGjDu4yy" +
"pMT++3dV5Cy2GF4vp3mxp89Ylq2boYZ8b4B86IcJqUfyU/fG19O+vXyjn/0VUP3f" +
"OjMM71oqvQc/Qou/LvgDYQZY1koDldoeH89waZ1hgFaVpFEwGZUPSHmzgfsxMOpj" +
"RoToifiTsP3PkjA8BgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBCCufI08zVL4KVc" +
"WgKwZxCNgBA9M9KpJHmKwm5dMtvdcs/Q");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
Assert.ThrowsAny<CryptographicException>(
() => VerifySimpleDecrypt(encodedMessage, Certificates.RSASha256KeyTransfer1, expectedContentInfo));
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaep_PSpecified_NonDefault()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep \
// -keyopt rsa_mgf1_md:sha1 --aes256 -keyopt rsa_oaep_md:sha1 -keyopt rsa_oaep_label:0102030405
byte[] encodedMessage = Convert.FromBase64String(
"MIIBOwYJKoZIhvcNAQcDoIIBLDCCASgCAQAxgeQwgeECAQAwNDAgMR4wHAYDVQQD" +
"ExVSU0FTaGEyNTZLZXlUcmFuc2ZlcjECEHLGx3NJFkaMTWCCU9oBdnYwIwYJKoZI" +
"hvcNAQEHMBaiFDASBgkqhkiG9w0BAQkEBQECAwQFBIGAoJ7P69rwtexRcLbK+K8z" +
"UrKROLk2tVU8xGA056j8o2GfqQPxGsHl1w8Q3lsnSPsjGHY30+KYmQMQrZJd5zIW" +
"2OpgriYeqnHUwNCd9CrRFVvEqqACZlzTw/L+DgeDXwSNPRzNghjIqWo79FFT9kRI" +
"DHUB10A+sIZevVYtFrWxbVQwPAYJKoZIhvcNAQcBMB0GCWCGSAFlAwQBKgQQfxMe" +
"56xuPm9lTJYYozmQ6oAQd1RIE2hhgx1kdJmIW1Z4/w==");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
Assert.ThrowsAny<CryptographicException>(
() => VerifySimpleDecrypt(encodedMessage, Certificates.RSASha256KeyTransfer1, expectedContentInfo));
}
[Fact]
public void DecryptEnvelopedOctetStringWithDefiniteLength()
{
// enveloped content consists of 5 bytes: <id: 1 byte><length: 1 byte><content: 3 bytes>
// <id>:
// 04 - Octet string
// 30 - Sequence
// <length>: 03 => length is 3 (encoded with definite length)
// <content>: 010203
// Note: we expect invalid ASN.1 sequence
byte[] content = "0403010203".HexToByteArray();
byte[] expectedContent = "3003010203".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedOctetStringWithInefficientlyEncodedLength()
{
// enveloped content consists of 5 or 6 bytes: <id: 1 byte><length: 1 or 2 bytes><content: 3 bytes>
// <id>:
// 04 - Octet string
// 30 - Sequence
// <length>: 03 => length is 3 (encoded with definite length)
// 81 03 => length is 3 (encoded with inefficiently encoded length)
// <content>: 010203
// Note: we expect invalid ASN.1 sequence
byte[] content = "048103010203".HexToByteArray();
byte[] expectedContent = "3003010203".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "netfx does not allow it")]
public void DecryptEnvelopedEmptyArray()
{
byte[] content = Array.Empty<byte>();
byte[] expectedContent = "3000".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedEmptyOctetString()
{
byte[] content = "0400".HexToByteArray();
byte[] expectedContent = "3000".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedOctetStringWithExtraData()
{
byte[] content = "04010203".HexToByteArray();
byte[] expectedContent = "300102".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedDataWithNonPkcs7Oid()
{
byte[] content = "3003010203".HexToByteArray();
string nonPkcs7Oid = "0.0";
ContentInfo contentInfo = new ContentInfo(new Oid(nonPkcs7Oid), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsIndefiniteLengthEncoding))]
public void DecryptEnvelopedEmptyOctetStringWithIndefiniteLength()
{
byte[] content = "30800000".HexToByteArray();
byte[] expectedContent = "3000".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[ConditionalFact(nameof(SupportsIndefiniteLengthEncoding))]
public void DecryptEnvelopedOctetStringWithIndefiniteLength()
{
byte[] content = "308004000000".HexToByteArray();
byte[] expectedContent = "30020400".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
private void TestSimpleDecrypt_RoundTrip(CertLoader certLoader, ContentInfo contentInfo, string algorithmOidValue, SubjectIdentifierType type, ContentInfo expectedContentInfo = null)
{
// Deep-copy the contentInfo since the real ContentInfo doesn't do this. This defends against a bad implementation changing
// our "expectedContentInfo" to match what it produces.
expectedContentInfo = expectedContentInfo ?? new ContentInfo(new Oid(contentInfo.ContentType), (byte[])(contentInfo.Content.Clone()));
string certSubjectName;
byte[] encodedMessage;
byte[] originalCopy = (byte[])(contentInfo.Content.Clone());
using (X509Certificate2 certificate = certLoader.GetCertificate())
{
certSubjectName = certificate.Subject;
AlgorithmIdentifier alg = new AlgorithmIdentifier(new Oid(algorithmOidValue));
EnvelopedCms ecms = new EnvelopedCms(contentInfo, alg);
CmsRecipient cmsRecipient = new CmsRecipient(type, certificate);
ecms.Encrypt(cmsRecipient);
Assert.Equal(originalCopy.ByteArrayToHex(), ecms.ContentInfo.Content.ByteArrayToHex());
encodedMessage = ecms.Encode();
}
// We don't pass "certificate" down because it's expected that the certificate used for encrypting doesn't have a private key (part of the purpose of this test is
// to ensure that you don't need the recipient's private key to encrypt.) The decrypt phase will have to locate the matching cert with the private key.
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
internal void VerifySimpleDecrypt(byte[] encodedMessage, CertLoader certLoader, ContentInfo expectedContent)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
using (X509Certificate2 cert = certLoader.TryGetCertificateWithPrivateKey())
{
if (cert == null)
return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
#if NETCOREAPP // API not present on netfx
if (_useExplicitPrivateKey)
{
using (X509Certificate2 pubCert = certLoader.GetCertificate())
{
RecipientInfo recipient = ecms.RecipientInfos.Cast<RecipientInfo>().Where((r) => r.RecipientIdentifier.MatchesCertificate(cert)).Single();
ecms.Decrypt(recipient, cert.PrivateKey);
}
}
else
#endif
{
X509Certificate2Collection extraStore = new X509Certificate2Collection(cert);
ecms.Decrypt(extraStore);
}
ContentInfo contentInfo = ecms.ContentInfo;
Assert.Equal(expectedContent.ContentType.Value, contentInfo.ContentType.Value);
Assert.Equal(expectedContent.Content.ByteArrayToHex(), contentInfo.Content.ByteArrayToHex());
}
}
}
}
| 61.989547 | 190 | 0.710565 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Security.Cryptography.Pkcs/tests/EnvelopedCms/DecryptTests.cs | 53,373 | C# |
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.LayoutRules
{
using System.Threading;
using System.Threading.Tasks;
using StyleCop.Analyzers.LayoutRules;
using TestHelper;
using Xunit;
/// <summary>
/// Unit tests for <see cref="SA1500BracesForMultiLineStatementsMustNotShareLine"/>.
/// </summary>
public partial class SA1500UnitTests
{
/// <summary>
/// Verifies that no diagnostics are reported for the valid do ... while statements defined in this test.
/// </summary>
/// <remarks>
/// These are valid for SA1500 only, some will report other diagnostics from the layout (SA15xx) series.
/// </remarks>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestDoWhileValidAsync()
{
var testCode = @"public class Foo
{
private void Bar()
{
var x = 0;
// Valid do ... while #1
do
{
}
while (x == 0);
// Valid do ... while #2
do
{
x = 1;
}
while (x == 0);
// Valid do ... while #3 (Valid only for SA1500)
do { } while (x == 0);
// Valid do ... while #4 (Valid only for SA1500)
do { x = 1; } while (x == 0);
// Valid do ... while #5 (Valid only for SA1500)
do
{ x = 1; } while (x == 0);
}
}";
await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
/// <summary>
/// Verifies that diagnostics will be reported for all invalid do ... while statement definitions.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestDoWhileInvalidAsync()
{
var testCode = @"public class Foo
{
private void Bar()
{
var x = 0;
// Invalid do ... while #1
do
{
} while (x == 0);
// Invalid do ... while #2
do {
}
while (x == 0);
// Invalid do ... while #3
do {
} while (x == 0);
// Invalid do ... while #4
do
{
x = 1;
} while (x == 0);
// Invalid do ... while #5
do
{
x = 1; }
while (x == 0);
// Invalid do ... while #6
do
{
x = 1; } while (x == 0);
// Invalid do ... while #7
do
{ x = 1;
}
while (x == 0);
// Invalid do ... while #8
do
{ x = 1;
} while (x == 0);
// Invalid do ... while #9
do {
x = 1;
}
while (x == 0);
// Invalid do ... while #10
do {
x = 1;
} while (x == 0);
// Invalid do ... while #11
do {
x = 1; }
while (x == 0);
// Invalid do ... while #12
do {
x = 1; } while (x == 0);
// Invalid do ... while #13
do { x = 1;
}
while (x == 0);
// Invalid do ... while #14
do { x = 1;
} while (x == 0);
}
}";
var fixedTestCode = @"public class Foo
{
private void Bar()
{
var x = 0;
// Invalid do ... while #1
do
{
}
while (x == 0);
// Invalid do ... while #2
do
{
}
while (x == 0);
// Invalid do ... while #3
do
{
}
while (x == 0);
// Invalid do ... while #4
do
{
x = 1;
}
while (x == 0);
// Invalid do ... while #5
do
{
x = 1;
}
while (x == 0);
// Invalid do ... while #6
do
{
x = 1;
}
while (x == 0);
// Invalid do ... while #7
do
{
x = 1;
}
while (x == 0);
// Invalid do ... while #8
do
{
x = 1;
}
while (x == 0);
// Invalid do ... while #9
do
{
x = 1;
}
while (x == 0);
// Invalid do ... while #10
do
{
x = 1;
}
while (x == 0);
// Invalid do ... while #11
do
{
x = 1;
}
while (x == 0);
// Invalid do ... while #12
do
{
x = 1;
}
while (x == 0);
// Invalid do ... while #13
do
{
x = 1;
}
while (x == 0);
// Invalid do ... while #14
do
{
x = 1;
}
while (x == 0);
}
}";
DiagnosticResult[] expectedDiagnostics =
{
// Invalid do ... while #1
this.CSharpDiagnostic().WithLocation(10, 9),
// Invalid do ... while #2
this.CSharpDiagnostic().WithLocation(13, 12),
// Invalid do ... while #3
this.CSharpDiagnostic().WithLocation(18, 12),
this.CSharpDiagnostic().WithLocation(19, 9),
// Invalid do ... while #4
this.CSharpDiagnostic().WithLocation(25, 9),
// Invalid do ... while #5
this.CSharpDiagnostic().WithLocation(30, 20),
// Invalid do ... while #6
this.CSharpDiagnostic().WithLocation(36, 20),
// Invalid do ... while #7
this.CSharpDiagnostic().WithLocation(40, 9),
// Invalid do ... while #8
this.CSharpDiagnostic().WithLocation(46, 9),
this.CSharpDiagnostic().WithLocation(47, 9),
// Invalid do ... while #9
this.CSharpDiagnostic().WithLocation(50, 12),
// Invalid do ... while #10
this.CSharpDiagnostic().WithLocation(56, 12),
this.CSharpDiagnostic().WithLocation(58, 9),
// Invalid do ... while #11
this.CSharpDiagnostic().WithLocation(61, 12),
this.CSharpDiagnostic().WithLocation(62, 20),
// Invalid do ... while #12
this.CSharpDiagnostic().WithLocation(66, 12),
this.CSharpDiagnostic().WithLocation(67, 20),
// Invalid do ... while #13
this.CSharpDiagnostic().WithLocation(70, 12),
// Invalid do ... while #14
this.CSharpDiagnostic().WithLocation(75, 12),
this.CSharpDiagnostic().WithLocation(76, 9),
};
await this.VerifyCSharpDiagnosticAsync(testCode, expectedDiagnostics, CancellationToken.None).ConfigureAwait(false);
await this.VerifyCSharpDiagnosticAsync(fixedTestCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
await this.VerifyCSharpFixAsync(testCode, fixedTestCode).ConfigureAwait(false);
}
}
}
| 24.065147 | 136 | 0.442339 | [
"Apache-2.0"
] | jnm2/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers.Test/LayoutRules/SA1500/SA1500UnitTests.DoWhiles.cs | 7,390 | C# |
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace FlatBeats.ViewModels
{
using Flatliner.Phone.ViewModels;
public class ListItemViewModel : ViewModel
{
private bool isFirstItem;
public bool IsFirstItem
{
get
{
return this.isFirstItem;
}
set
{
if (this.isFirstItem == value)
{
return;
}
this.isFirstItem = value;
this.OnPropertyChanged("IsFirstItem");
}
}
private bool isLastItem;
public bool IsLastItem
{
get
{
return this.isLastItem;
}
set
{
if (this.isLastItem == value)
{
return;
}
this.isLastItem = value;
this.OnPropertyChanged("IsLastItem");
}
}
}
}
| 22.101695 | 55 | 0.465491 | [
"MIT"
] | FlatlinerDOA/FlatBeats | FlatBeats.Framework/ListItemViewModel.cs | 1,306 | C# |
using System;
using System.Linq;
using Sally7.ValueConversion;
using Xunit;
namespace Sally7.Tests
{
public class ArrayConversionTests
{
[Theory]
[InlineData(new short[] { 1 })]
[InlineData(new short[] { 1, 1 << 8 })]
public void ConvertToShortArray(short[] value)
{
var bytes = value.SelectMany(v =>
{
var b = BitConverter.GetBytes(v);
if (BitConverter.IsLittleEndian) Array.Reverse(b);
return b;
}).ToArray();
var converter = ConverterFactory.GetFromPlcConverter<short[]>();
var result = new short[value.Length];
converter(ref result, bytes, value.Length);
Assert.Equal(value, result);
}
[Theory]
[InlineData(new int[] { 1 })]
[InlineData(new int[] { 1, 1 << 8, 1 << 16, 1 << 24 })]
public void ConvertToIntArray(int[] value)
{
var bytes = value.SelectMany(v =>
{
var b = BitConverter.GetBytes(v);
if (BitConverter.IsLittleEndian) Array.Reverse(b);
return b;
}).ToArray();
var converter = ConverterFactory.GetFromPlcConverter<int[]>();
var result = new int[value.Length];
converter(ref result, bytes, value.Length);
Assert.Equal(value, result);
}
[Theory]
[InlineData(new long[] { 1 })]
[InlineData(new long[] { 1, 1 << 8, 1 << 16, 1 << 24, 1 << 32, 1 << 40, 1 << 48, 1 << 56 })]
public void ConvertToLongArray(long[] value)
{
var bytes = value.SelectMany(v =>
{
var b = BitConverter.GetBytes(v);
if (BitConverter.IsLittleEndian) Array.Reverse(b);
return b;
}).ToArray();
var converter = ConverterFactory.GetFromPlcConverter<long[]>();
var result = new long[value.Length];
converter(ref result, bytes, value.Length);
Assert.Equal(value, result);
}
[Theory]
[InlineData(new float[] { 3.14f })]
[InlineData(new float[] { 2.81f, 3.14f })]
public void ConvertToFloatArray(float[] value)
{
var bytes = value.SelectMany(v =>
{
var b = BitConverter.GetBytes(v);
if (BitConverter.IsLittleEndian) Array.Reverse(b);
return b;
}).ToArray();
var converter = ConverterFactory.GetFromPlcConverter<float[]>();
var result = new float[value.Length];
converter(ref result, bytes, value.Length);
Assert.Equal(value, result);
}
[Theory]
[InlineData(new double[] { 3.14 })]
[InlineData(new double[] { 2.81, 3.14 })]
public void ConvertToDoubleArray(double[] value)
{
var bytes = value.SelectMany(v =>
{
var b = BitConverter.GetBytes(v);
if (BitConverter.IsLittleEndian) Array.Reverse(b);
return b;
}).ToArray();
var converter = ConverterFactory.GetFromPlcConverter<double[]>();
var result = new double[value.Length];
converter(ref result, bytes, value.Length);
Assert.Equal(value, result);
}
}
}
| 32.122642 | 100 | 0.517768 | [
"MIT"
] | gfoidl/Sally7 | Sally7.Tests/ArrayConversionTests.cs | 3,407 | C# |
// ***********************************************************************
// Assembly : OpenAC.Net.Core
// Author : RFTD
// Created : 03-21-2014
//
// Last Modified By : RFTD
// Last Modified On : 01-30-2015
// ***********************************************************************
// <copyright file="NoLoggingLogger.cs" company="OpenAC .Net">
// The MIT License (MIT)
// Copyright (c) 2014 - 2022 Projeto OpenAC .Net
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
namespace OpenAC.Net.Core.Logging
{
/// <summary>
/// Classe NoLoggingLogger.
/// </summary>
public class NoLoggingLogger : IOpenLogger
{
#region Propriedades
/// <summary>
/// Gets a value indicating whether this instance is error enabled.
/// </summary>
/// <value><c>true</c> if this instance is error enabled; otherwise, <c>false</c>.</value>
public bool IsErrorEnabled => false;
/// <summary>
/// Gets a value indicating whether this instance is fatal enabled.
/// </summary>
/// <value><c>true</c> if this instance is fatal enabled; otherwise, <c>false</c>.</value>
public bool IsFatalEnabled => false;
/// <summary>
/// Gets a value indicating whether this instance is debug enabled.
/// </summary>
/// <value><c>true</c> if this instance is debug enabled; otherwise, <c>false</c>.</value>
public bool IsDebugEnabled => false;
/// <summary>
/// Gets a value indicating whether this instance is information enabled.
/// </summary>
/// <value><c>true</c> if this instance is information enabled; otherwise, <c>false</c>.</value>
public bool IsInfoEnabled => false;
/// <summary>
/// Gets a value indicating whether this instance is warn enabled.
/// </summary>
/// <value><c>true</c> if this instance is warn enabled; otherwise, <c>false</c>.</value>
public bool IsWarnEnabled => false;
#endregion Propriedades
#region Methods
/// <summary>
/// Errors the specified message.
/// </summary>
/// <param name="message">The message.</param>
public void Error(object message)
{
}
/// <summary>
/// Errors the specified message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public void Error(object message, Exception exception)
{
}
/// <summary>
/// Errors the format.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The arguments.</param>
public void ErrorFormat(string format, params object[] args)
{
}
/// <summary>
/// Fatals the specified message.
/// </summary>
/// <param name="message">The message.</param>
public void Fatal(object message)
{
}
/// <summary>
/// Fatals the specified message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public void Fatal(object message, Exception exception)
{
}
/// <summary>
/// Debugs the specified message.
/// </summary>
/// <param name="message">The message.</param>
public void Debug(object message)
{
}
/// <summary>
/// Debugs the specified message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public void Debug(object message, Exception exception)
{
}
/// <summary>
/// Debugs the format.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The arguments.</param>
public void DebugFormat(string format, params object[] args)
{
}
/// <summary>
/// Informations the specified message.
/// </summary>
/// <param name="message">The message.</param>
public void Info(object message)
{
}
/// <summary>
/// Informations the specified message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public void Info(object message, Exception exception)
{
}
/// <summary>
/// Informations the format.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The arguments.</param>
public void InfoFormat(string format, params object[] args)
{
}
/// <summary>
/// Warns the specified message.
/// </summary>
/// <param name="message">The message.</param>
public void Warn(object message)
{
}
/// <summary>
/// Warns the specified message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
public void Warn(object message, Exception exception)
{
}
/// <summary>
/// Warns the format.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The arguments.</param>
public void WarnFormat(string format, params object[] args)
{
}
#endregion Methods
}
} | 33.979899 | 104 | 0.562112 | [
"MIT"
] | adrbarros/OpenAC.Net.Core | src/OpenAC.Net.Core/Logging/NoLoggingLogger.cs | 6,762 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// alipay.ins.cooperation.product.query
/// </summary>
public class AlipayInsCooperationProductQueryRequest : IAlipayRequest<AlipayInsCooperationProductQueryResponse>
{
/// <summary>
/// 保险product查询
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.ins.cooperation.product.query";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 22.846774 | 115 | 0.550653 | [
"MIT"
] | ekolios/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayInsCooperationProductQueryRequest.cs | 2,843 | C# |
using System;
using System.Diagnostics;
namespace VSDom
{
/// <summary>Supplies input parameter guarding.</summary>
/// <remarks>
/// Supplying a Guard mechanism is not something that belongs in VSDOM. So,
/// although is a nice feature, we don't provide it anymore as we would have to
/// add methods just because the sake of being complete.
/// </remarks>
internal static class Guard
{
/// <summary>Guards the parameter if not null, otherwise throws an argument (null) exception.</summary>
/// <typeparam name="T">
/// The type to guard, can not be a structure.
/// </typeparam>
/// <param name="param">
/// The parameter to guard.
/// </param>
/// <param name="paramName">
/// The name of the parameter.
/// </param>
[DebuggerStepThrough]
public static T NotNull<T>([ValidatedNotNull]T param, string paramName) where T : class
{
if (param is null)
{
throw new ArgumentNullException(paramName);
}
return param;
}
/// <summary>Guards the parameter if not null or an empty string, otherwise throws an argument (null) exception.</summary>
/// <param name="param">
/// The parameter to guard.
/// </param>
/// <param name="paramName">
/// The name of the parameter.
/// </param>
[DebuggerStepThrough]
public static string NotNullOrEmpty([ValidatedNotNull]string param, string paramName)
{
NotNull(param, paramName);
#pragma warning disable S3256 // "string.IsNullOrEmpty" should be used
// in this case, not null was already checked.
if (string.Empty.Equals(param))
#pragma warning restore S3256 // "string.IsNullOrEmpty" should be used
{
throw new ArgumentException("Value cannot be an empty string.", paramName);
}
return param;
}
/// <summary>Marks the NotNull argument as being validated for not being null,
/// to satisfy the static code analysis.
/// </summary>
/// <remarks>
/// Notice that it does not matter what this attribute does, as long as
/// it is named ValidatedNotNullAttribute.
/// </remarks>
[AttributeUsage(AttributeTargets.Parameter)]
sealed class ValidatedNotNullAttribute : Attribute { }
}
}
| 37.560606 | 130 | 0.592981 | [
"MIT"
] | Corniel/VSDom | src/VSDom/Guard.cs | 2,481 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using MahApps.Metro;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.UI;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
using DALSA.SaperaLT.SapClassBasic;
using DALSA.SaperaLT;
using Accord.Math;
using System.Windows.Forms;
using LiveCharts;
using LiveCharts.Wpf;
using MachineControl.Camera.Dalsa;
namespace PLImg_V2
{
enum StageEnableState {
Enabled,
Disabled
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
Core Core = new Core();
public SeriesCollection seriesbox { get; set; }
public ChartValues<int> chartV { get; set; }
ImageBox[,] ImgBoxArr;
ImageBox[] TrgImgBoxArr;
Dictionary<ScanConfig, System.Windows.Controls.RadioButton> SampleConfig;
Dictionary<string,StageEnableState> StgState;
public MainWindow()
{
InitializeComponent();
InitImgBox();
SetImgBoxStretch();
InitLocalData();
DataContext = this;
ConnectionData cd = new ConnectionData();
Core.ConnectDevice( cd.CameraPath, cd.ControllerIP, cd.RStage )( ScanConfig.Trigger_1 );
//Core.ConnectDevice( cd.CameraPath, cd.DctStagePort, cd.RStage );
InitCore();
Display_GrabStatus();
}
#region Display
void DisplayTrgImg( Image<Gray , byte> img , int lineNum )
{
TrgImgBoxArr[lineNum].Image = img;
}
void DisplayAF(double input)
{
lblAFV.BeginInvoke(()=> lblAFV.Content = input.ToString("N4") );
}
void DisplayRealTime(Image<Gray, byte> img)
{
imgboxReal.Image = img;
Console.WriteLine( "readl time image is comming0" );
}
void DisplayBuffNumber(int num)
{
lblBuffNum.BeginInvoke(() => lblBuffNum.Content = num.ToString());
}
void DisplayFullScanImg(Image<Gray, Byte> img, int lineNum, int unitNum)
{
if ( lineNum < 4 && unitNum < 4 )
{
ImgBoxArr[unitNum , lineNum].Image = img;
}
}
void SetImgBoxStretch()
{
foreach (var item in ImgBoxArr)
{
item.SizeMode = PictureBoxSizeMode.Zoom;
}
}
#endregion
#region Init
void InitCore( )
{
foreach ( var item in GD.YXZ )
{
StgState[item] = StageEnableState.Enabled;
}
Core.evtRealimg += new TferImgArr( DisplayRealTime );
Core.evtTrgImg += new TferTrgImgArr( DisplayTrgImg );
Core.evtSV += new TferNumber( DisplayAF );
Core.evtFedBckPos += new TferFeedBackPos( DisplayPos );
Core.evtScanEnd += new TferScanStatus( ( ) => { this.BeginInvoke( () => Mouse.OverrideCursor = null ); } );
Task.Run(()=>Core.GetFeedbackPos());
imgboxReal.SizeMode = PictureBoxSizeMode.StretchImage;
InitViewWin();
}
void InitImgBox()
{
TrgImgBoxArr = new ImageBox[4];
TrgImgBoxArr[0] = imgboxTrig0;
TrgImgBoxArr[1] = imgboxTrig1;
TrgImgBoxArr[2] = imgboxTrig2;
TrgImgBoxArr[3] = imgboxTrig3;
foreach ( var item in TrgImgBoxArr )
{
item.SizeMode = PictureBoxSizeMode.StretchImage;
}
ImgBoxArr = new ImageBox[4,4];
ImgBoxArr[0, 0] = imgboxScan00;
ImgBoxArr[0, 1] = imgboxScan01;
ImgBoxArr[0, 2] = imgboxScan02;
ImgBoxArr[0, 3] = imgboxScan03;
ImgBoxArr[1, 0] = imgboxScan10;
ImgBoxArr[1, 1] = imgboxScan11;
ImgBoxArr[1, 2] = imgboxScan12;
ImgBoxArr[1, 3] = imgboxScan13;
ImgBoxArr[2, 0] = imgboxScan20;
ImgBoxArr[2, 1] = imgboxScan21;
ImgBoxArr[2, 2] = imgboxScan22;
ImgBoxArr[2, 3] = imgboxScan23;
ImgBoxArr[3, 0] = imgboxScan30;
ImgBoxArr[3, 1] = imgboxScan31;
ImgBoxArr[3, 2] = imgboxScan32;
ImgBoxArr[3, 3] = imgboxScan33;
}
void ClearImgBox()
{
for (int i = 0; i < ImgBoxArr.GetLength(0); i++)
{
for (int j = 0; j < ImgBoxArr.GetLength(1); j++)
{
ImgBoxArr[i, j].Image = null;
}
}
}
void InitViewWin( )
{
nudExtime.Value = 2400;
nudlinerate.Value = 400;
nudScanSpeed.Value = 1;
nudGoXPos.Value = 100;
nudGoYPos.Value = 50;
nudGoZPos.Value = 26.190;
}
void InitLocalData() {
StgState = new Dictionary<string , StageEnableState>();
StgState.Add("Y", new StageEnableState());
StgState.Add("X", new StageEnableState());
StgState.Add("Z", new StageEnableState());
SampleConfig = new Dictionary<ScanConfig , System.Windows.Controls.RadioButton>();
SampleConfig.Add( ScanConfig.Trigger_1 ,rdb1inch);
SampleConfig.Add( ScanConfig.Trigger_2 ,rdb2inch);
SampleConfig.Add( ScanConfig.Trigger_4 ,rdb4inch);
}
void DisplayPos(double[] inputPos)
{
Task.Run( ( ) => lblXpos.BeginInvoke( (Action)(( ) => lblXpos.Content = inputPos[0].ToString("N4")) ) );
Task.Run( ( ) => lblYpos.BeginInvoke( (Action)(( ) => lblYpos.Content = inputPos[1].ToString("N4")) ) );
Task.Run( ( ) => lblZpos.BeginInvoke( (Action)(( ) => lblZpos.Content = inputPos[2].ToString("N4")) ) );
}
#endregion
#region MainWindowEvent
void ScanStart( ) { Mouse.OverrideCursor = Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;}
void ScanEnd( ) { Mouse.OverrideCursor = null; }
#region Camera
private void btnGrap_Click(object sender, RoutedEventArgs e)
{
if ( Core == null ) Console.WriteLine( "null ");
Core.Grab();
}
private void btnFreeze_Click( object sender, RoutedEventArgs e )
{
Core.Freeze();
}
private void btnSaveData_Click(object sender, RoutedEventArgs e)
{
string savePath = "";
FolderBrowserDialog fbd = new FolderBrowserDialog();
if ( fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{
savePath = fbd.SelectedPath;
}
Core.SaveImageData( ImgBoxArr, savePath );
}
#endregion
#region Stage
// common //
private void btnOrigin_Click( object sender, RoutedEventArgs e ) {
foreach ( var item in GD.YXZ ) Core.Stg.Home( item )();
}
// XYZStage //
private void btnYMove_Click( object sender, RoutedEventArgs e )
{
if ( StgState["Y"] == StageEnableState.Enabled ) Core.MoveXYstg( "Y" , ( double ) nudGoYPos.Value );
}
private void btnXMove_Click( object sender, RoutedEventArgs e )
{
if ( StgState["X"] == StageEnableState.Enabled ) Core.MoveXYstg( "X" , ( double ) nudGoXPos.Value );
}
private void btnZMove_Click( object sender, RoutedEventArgs e )
{
if( StgState["Z"] == StageEnableState.Enabled) Core.MoveZstg( ( double ) nudGoZPos.Value );
}
// R Stage //
private void btnRMove_Click( object sender, RoutedEventArgs e )
{
double pulse = (double)nudGoRPos.Value * 400;
}
private void btnROrigin_Click( object sender, RoutedEventArgs e )
{
}
private void btnRForceStop_Click( object sender, RoutedEventArgs e )
{
}
#endregion
#endregion
#region Motor Enable / Disable // Done
private void ckbYDisa_Checked( object sender , RoutedEventArgs e )
{
Core.Stg.Disable( "Y" )();
StgState ["Y"] = StageEnableState.Disabled;
}
private void ckbXDisa_Checked( object sender, RoutedEventArgs e ) {
Core.Stg.Disable("X")();
StgState["X"] = StageEnableState.Disabled;
}
private void ckbZDisa_Checked( object sender, RoutedEventArgs e ) {
Core.Stg.Disable( "Z" )();
StgState["Z"] = StageEnableState.Disabled;
}
private void ckbYDisa_Unchecked( object sender , RoutedEventArgs e )
{
Core.Stg.Enable( "Y" )();
StgState["Y"] = StageEnableState.Enabled;
}
private void ckbXDisa_Unchecked( object sender , RoutedEventArgs e )
{
Core.Stg.Enable( "X" )();
StgState["X"] = StageEnableState.Enabled;
}
private void ckbZDisa_Unchecked( object sender, RoutedEventArgs e ) {
Core.Stg.Enable( "Z" )();
StgState["Z"] = StageEnableState.Enabled;
}
#endregion
#region Sscan data Setting
private void nudlinerate_KeyUp( object sender, System.Windows.Input.KeyEventArgs e ) {
if ( e.Key != System.Windows.Input.Key.Enter ) return;
Core.LineRate( (int)nudlinerate.Value );
}
private void nudExtime_KeyUp( object sender , System.Windows.Input.KeyEventArgs e )
{
if ( e.Key != System.Windows.Input.Key.Enter ) return;
Core.Exposure( ( int ) nudExtime.Value );
}
#endregion
#region window Event
private void MetroWindow_Closing( object sender, System.ComponentModel.CancelEventArgs e ) {
foreach ( var item in GD.YXZ )
{
Core.Stg.Disable( item )();
Core.Stg.Disconnect();
}
Core.Cam.Freeze();
Core.Cam.Disconnect();
}
#endregion
#region Image event
private void imgboxScan00_Click( object sender , EventArgs e )
{
}
private void imgboxScan01_Click( object sender , EventArgs e )
{
}
private void imgboxScan02_Click( object sender , EventArgs e )
{
}
private void imgboxScan03_Click( object sender , EventArgs e )
{
}
private void imgboxScan10_Click( object sender , EventArgs e )
{
}
private void imgboxScan11_Click( object sender , EventArgs e )
{
}
private void imgboxScan12_Click( object sender , EventArgs e )
{
}
private void imgboxScan13_Click( object sender , EventArgs e )
{
}
private void imgboxScan20_Click( object sender , EventArgs e )
{
}
private void imgboxScan21_Click( object sender , EventArgs e )
{
}
private void imgboxScan22_Click( object sender , EventArgs e )
{
}
private void imgboxScan23_Click( object sender , EventArgs e )
{
}
#endregion
#region Tab Select Event
#endregion
private void btnStartFixAreaScan_Click( object sender , RoutedEventArgs e )
{
Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
Core.TrigScanData.Scan_Stage_Speed = (double)nudTrgScanSpeed.Value;
foreach ( var item in SampleConfig )
{
if ( item.Value.IsChecked == true )
{
ResizeTriggerImgBox( item.Key );
Core.StartTrigScan( item.Key );
}
}
}
void ResizeTriggerImgBox(ScanConfig config)
{
switch ( config ) {
case ScanConfig.Trigger_1:
windowTrig0.Width = 560;
imgboxTrig0.Width = 560;
break;
case ScanConfig.Trigger_2:
windowTrig0.Width = 280;
windowTrig1.Width = 280;
imgboxTrig0.Width = 280;
imgboxTrig1.Width = 280;
break;
case ScanConfig.Trigger_4:
windowTrig0.Width = 140;
windowTrig1.Width = 140;
windowTrig2.Width = 140;
windowTrig3.Width = 140;
imgboxTrig0.Width = 140;
imgboxTrig1.Width = 140;
imgboxTrig2.Width = 140;
imgboxTrig3.Width = 140;
break;
}
}
private void btnSaveImg_Click( object sender, RoutedEventArgs e )
{
string savePath = "";
FolderBrowserDialog fbd = new FolderBrowserDialog();
if ( fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{
savePath = fbd.SelectedPath;
for ( int i = 0; i < TrgImgBoxArr.GetLength(0); i++ )
{
string filename = savePath + "\\" + i.ToString("D3") + ".png";
TrgImgBoxArr[i].Image?.Save( filename );
}
}
}
void Display_GrabStatus() {
Task.Run( () => {
while ( true )
{
lblgrabstatus.BeginInvoke(()=> {
lblgrabstatus.Content = Core.Cam.Xfer.Grabbing.ToString();
} );
System.Threading.Thread.Sleep( 200 );
}
} );
}
}
}
| 30.786638 | 125 | 0.534967 | [
"MIT"
] | pimier15/PLInspector | PLImg_V5/PL_Inspect_v5/MainWindow.xaml.cs | 14,287 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V4200</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V4200 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName="PRPA_MT010101UK06.Component2", Namespace="urn:hl7-org:v3")]
[System.Xml.Serialization.XmlRootAttribute("PRPA_MT010101UK06.Component2", Namespace="urn:hl7-org:v3")]
public partial class PRPA_MT010101UK06Component2 {
private PRPA_MT010101UK06Specialty specialtyField;
private string typeField;
private string typeCodeField;
private string[] typeIDField;
private string[] realmCodeField;
private string nullFlavorField;
private static System.Xml.Serialization.XmlSerializer serializer;
public PRPA_MT010101UK06Component2() {
this.typeField = "ActRelationship";
this.typeCodeField = "COMP";
}
public PRPA_MT010101UK06Specialty specialty {
get {
return this.specialtyField;
}
set {
this.specialtyField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string typeCode {
get {
return this.typeCodeField;
}
set {
this.typeCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] typeID {
get {
return this.typeIDField;
}
set {
this.typeIDField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string[] realmCode {
get {
return this.realmCodeField;
}
set {
this.realmCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string nullFlavor {
get {
return this.nullFlavorField;
}
set {
this.nullFlavorField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(PRPA_MT010101UK06Component2));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current PRPA_MT010101UK06Component2 object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if ((streamReader != null)) {
streamReader.Dispose();
}
if ((memoryStream != null)) {
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an PRPA_MT010101UK06Component2 object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output PRPA_MT010101UK06Component2 object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out PRPA_MT010101UK06Component2 obj, out System.Exception exception) {
exception = null;
obj = default(PRPA_MT010101UK06Component2);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out PRPA_MT010101UK06Component2 obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static PRPA_MT010101UK06Component2 Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((PRPA_MT010101UK06Component2)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current PRPA_MT010101UK06Component2 object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception) {
exception = null;
try {
SaveToFile(fileName);
return true;
}
catch (System.Exception e) {
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName) {
System.IO.StreamWriter streamWriter = null;
try {
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally {
if ((streamWriter != null)) {
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an PRPA_MT010101UK06Component2 object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output PRPA_MT010101UK06Component2 object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out PRPA_MT010101UK06Component2 obj, out System.Exception exception) {
exception = null;
obj = default(PRPA_MT010101UK06Component2);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out PRPA_MT010101UK06Component2 obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static PRPA_MT010101UK06Component2 LoadFromFile(string fileName) {
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try {
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally {
if ((file != null)) {
file.Dispose();
}
if ((sr != null)) {
sr.Dispose();
}
}
}
#endregion
#region Clone method
/// <summary>
/// Create a clone of this PRPA_MT010101UK06Component2 object
/// </summary>
public virtual PRPA_MT010101UK06Component2 Clone() {
return ((PRPA_MT010101UK06Component2)(this.MemberwiseClone()));
}
#endregion
}
}
| 41.417293 | 1,358 | 0.574567 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V4200/Generated/PRPA_MT010101UK06Component2.cs | 11,017 | C# |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using XenAdmin.Network;
using XenAdmin.Wizards.PatchingWizard;
using XenAdmin.Properties;
using System.Drawing;
using System.Collections.ObjectModel;
namespace XenAdmin.Commands
{
/// <summary>
/// Shows the patching wizard.
/// </summary>
internal class InstallNewUpdateCommand : Command
{
/// <summary>
/// Initializes a new instance of this Command. The parameter-less constructor is required if
/// this Command is to be attached to a ToolStrip menu item or button. It should not be used in any other scenario.
/// </summary>
public InstallNewUpdateCommand()
{
}
public InstallNewUpdateCommand(IMainWindow mainWindow)
: base(mainWindow)
{
}
protected override void ExecuteCore(SelectedItemCollection selection)
{
MainWindowCommandInterface.ShowForm(typeof(PatchingWizard));
}
protected override bool CanExecuteCore(SelectedItemCollection selection)
{
foreach (IXenConnection xenConnection in ConnectionsManager.XenConnectionsCopy)
{
if (xenConnection.IsConnected)
{
return true;
}
}
return false;
}
public override Image ContextMenuImage
{
get
{
return Resources._000_HostUnpatched_h32bit_16;
}
}
public override string ContextMenuText
{
get
{
return Messages.INSTALL_PENDING_UPDATES;
}
}
}
}
| 33.770833 | 124 | 0.637878 | [
"BSD-2-Clause"
] | cheng-z/xenadmin | XenAdmin/Commands/InstallNewUpdateCommand.cs | 3,244 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Vidas : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
gameObject.GetComponent<Text>().text = "Vidas: " + PlayerPrefs.GetInt("Vidas", 0);
}
}
| 19.3 | 90 | 0.660622 | [
"MIT"
] | decoejz/asteroides3d | Assets/Scripts/Vidas.cs | 388 | 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 glue-2017-03-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Glue.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Glue.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for CreateSession operation
/// </summary>
public class CreateSessionResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
CreateSessionResponse response = new CreateSessionResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Session", targetDepth))
{
var unmarshaller = SessionUnmarshaller.Instance;
response.Session = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException"))
{
return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("AlreadyExistsException"))
{
return AlreadyExistsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("IdempotentParameterMismatchException"))
{
return IdempotentParameterMismatchExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServiceException"))
{
return InternalServiceExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidInputException"))
{
return InvalidInputExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("OperationTimeoutException"))
{
return OperationTimeoutExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNumberLimitExceededException"))
{
return ResourceNumberLimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException"))
{
return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonGlueException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static CreateSessionResponseUnmarshaller _instance = new CreateSessionResponseUnmarshaller();
internal static CreateSessionResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static CreateSessionResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.956522 | 187 | 0.636269 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/Glue/Generated/Model/Internal/MarshallTransformations/CreateSessionResponseUnmarshaller.cs | 5,790 | C# |
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace FollowAlongLearnAPI
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
//TODO 1.0.0.a This is where the startup will be called from.
//TODO 1.0.0.b Let's also take this time to edit the launchSettings.json file, you'll find in that file what should be in there.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 33.210526 | 136 | 0.649762 | [
"MIT"
] | rmarks6767/FollowAlongAPI | Program.cs | 633 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithm
{
public static class Mathematics
{
public static (long rem, long mod) ChineseRemainderTheorem(IEnumerable<long> r, IEnumerable<long> m)
{
var ra = r.ToArray();
var ma = m.ToArray();
if (ra.Length != ma.Length) throw new ArgumentException();
var (r0, m0) = (0L, 1L);
for (var i = 0; i < ra.Length; i++)
{
if (ma[i] < 1) throw new ArgumentException(nameof(m));
var r1 = SafeModulo(ra[i], ma[i]);
var m1 = ma[i];
if (m0 < m1)
{
(r0, r1) = (r1, r0);
(m0, m1) = (m1, m0);
}
if (m0 % m1 == 0)
{
if (r0 % m1 != r1) return (0, 0);
continue;
}
var (g, im) = InverseGreatestCommonDivisor(m0, m1);
var u1 = m1 / g;
if ((r1 - r0) % g != 0) return (0, 0);
var x = (r1 - r0) / g % u1 * im % u1;
r0 += x * m0;
m0 *= u1;
if (r0 < 0) r0 += m0;
}
return (r0, m0);
}
public static long FloorSum(long n, long m, long a, long b)
{
var ret = 0L;
while (true)
{
if (a >= m)
{
ret += (n - 1) * n / 2 * (a / m);
a %= m;
}
if (b >= m)
{
ret += n * (b / m);
b %= m;
}
var yMax = a * n + b;
if (yMax < m) return ret;
(n, m, a, b) = (yMax / m, a, m, yMax % m);
}
}
public static (long g, long im) InverseGreatestCommonDivisor(long a, long b)
{
a = SafeModulo(a, b);
if (a == 0) return (b, 0);
var (s, t, m0, m1) = (b, a, 0L, 1L);
while (t > 0)
{
var u = s / t;
s -= t * u;
m0 -= m1 * u;
(s, t) = (t, s);
(m0, m1) = (m1, m0);
}
if (m0 < 0) m0 += b / s;
return (s, m0);
}
public static long InverseModulo(long value, long modulo)
{
if (modulo < 1) throw new ArgumentException(nameof(modulo));
var (rem, mod) = InverseGreatestCommonDivisor(value, modulo);
if (rem != 1) throw new InvalidOperationException();
return mod;
}
public static bool IsPrime(int value)
{
if (value <= 1) return false;
if (value == 2 || value == 7 || value == 61) return true;
if (value % 2 == 0) return false;
long d = value - 1;
while (d % 2 == 0) d /= 2;
foreach (var a in new long[] { 2, 7, 61 })
{
var t = d;
var y = PowerModulo(a, t, value);
while (t != value - 1 && y != 1 && y != value - 1)
{
y = y * y % value;
t <<= 1;
}
if (y != value - 1 && t % 2 == 0) return false;
}
return true;
}
public static long PowerModulo(long value, long n, long modulo)
{
if (n < 0) throw new ArgumentException(nameof(n));
if (modulo < 1) throw new ArgumentException(nameof(modulo));
if (modulo == 1) return 0;
var ret = 1L;
var y = SafeModulo(value, modulo);
while (n > 0)
{
if ((n & 1) == 1) ret = ret * y % modulo;
y = y * y % modulo;
n >>= 1;
}
return ret;
}
public static int PrimitiveRoot(long m)
{
switch (m)
{
case 2:
return 1;
case 167772161:
case 469762049:
case 998244353:
return 3;
case 754974721:
return 11;
}
var divs = new long[20];
divs[0] = 2;
var count = 1;
var x = (m - 1) / 2;
while (x % 2 == 0) x /= 2;
for (var i = 3L; i * i <= x; i += 2)
{
if (x % i != 0) continue;
divs[count++] = i;
while (x % i == 0) x /= i;
}
if (x > 1) divs[count++] = x;
for (var g = 2; ; g++)
{
var ok = true;
for (var i = 0; i < count && ok; i++)
if (PowerModulo(g, (m - 1) / divs[i], m) == 1)
ok = false;
if (ok) return g;
}
}
public static long SafeModulo(long value, long modulo) =>
value % modulo < 0 ? value % modulo + modulo : value % modulo;
}
} | 29.758621 | 108 | 0.353418 | [
"CC0-1.0"
] | AconCavy/AlgorithmSharp | src/Algorithm/Mathematics.cs | 5,178 | C# |
using System.IO;
using ELFinder.Connector.Drivers.FileSystem.Models.Files.Common;
using ELFinder.Connector.Drivers.FileSystem.Volumes;
using ELFinder.Connector.Utils;
namespace ELFinder.Connector.Drivers.FileSystem.Models.Files
{
/// <summary>
/// File entry object model
/// </summary>
public class FileEntryObjectModel : BaseFileEntryObjectModel
{
#region Static methods
/// <summary>
/// Create a new instance
/// </summary>
/// <param name="fileInfo">File info</param>
/// <param name="rootVolume">Root volume</param>
/// <returns>Result instance</returns>
public static FileEntryObjectModel Create(FileInfo fileInfo, FileSystemRootVolume rootVolume)
{
// Get paths
var parentPath = fileInfo.Directory?.FullName.Substring(rootVolume.Directory.FullName.Length);
var relativePath = fileInfo.FullName.Substring(rootVolume.Directory.FullName.Length);
// Create new instance
var objectModel = new FileEntryObjectModel
{
Read = true,
Write = !rootVolume.IsReadOnly,
Locked = rootVolume.IsLocked,
Name = fileInfo.Name,
Size = fileInfo.Length,
UnixTimeStamp = (long) (fileInfo.LastWriteTimeUtc - UnixOrigin).TotalSeconds,
Mime = UrlPathUtils.GetMimeType(fileInfo),
Hash = rootVolume.VolumeId + UrlPathUtils.EncodePath(relativePath),
ParentHash =
rootVolume.VolumeId +
UrlPathUtils.EncodePath(!string.IsNullOrEmpty(parentPath) ? parentPath : fileInfo.Directory?.Name)
};
// Return it
return objectModel;
}
#endregion
}
} | 34.509434 | 118 | 0.610169 | [
"BSD-3-Clause"
] | mppa-git/ELFinder.Connector.NET | Core/ELFinder.Connector/Drivers/FileSystem/Models/Files/FileEntryObjectModel.cs | 1,831 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using Caliburn.Micro;
using Microsoft.Phone.Controls;
using WhoWhat.UI.WindowsPhone.Core;
using WhoWhat.UI.WindowsPhone.Infrastructure;
using WhoWhat.UI.WindowsPhone.Infrastructure.ViewModels;
using WhoWhat.UI.WindowsPhone.Resources;
using WhoWhat.UI.WindowsPhone.Services;
using WhoWhat.UI.WindowsPhone.Services.Model;
namespace WhoWhat.UI.WindowsPhone.ViewModels.Question
{
public class ViewQuestionViewModel : TaskViewModel
{
private readonly INavigationService navigationService;
private readonly AppSettings appSettings;
private readonly QuestionRestService questionRestService;
private readonly ToastService toastService;
private readonly AnswerRestService answerRestService;
//From navigation
public string QuestionId { get; set; }
//From navigation
public bool FocusAnswer { get; set; }
/// <summary>
/// Indicates that answer of the current user should be highlighted
/// </summary>
public bool HighlightAnswer { get; set; }
public ViewQuestionViewModel(
INavigationService navigationService,
AppSettings appSettings,
QuestionRestService questionRestService,
ToastService toastService,
AnswerRestService answerRestService)
{
this.navigationService = navigationService;
this.appSettings = appSettings;
this.questionRestService = questionRestService;
this.toastService = toastService;
this.answerRestService = answerRestService;
Question = new Services.Model.Question()
{
Author = new Author()
};
Answers = new OrderedObservableCollection<Answer>((x, y) => y.CreatedAt.CompareTo(x.CreatedAt));
Votes = new Dictionary<string, VoteDirection>();
}
public bool IsQuestionExist
{
get { return isQuestionExist; }
set
{
isQuestionExist = value;
NotifyOfPropertyChange(() => IsQuestionExist);
}
}
protected override void OnInitialize()
{
base.OnInitialize();
IsQuestionExist = true;
IsAuthenticated = appSettings.IsAuthenticated;
}
protected async override void OnActivate()
{
base.OnActivate();
await RunTaskAsync(async () =>
{
await PopulateQuestion();
//Scroll to user answer
if (FocusAnswer)
{
Answer ownAnswer = Answers.FirstOrDefault(answer => answer.Author.UserId == appSettings.UserId);
SelectedAnswer = ownAnswer;
FocusAnswer = false;
}
},
(ex) =>
{
RestException restException = ex as RestException;
if (restException != null && restException.StatusCode == HttpStatusCode.NotFound)
{
IsQuestionExist = false;
}
else
{
IoC.Get<ToastService>().ShowError(AppResources.Message_ServerError);
}
});
}
private async Task PopulateQuestion()
{
QuestionDetailsResponse response = await questionRestService.Details(QuestionId);
//Update question
Question = response.Question;
IsCurrentUserAuthor = IsAuthenticated && Question.Author.UserId == appSettings.UserId;
//The user can only edit own question within 30 minutes
CanQuestionBeEdited = (response.ServerTimeUtc - Question.CreatedAt) < TimeSpan.FromMinutes(30);
MergeAnswers(response.Answers);
Votes = response.Votes;
IsQuestionEdit = false;
Question.IsVotedUp = response.Votes.Any(x => x.Key == appSettings.UserId && x.Value == VoteDirection.Up);
Question.IsVotedDown = response.Votes.Any(x => x.Key == appSettings.UserId && x.Value == VoteDirection.Down);
//Copy body to EditedBody
foreach (Answer answer in Answers)
{
answer.EditedBody = answer.Body;
answer.IsCurrentUserAuthor = IsAuthenticated && answer.Author.UserId == appSettings.UserId;
answer.IsVotedUp = answer.Votes.Any(x => x.Key == appSettings.UserId && x.Value == VoteDirection.Up);
answer.IsVotedDown = answer.Votes.Any(x => x.Key == appSettings.UserId && x.Value == VoteDirection.Down);
answer.IsEdit = false;
answer.CanBeAccepted = IsCurrentUserAuthor && answer.Author.UserId != appSettings.UserId;
//The user can only edit own answer within 30 minutes.
answer.CanBeEdited = IsAuthenticated && (response.ServerTimeUtc - answer.CreatedAt) < TimeSpan.FromMinutes(30);
}
}
private void MergeAnswers(IList<Answer> remote)
{
List<string> localIds = Answers.Select(answer => answer.AnswerId).ToList();
List<string> remoteIds = remote.Select(answer => answer.AnswerId).ToList();
//Get new answers
List<Answer> @new = remote.Where(answer => !localIds.Contains(answer.AnswerId)).ToList();
List<Answer> @removed = Answers.Where(answer => !remoteIds.Contains(answer.AnswerId)).ToList();
//Add
foreach (Answer answer in @new)
{
Answers.Add(answer);
}
//Remove
foreach (Answer answer in @removed)
{
Answers.Remove(answer);
}
//Update
foreach (Answer localAnswer in Answers)
{
Answer remoteAnswer = remote.FirstOrDefault(answer => answer.AnswerId == localAnswer.AnswerId);
if (remoteAnswer != null)
{
UpdateAnswer(localAnswer, remoteAnswer);
}
}
}
private static void UpdateAnswer(Answer localAnswer, Answer remoteAnswer)
{
localAnswer.Author = remoteAnswer.Author;
localAnswer.Body = remoteAnswer.Body;
localAnswer.CreatedAt = remoteAnswer.CreatedAt;
localAnswer.EditedAt = remoteAnswer.EditedAt;
localAnswer.EditedBody = remoteAnswer.EditedBody;
localAnswer.IsAccepted = remoteAnswer.IsAccepted;
localAnswer.IsEdit = false;
localAnswer.QuestionId = remoteAnswer.QuestionId;
localAnswer.Rating = remoteAnswer.Rating;
localAnswer.Votes = remoteAnswer.Votes;
}
private Services.Model.Question question;
public Services.Model.Question Question
{
get { return question; }
set
{
if (Equals(value, question)) return;
question = value;
NotifyOfPropertyChange(() => Question);
}
}
public Dictionary<string, VoteDirection> Votes { get; set; }
private bool isCurrentUserAuthor;
public bool IsCurrentUserAuthor
{
get { return isCurrentUserAuthor; }
set
{
if (value.Equals(isCurrentUserAuthor)) return;
isCurrentUserAuthor = value;
NotifyOfPropertyChange(() => IsCurrentUserAuthor);
}
}
private bool canQuestionBeEdited;
public bool CanQuestionBeEdited
{
get { return canQuestionBeEdited; }
set
{
canQuestionBeEdited = value;
NotifyOfPropertyChange(() => CanQuestionBeEdited);
}
}
private OrderedObservableCollection<Answer> answers;
public OrderedObservableCollection<Answer> Answers
{
get { return answers; }
set
{
if (Equals(value, answers)) return;
answers = value;
NotifyOfPropertyChange(() => Answers);
}
}
private Answer selectedAnswer;
public Answer SelectedAnswer
{
get { return selectedAnswer; }
set
{
selectedAnswer = value;
NotifyOfPropertyChange(() => SelectedAnswer);
}
}
#region Validation
private bool Validate()
{
if (string.IsNullOrEmpty(Body))
{
toastService.ShowWarning(
AppResources.Validation_QuestionBodyRequired
);
return false;
}
Body = Body.Trim();
if (Body.Length < appSettings.MinQuestionLength)
{
toastService.ShowWarning(string.Format(
AppResources.Validation_BodyValidationFrmt,
appSettings.MinQuestionLength,
Body.Length)
);
return false;
}
if (Tags.Count == 0)
{
toastService.ShowWarning(AppResources.Validation_TagRequired);
return false;
}
return true;
}
#endregion
#region Actions
public void Answer()
{
if (!appSettings.IsAuthenticated)
{
navigationService.UriFor<Login.LoginViewModel>().Navigate();
return;
}
navigationService.UriFor<AnswerQuestionViewModel>()
.WidthData(x => x.Question, Question).Navigate();
}
public async void QuestionDown()
{
if (!appSettings.IsAuthenticated)
{
navigationService.UriFor<Login.LoginViewModel>().Navigate();
return;
}
//Author can not vote for own question
if (IsCurrentUserAuthor) return;
await RunTaskAsync(async () =>
{
bool alreadyVotedDown = Votes.Any(x => x.Key == appSettings.UserId && x.Value == VoteDirection.Down);
if (alreadyVotedDown)
{
await questionRestService.Unvote(Question.QuestionId);
}
else
{
await questionRestService.VoteDown(Question.QuestionId);
}
await PopulateQuestion();
}, busy => Question.IsVotingBusy = busy);
}
public async void QuestionUp()
{
if (!appSettings.IsAuthenticated)
{
navigationService.UriFor<Login.LoginViewModel>().Navigate();
return;
}
//Author can not vote for own question
if (IsCurrentUserAuthor) return;
await RunTaskAsync(async () =>
{
bool alreadyVoteUp = Votes.Any(x => x.Key == appSettings.UserId && x.Value == VoteDirection.Up);
if (alreadyVoteUp)
{
await questionRestService.Unvote(Question.QuestionId);
}
else
{
await questionRestService.VoteUp(Question.QuestionId);
}
await PopulateQuestion();
}, busy => Question.IsVotingBusy = busy);
}
public async void AnswerUp(Answer answer)
{
if (!appSettings.IsAuthenticated)
{
navigationService.UriFor<Login.LoginViewModel>().Navigate();
return;
}
await RunTaskAsync(async () =>
{
bool alreadyVotedUp = answer.Votes.Any(x => x.Key == appSettings.UserId && x.Value == VoteDirection.Up);
if (alreadyVotedUp)
{
await answerRestService.Unvote(answer.AnswerId);
}
else
{
await answerRestService.VoteUp(answer.AnswerId);
}
await PopulateQuestion();
}, busy => answer.IsVotingBusy = busy);
}
public async void AnswerDown(Answer answer)
{
if (!appSettings.IsAuthenticated)
{
navigationService.UriFor<Login.LoginViewModel>().Navigate();
return;
}
await RunTaskAsync(async () =>
{
bool alreadyVotedDown = answer.Votes.Any(x => x.Key == appSettings.UserId && x.Value == VoteDirection.Down);
if (alreadyVotedDown)
{
await answerRestService.Unvote(answer.AnswerId);
}
else
{
await answerRestService.VoteDown(answer.AnswerId);
}
await PopulateQuestion();
}, (busy) => answer.IsVotingBusy = busy);
}
public async void MarkAsAccepted(Answer answer)
{
await RunTaskAsync(async () =>
{
//Only one answer can be accepted.
Answer accepted = Answers.FirstOrDefault(x => x.IsAccepted);
if (accepted != null)
{
await answerRestService.UnmarkAsAccepted(answer.AnswerId);
}
else
{
await answerRestService.MarkAsAccepted(answer.AnswerId);
}
await PopulateQuestion();
}, busy => answer.IsVotingBusy = busy);
}
public async void SaveEditedAnswer()
{
editingAnswer.EditedBody = editingAnswer.EditedBody.Trim();
if (editingAnswer.EditedBody.Length < appSettings.MinAnswerLength)
{
toastService.ShowWarning(string.Format(
AppResources.Validation_BodyValidationFrmt,
appSettings.MinAnswerLength,
editingAnswer.EditedBody.Length
));
return;
}
await RunTaskAsync(async () =>
{
await answerRestService.ChangeBody(editingAnswer.AnswerId, editingAnswer.EditedBody);
editingAnswer.IsEdit = false;
await PopulateQuestion();
editingAnswer = null;
},
(ex) =>
{
RestException restException = ex as RestException;
if (restException != null)
{
editingAnswer.IsEdit = false;
editingAnswer = null;
}
});
}
public async void UnmarkAsAccepted(Answer answer)
{
await RunTaskAsync(async () =>
{
await answerRestService.UnmarkAsAccepted(answer.AnswerId);
await PopulateQuestion();
}, busy => answer.IsVotingBusy = busy);
}
private Answer editingAnswer;
public void EditAnswer(Answer answer)
{
answer.IsEdit = true;
editingAnswer = answer;
}
public void CancelEditAnswer()
{
if (editingAnswer == null) return;
editingAnswer.EditedBody = editingAnswer.Body;
editingAnswer.IsEdit = false;
editingAnswer = null;
}
public async void RemoveAnswer(Answer answer)
{
if (MessageBox.Show(AppResources.Confirm_RemoveAnswer, AppResources.Confirm_Title, MessageBoxButton.OKCancel) != MessageBoxResult.OK)
return;
await RunTaskAsync(async () =>
{
await answerRestService.Remove(answer.AnswerId);
await PopulateQuestion();
});
}
public void ViewImage()
{
navigationService.UriFor<ImageViewModel>()
.WithParam(x => x.Image, new Uri(Question.ImageUri))
.WithParam(x => x.Body, Question.Body)
.Navigate();
}
public void OpenTag(string tag)
{
navigationService.UriFor<Search.SearchByTagViewModel>()
.WithParam(x => x.Tag, tag).Navigate();
}
public void OpenUserProfile(Author author)
{
if (appSettings.IsAuthenticated)
{
navigationService.UriFor<UserProfile.UserProfileViewModel>()
.WithParam(vm => vm.UserId, author.UserId)
.Navigate();
}
}
#region EditQuestion
private bool isQuestionEdit;
public bool IsQuestionEdit
{
get { return isQuestionEdit; }
set
{
isQuestionEdit = value;
NotifyOfPropertyChange(() => IsQuestionEdit);
}
}
public void EditQuestion()
{
Body = Question.Body;
Tags = new List<string>(Question.Tags);
IsQuestionEdit = true;
}
public void CancelEditQuestion()
{
IsQuestionEdit = false;
Body = Question.Body;
Tags = Question.Tags;
}
private string body;
public string Body
{
get { return body; }
set
{
if (value == body) return;
body = value;
NotifyOfPropertyChange(() => Body);
}
}
private List<string> tags = new List<string>();
private bool isQuestionExist;
public List<string> Tags
{
get { return tags; }
set
{
if (Equals(value, tags)) return;
tags = value;
NotifyOfPropertyChange(() => Tags);
}
}
public async void SaveEditedQuestion()
{
bool valid = Validate();
if (!valid)
{
return;
}
//Hide the keyboard
((PhoneApplicationPage)this.GetView()).Focus();
await RunTaskAsync(async () =>
{
IsQuestionEdit = false;
await questionRestService.ChangeInfo(QuestionId, Body, Tags);
await PopulateQuestion();
},
(ex) =>
{
RestException restException = ex as RestException;
if (restException != null)
{
IsQuestionEdit = false;
}
});
}
#endregion
public async void RemoveQuestion()
{
if (MessageBox.Show(AppResources.Confirm_RemoveQuestion, AppResources.Confirm_Title, MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
return;
}
await RunTaskAsync(async () =>
{
await questionRestService.Remove(question.QuestionId);
App.ReloadFeeds = true;
//The question does not exist so simple go back.
navigationService.GoBack();
});
}
#endregion
}
}
| 31.045814 | 147 | 0.521575 | [
"Apache-2.0"
] | Ontropix/whowhat | src/client/WhoWhat.UI.WindowsPhone/ViewModels/Question/ViewQuestionViewModel.cs | 19,654 | C# |
using System;
namespace NetSpell.SpellChecker.Dictionary
{
/// <summary>
/// The Word class represents a base word in the dictionary
/// </summary>
public class Word : IComparable
{
private string _AffixKeys = "";
private int _EditDistance = 0;
private int _height = 0;
private int _index = 0;
private string _PhoneticCode = "";
private string _text = "";
/// <summary>
/// Initializes a new instance of the class
/// </summary>
public Word()
{
}
/// <summary>
/// Initializes a new instance of the class
/// </summary>
/// <param name="text" type="string">
/// <para>
/// The string for the base word
/// </para>
/// </param>
/// <param name="affixKeys" type="string">
/// <para>
/// The affix keys that can be applied to this base word
/// </para>
/// </param>
/// <param name="phoneticCode" type="string">
/// <para>
/// The phonetic code for this word
/// </para>
/// </param>
public Word(string text, string affixKeys, string phoneticCode)
{
_text = text;
_AffixKeys = affixKeys;
_PhoneticCode = phoneticCode;
}
/// <summary>
/// Initializes a new instance of the class
/// </summary>
/// <param name="text" type="string">
/// <para>
/// The string for the base word
/// </para>
/// </param>
/// <param name="affixKeys" type="string">
/// <para>
/// The affix keys that can be applied to this base word
/// </para>
/// </param>
public Word(string text, string affixKeys)
{
_text = text;
_AffixKeys = affixKeys;
}
/// <summary>
/// Initializes a new instance of the class
/// </summary>
/// <param name="text" type="string">
/// <para>
/// The string for the base word
/// </para>
/// </param>
public Word(string text)
{
_text = text;
}
/// <summary>
/// Initializes a new instance of the class
/// </summary>
/// <param name="text" type="string">
/// <para>
/// The string for the word
/// </para>
/// </param>
/// <param name="index" type="int">
/// <para>
/// The position index of this word
/// </para>
/// </param>
/// <param name="height" type="int">
/// <para>
/// The line height of this word
/// </para>
/// </param>
/// <returns>
/// A void value...
/// </returns>
internal Word(string text, int index, int height)
{
_text = text;
_index = index;
_height = height;
}
/// <summary>
/// Initializes a new instance of the class
/// </summary>
/// <param name="text" type="string">
/// <para>
/// The string for the base word
/// </para>
/// </param>
/// <param name="editDistance" type="int">
/// <para>
/// The edit distance from the misspelled word
/// </para>
/// </param>
internal Word(string text, int editDistance)
{
_text = text;
_EditDistance = editDistance;
}
/// <summary>
/// Sorts a collection of words by EditDistance
/// </summary>
/// <remarks>
/// The compare sorts in desc order, largest EditDistance first
/// </remarks>
public int CompareTo(object obj)
{
int result = this.EditDistance.CompareTo(((Word)obj).EditDistance);
return result; // * -1; // sorts desc order
}
/// <summary>
/// The affix keys that can be applied to this base word
/// </summary>
public string AffixKeys
{
get {return _AffixKeys;}
set {_AffixKeys = value;}
}
/// <summary>
/// The index position of where this word appears
/// </summary>
public int Index
{
get { return _index; }
set { _index = value; }
}
/// <summary>
/// The phonetic code for this word
/// </summary>
public string PhoneticCode
{
get {return _PhoneticCode;}
set {_PhoneticCode = value;}
}
/// <summary>
/// The string for the base word
/// </summary>
public string Text
{
get { return _text; }
set { _text = value; }
}
/// <summary>
/// Used for sorting suggestions by its edit distance for
/// the misspelled word
/// </summary>
internal int EditDistance
{
get {return _EditDistance;}
set {_EditDistance = value;}
}
/// <summary>
/// The line height of this word
/// </summary>
internal int Height
{
get { return _height; }
set { _height = value; }
}
/// <summary>
/// Converts the word object to a string
/// </summary>
/// <returns>
/// Returns the Text Property contents
/// </returns>
public override string ToString()
{
return _text;
}
}
}
| 22.285714 | 70 | 0.558333 | [
"MIT"
] | mlocati/betterpoeditor | src/NetSpell.SpellChecker/Dictionary/Word.cs | 4,680 | C# |
#region License
/*
* All content copyright Marko Lahma, unless otherwise indicated. 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.
*
*/
#endregion
using System;
using System.Collections;
using System.Data.Common;
using System.Data.SqlClient;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using FakeItEasy;
using NUnit.Framework;
using Quartz.Impl.AdoJobStore;
using Quartz.Impl.AdoJobStore.Common;
using Quartz.Simpl;
using Quartz.Spi;
namespace Quartz.Tests.Unit.Impl.AdoJobStore
{
/// <author>Marko Lahma (.NET)</author>
[TestFixture(typeof(BinaryObjectSerializer))]
[TestFixture(typeof(JsonObjectSerializer))]
public class StdAdoDelegateTest
{
private readonly IObjectSerializer serializer;
public StdAdoDelegateTest(Type serializerType)
{
serializer = (IObjectSerializer) Activator.CreateInstance(serializerType);
serializer.Initialize();
}
[Test]
public void TestSerializeJobData()
{
bool binary = serializer.GetType() == typeof(BinaryObjectSerializer);
var args = new DelegateInitializationArgs();
args.TablePrefix = "QRTZ_";
args.InstanceName = "TESTSCHED";
args.InstanceId = "INSTANCE";
args.DbProvider = new DbProvider(TestConstants.DefaultSqlServerProvider, "");
args.TypeLoadHelper = new SimpleTypeLoadHelper();
args.ObjectSerializer = serializer;
var del = new StdAdoDelegate();
del.Initialize(args);
var jdm = new JobDataMap();
del.SerializeJobData(jdm);
jdm.Clear();
jdm.Put("key", "value");
jdm.Put("key2", null);
del.SerializeJobData(jdm);
jdm.Clear();
jdm.Put("key1", "value");
jdm.Put("key2", null);
jdm.Put("key3", new NonSerializableTestClass());
try
{
del.SerializeJobData(jdm);
if (binary)
{
Assert.Fail("Private types should not be serializable by binary serialization");
}
}
catch (SerializationException e)
{
if (binary)
{
Assert.IsTrue(e.Message.IndexOf("key3", StringComparison.Ordinal) >= 0);
}
else
{
Assert.Fail($"Private types should be serializable when not using binary serialization: {e}");
}
}
}
private class NonSerializableTestClass
{
}
[Test]
public async Task TestSelectBlobTriggerWithNoBlobContent()
{
var dbProvider = A.Fake<IDbProvider>();
var connection = A.Fake<DbConnection>();
var transaction = A.Fake<DbTransaction>();
var command = (DbCommand) A.Fake<StubCommand>();
var dbMetadata = new DbMetadata();
A.CallTo(() => dbProvider.Metadata).Returns(dbMetadata);
A.CallTo(() => dbProvider.CreateCommand()).Returns(command);
var dataReader = A.Fake<DbDataReader>();
A.CallTo(command).Where(x => x.Method.Name == "ExecuteDbDataReaderAsync")
.WithReturnType<Task<DbDataReader>>()
.Returns(dataReader);
A.CallTo(command).Where(x => x.Method.Name == "get_DbParameterCollection")
.WithReturnType<DbParameterCollection>()
.Returns(new StubParameterCollection());
A.CallTo(() => command.CommandText).Returns("");
A.CallTo(command).Where(x => x.Method.Name == "CreateDbParameter")
.WithReturnType<DbParameter>()
.Returns(new SqlParameter());
var adoDelegate = new StdAdoDelegate();
var delegateInitializationArgs = new DelegateInitializationArgs
{
TablePrefix = "QRTZ_",
InstanceId = "TESTSCHED",
InstanceName = "INSTANCE",
TypeLoadHelper = new SimpleTypeLoadHelper(),
UseProperties = false,
InitString = "",
DbProvider = dbProvider
};
adoDelegate.Initialize(delegateInitializationArgs);
var conn = new ConnectionAndTransactionHolder(connection, transaction);
// First result set has results, second has none
A.CallTo(() => dataReader.ReadAsync(CancellationToken.None)).Returns(true).Once();
A.CallTo(() => dataReader.ReadAsync(CancellationToken.None)).Returns(false);
A.CallTo(() => dataReader[AdoConstants.ColumnTriggerType]).Returns(AdoConstants.TriggerTypeBlob);
IOperableTrigger trigger = await adoDelegate.SelectTrigger(conn, new TriggerKey("test"));
Assert.That(trigger, Is.Null);
}
[Test]
public async Task TestSelectSimpleTriggerWithExceptionWithExtendedProps()
{
var dbProvider = A.Fake<IDbProvider>();
var connection = A.Fake<DbConnection>();
var transaction = A.Fake<DbTransaction>();
var command = (DbCommand) A.Fake<StubCommand>();
var dbMetadata = new DbMetadata();
A.CallTo(() => dbProvider.Metadata).Returns(dbMetadata);
A.CallTo(() => dbProvider.CreateCommand()).Returns(command);
var dataReader = A.Fake<DbDataReader>();
A.CallTo(command).Where(x => x.Method.Name == "ExecuteDbDataReaderAsync")
.WithReturnType<Task<DbDataReader>>()
.Returns(Task.FromResult(dataReader));
A.CallTo(command).Where(x => x.Method.Name == "get_DbParameterCollection")
.WithReturnType<DbParameterCollection>()
.Returns(new StubParameterCollection());
A.CallTo(() => command.CommandText).Returns("");
A.CallTo(command).Where(x => x.Method.Name == "CreateDbParameter")
.WithReturnType<DbParameter>()
.Returns(new SqlParameter());
var persistenceDelegate = A.Fake<ITriggerPersistenceDelegate>();
var exception = new InvalidOperationException();
A.CallTo(() => persistenceDelegate.LoadExtendedTriggerProperties(A<ConnectionAndTransactionHolder>.Ignored, A<TriggerKey>.Ignored, CancellationToken.None)).Throws(exception);
StdAdoDelegate adoDelegate = new TestStdAdoDelegate(persistenceDelegate);
var delegateInitializationArgs = new DelegateInitializationArgs
{
TablePrefix = "QRTZ_",
InstanceId = "TESTSCHED",
InstanceName = "INSTANCE",
TypeLoadHelper = new SimpleTypeLoadHelper(),
UseProperties = false,
InitString = "",
DbProvider = dbProvider
};
adoDelegate.Initialize(delegateInitializationArgs);
// Mock basic trigger data
A.CallTo(() => dataReader.ReadAsync(CancellationToken.None)).Returns(true);
A.CallTo(() => dataReader[AdoConstants.ColumnTriggerType]).Returns(AdoConstants.TriggerTypeSimple);
A.CallTo(() => dataReader[A<string>._]).Returns("1");
try
{
var conn = new ConnectionAndTransactionHolder(connection, transaction);
await adoDelegate.SelectTrigger(conn, new TriggerKey("test"));
Assert.Fail("Trigger selection should result in exception");
}
catch (InvalidOperationException e)
{
Assert.That(e, Is.SameAs(exception));
}
A.CallTo(() => persistenceDelegate.LoadExtendedTriggerProperties(A<ConnectionAndTransactionHolder>.Ignored, A<TriggerKey>.Ignored, CancellationToken.None)).MustHaveHappened();
}
[Test]
public async Task TestSelectSimpleTriggerWithDeleteBeforeSelectExtendedProps()
{
var dbProvider = A.Fake<IDbProvider>();
var connection = A.Fake<DbConnection>();
var transaction = A.Fake<DbTransaction>();
var command = (DbCommand) A.Fake<StubCommand>();
var dbMetadata = new DbMetadata();
A.CallTo(() => dbProvider.Metadata).Returns(dbMetadata);
A.CallTo(() => dbProvider.CreateCommand()).Returns(command);
var dataReader = A.Fake<DbDataReader>();
A.CallTo(command).Where(x => x.Method.Name == "ExecuteDbDataReaderAsync")
.WithReturnType<Task<DbDataReader>>()
.Returns(Task.FromResult(dataReader));
A.CallTo(command).Where(x => x.Method.Name == "get_DbParameterCollection")
.WithReturnType<DbParameterCollection>()
.Returns(new StubParameterCollection());
A.CallTo(() => command.CommandText).Returns("");
A.CallTo(command).Where(x => x.Method.Name == "CreateDbParameter")
.WithReturnType<DbParameter>()
.Returns(new SqlParameter());
var persistenceDelegate = A.Fake<ITriggerPersistenceDelegate>();
var exception = new InvalidOperationException();
A.CallTo(() => persistenceDelegate.LoadExtendedTriggerProperties(A<ConnectionAndTransactionHolder>.Ignored, A<TriggerKey>.Ignored, CancellationToken.None)).Throws(exception);
StdAdoDelegate adoDelegate = new TestStdAdoDelegate(persistenceDelegate);
var delegateInitializationArgs = new DelegateInitializationArgs
{
TablePrefix = "QRTZ_",
InstanceId = "TESTSCHED",
InstanceName = "INSTANCE",
TypeLoadHelper = new SimpleTypeLoadHelper(),
UseProperties = false,
InitString = "",
DbProvider = dbProvider
};
adoDelegate.Initialize(delegateInitializationArgs);
// First result set has results, second has none
A.CallTo(() => dataReader.ReadAsync(CancellationToken.None)).Returns(true).Once();
A.CallTo(() => dataReader[AdoConstants.ColumnTriggerType]).Returns(AdoConstants.TriggerTypeSimple);
A.CallTo(() => dataReader[A<string>._]).Returns("1");
var conn = new ConnectionAndTransactionHolder(connection, transaction);
IOperableTrigger trigger = await adoDelegate.SelectTrigger(conn, new TriggerKey("test"));
Assert.That(trigger, Is.Null);
A.CallTo(() => persistenceDelegate.LoadExtendedTriggerProperties(A<ConnectionAndTransactionHolder>.Ignored, A<TriggerKey>.Ignored, CancellationToken.None)).MustHaveHappened();
}
[Test]
public void ShouldSupportAssemblyQualifiedTriggerPersistenceDelegates()
{
StdAdoDelegate adoDelegate = new TestStdAdoDelegate(new SimpleTriggerPersistenceDelegate());
var delegateInitializationArgs = new DelegateInitializationArgs
{
TablePrefix = "QRTZ_",
InstanceId = "TESTSCHED",
InstanceName = "INSTANCE",
TypeLoadHelper = new SimpleTypeLoadHelper(),
UseProperties = false,
InitString = "triggerPersistenceDelegateClasses=" + typeof(TestTriggerPersistenceDelegate).AssemblyQualifiedName + ";" + typeof(TestTriggerPersistenceDelegate).AssemblyQualifiedName,
DbProvider = A.Fake<IDbProvider>()
};
adoDelegate.Initialize(delegateInitializationArgs);
}
private class TestStdAdoDelegate : StdAdoDelegate
{
private readonly ITriggerPersistenceDelegate testDelegate;
public TestStdAdoDelegate(ITriggerPersistenceDelegate testDelegate)
{
this.testDelegate = testDelegate;
}
public override ITriggerPersistenceDelegate FindTriggerPersistenceDelegate(string discriminator)
{
return testDelegate;
}
}
}
public abstract class StubCommand : DbCommand
{
protected StubCommand()
{
CommandText = "";
}
public override string CommandText { get; set; }
}
public class StubParameterCollection : DbParameterCollection
{
public override int Add(object value)
{
return -1;
}
public override bool Contains(object value)
{
return false;
}
public override void Clear()
{
}
public override int IndexOf(object value)
{
return -1;
}
public override void Insert(int index, object value)
{
}
public override void Remove(object value)
{
}
public override void RemoveAt(int index)
{
}
public override void RemoveAt(string parameterName)
{
}
protected override void SetParameter(int index, DbParameter value)
{
}
protected override void SetParameter(string parameterName, DbParameter value)
{
}
public override int Count => throw new NotImplementedException();
public override object SyncRoot => throw new NotImplementedException();
#if !NETCORE
public override bool IsFixedSize => throw new NotImplementedException();
public override bool IsReadOnly => throw new NotImplementedException();
public override bool IsSynchronized => throw new NotImplementedException();
#endif
public override int IndexOf(string parameterName)
{
throw new NotImplementedException();
}
public override IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
protected override DbParameter GetParameter(int index)
{
throw new NotImplementedException();
}
protected override DbParameter GetParameter(string parameterName)
{
throw new NotImplementedException();
}
public override bool Contains(string value)
{
return false;
}
public override void CopyTo(Array array, int index)
{
}
public override void AddRange(Array values)
{
}
}
public class TestTriggerPersistenceDelegate : SimpleTriggerPersistenceDelegate
{
}
} | 36.033254 | 198 | 0.605076 | [
"Apache-2.0"
] | 1508553303/quartznet | src/Quartz.Tests.Unit/Impl/AdoJobStore/StdAdoDelegateTest.cs | 15,170 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace twitter.core.Services
{
internal static class OAuth
{
static OAuth()
{
ServicePointManager.Expect100Continue = false;
}
public static string UrlEncode(string value)
{
var encoded = Uri.EscapeDataString(value);
return Regex
.Replace(encoded, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpperInvariant(), RegexOptions.ExplicitCapture, TimeSpan.FromSeconds(1))
.Replace("(", "%28", StringComparison.Ordinal)
.Replace(")", "%29", StringComparison.Ordinal)
.Replace("$", "%24", StringComparison.Ordinal)
.Replace("!", "%21", StringComparison.Ordinal)
.Replace("*", "%2A", StringComparison.Ordinal)
.Replace("'", "%27", StringComparison.Ordinal)
.Replace("%7E", "~", StringComparison.Ordinal);
}
public static string Nonce()
{
return Guid.NewGuid().ToString();
}
public static string TimeStamp()
{
var timespan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var result = Convert.ToInt64(timespan.TotalSeconds).ToString(CultureInfo.InvariantCulture);
return result;
}
public static string Signature(
string httpMethod,
string url,
string nonce,
string timestamp,
string consumerKey,
string consumerSecret,
string accessToken,
string accessTokenSecret,
IEnumerable<(string, string)>? parameters)
{
var parameterList = OrderedParameters(nonce, timestamp, consumerKey, accessToken, signature: null, parameters);
var parameterStrings = parameterList.Select(p => $"{p.Item1}={p.Item2}");
var parameterString = string.Join("&", parameterStrings);
var signatureBaseString = $"{httpMethod}&{UrlEncode(url)}&{UrlEncode(parameterString)}";
var compositeKey = $"{UrlEncode(consumerSecret)}&{UrlEncode(accessTokenSecret)}";
using var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(compositeKey));
var result = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(signatureBaseString)));
return result;
}
public static string AuthorizationHeader(
string nonce,
string timestamp,
string consumerKey,
string? accessToken,
string? signature,
IEnumerable<(string, string)>? parameters = null)
{
var parameterList = OrderedParameters(nonce, timestamp, consumerKey, accessToken, signature, parameters);
var parameterStrings = parameterList.Select(p => $"{p.Item1}=\"{p.Item2}\"");
var header = "OAuth " + string.Join(",", parameterStrings);
return header;
}
private static IEnumerable<(string, string)> OrderedParameters(
string nonce,
string timestamp,
string consumerKey,
string? accessToken,
string? signature,
IEnumerable<(string, string)>? parameters)
{
return
Parameters(nonce, timestamp, consumerKey, accessToken, signature, parameters)
.OrderBy(p => p.Item1, StringComparer.Ordinal);
}
private static IEnumerable<(string, string)> Parameters(
string nonce,
string timestamp,
string consumerKey,
string? accessToken,
string? signature,
IEnumerable<(string, string)>? parameters)
{
yield return ("oauth_version", "1.0");
yield return ("oauth_nonce", UrlEncode(nonce));
yield return ("oauth_timestamp", UrlEncode(timestamp));
yield return ("oauth_signature_method", "HMAC-SHA1");
yield return ("oauth_consumer_key", UrlEncode(consumerKey));
if (!string.IsNullOrWhiteSpace(signature))
{
yield return ("oauth_signature", UrlEncode(signature));
}
if (!string.IsNullOrWhiteSpace(accessToken))
{
yield return ("oauth_token", UrlEncode(accessToken));
}
if (parameters is not null)
{
foreach (var par in parameters.Select(par => (UrlEncode(par.Item1), UrlEncode(par.Item2))))
{
yield return par;
}
}
}
}
} | 38.333333 | 144 | 0.574948 | [
"MIT"
] | johnlev0/tweetz | src/twitter.core/Services/OAuth.cs | 4,832 | C# |
using Ase.Messaging.Common;
namespace AseFramework.Modeling.Saga
{
/// <summary>
/// A combination of key and value by which a Saga can be found. Sagas are triggered by events that have a property that
/// the saga is associated with. A single Association Value can lead to multiple Sagas, and a single Saga can be
/// associated with multiple Association Values.
/// <p/>
/// Two association values are considered equal when both their key and value are equal. For example, a Saga managing
/// Orders could have a AssociationValue with key "orderId" and the order identifier as value.
/// </summary>
public class AssociationValue
{
private readonly string _propertyKey;
private readonly string? _propertyValue;
/// <summary>
/// Creates a Association Value instance with the given {@code key} and {@code value}.
/// </summary>
/// <param name="key">The key of the Association Value. Usually indicates where the value comes from.</param>
/// <param name="value">The value corresponding to the key of the association. It is highly recommended to only use</param>
public AssociationValue(string key, string? value) {
Assert.NotNull(key, () => "Cannot associate a Saga with a null key");
_propertyKey = key;
_propertyValue = value;
}
/// <summary>
/// Returns the key of this association value. The key usually indicates where the property's value comes from.
/// </summary>
/// <returns>the key of this association value</returns>
public string GetKey() {
return _propertyKey;
}
/// <summary>
/// Returns the value of this association.
/// </summary>
/// <returns>the value of this association. Never {@code null}.</returns>
public string? GetValue() {
return _propertyValue;
}
public override bool Equals(object? obj)
{
if (this == obj) {
return true;
}
if (obj == null || GetType() != obj.GetType()) {
return false;
}
AssociationValue that = (AssociationValue) obj;
return Equals(_propertyKey, that._propertyKey) &&
Equals(_propertyValue, that._propertyValue);
}
public override int GetHashCode()
{
return System.HashCode.Combine(_propertyKey, _propertyValue);
}
}
} | 39.9375 | 131 | 0.603286 | [
"Apache-2.0"
] | nsafari/AseFramework | AseFramework.Modeling/Saga/AssociationValue.cs | 2,558 | C# |
using System;
using System.Management.Automation;
using SnipeSharp.Models;
using SnipeSharp.PowerShell.BindingTypes;
namespace SnipeSharp.PowerShell.Cmdlets
{
/// <summary>Changes the properties of an existing Snipe-IT model.</summary>
/// <remarks>The Set-Model cmdlet changes the properties of an existing Snipe-IT model object.</remarks>
/// <example>
/// <code>Set-Model -Name "PotatoPeeler Plus 3000" -EndOfLife 36</code>
/// <para>Acknowledges that even the mighty "PotatoPeeler Plus 3000" will only last about 3 years before it's time for a new one.</para>
/// </example>
[Cmdlet(VerbsCommon.Set, nameof(Model))]
[OutputType(typeof(Model))]
public class SetModel: SetObject<Model, ObjectBinding<Model>>
{
/// <summary>
/// The new name of the model.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string NewName { get; set; }
/// <summary>
/// The updated maker of this model.
/// </summary>
[Parameter]
public ObjectBinding<Manufacturer> Manufacturer { get; set; }
/// <summary>
/// The updated uri of the image for the model.
/// </summary>
[Parameter]
public Uri ImageUri { get; set; }
/// <summary>
/// The updated model number for the model.
/// </summary>
[Parameter]
public string ModelNumber { get; set; }
/// <summary>
/// The new depreciation to use for the model.
/// </summary>
[Parameter]
public ObjectBinding<Depreciation> Depreciation { get; set; }
/// <summary>
/// The updated category of the model.
/// </summary>
[Parameter]
public ObjectBinding<Category> Category { get; set; }
/// <summary>
/// The new custom field set that applies to the model.
/// </summary>
[Parameter]
public ObjectBinding<FieldSet> FieldSet { get; set; }
/// <summary>
/// The updated lifetime of the model in months.
/// </summary>
[Parameter]
public int EndOfLife { get; set; }
/// <summary>
/// Any notes about the model.
/// </summary>
[Parameter]
public string Notes { get; set; }
/// <inheritdoc />
protected override bool PopulateItem(Model item)
{
if(MyInvocation.BoundParameters.ContainsKey(nameof(NewName)))
item.Name = this.NewName;
if(MyInvocation.BoundParameters.ContainsKey(nameof(Manufacturer)))
{
if(!this.GetSingleValue(Manufacturer, out var manufacturer))
return false;
item.Manufacturer = manufacturer;
}
if(MyInvocation.BoundParameters.ContainsKey(nameof(ImageUri)))
item.ImageUri = this.ImageUri;
if(MyInvocation.BoundParameters.ContainsKey(nameof(ModelNumber)))
item.ModelNumber = this.ModelNumber;
if(MyInvocation.BoundParameters.ContainsKey(nameof(Depreciation)))
{
if(!this.GetSingleValue(Depreciation, out var depreciation))
return false;
item.Depreciation = depreciation;
}
if(MyInvocation.BoundParameters.ContainsKey(nameof(Category)))
{
if(!this.GetSingleValue(Category, out var category))
return false;
item.Category = category;
}
if(MyInvocation.BoundParameters.ContainsKey(nameof(FieldSet)))
{
if(!this.GetSingleValue(FieldSet, out var fieldset))
return false;
item.FieldSet = fieldset;
}
if(MyInvocation.BoundParameters.ContainsKey(nameof(EndOfLife)))
item.EndOfLife = this.EndOfLife;
if(MyInvocation.BoundParameters.ContainsKey(nameof(Notes)))
item.Notes = this.Notes;
return true;
}
}
}
| 35.938596 | 142 | 0.573102 | [
"MIT"
] | cofl/SnipeSharp | SnipeSharp.PowerShell/Cmdlets/Set/SetModel.cs | 4,097 | C# |
using System.Web.Mvc;
using System.Web.SessionState;
namespace Farz.CMS.Web.Areas.Profile.Controllers
{
[SessionState(SessionStateBehavior.ReadOnly)]
public class WidgetsController : Controller
{
public ActionResult ProfileWidget()
{
return PartialView("_ProfileWidget");
}
public ActionResult BioWidget()
{
return PartialView("_BioWidget");
}
public ActionResult SecurityWidget()
{
return PartialView("_SecurityWidget");
}
}
} | 23.125 | 50 | 0.618018 | [
"MIT"
] | ziyadsv/DragDropCms | Portal.CMS.Web/Areas/Profile/Controllers/WidgetsController.cs | 557 | 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 Microsoft.EntityFrameworkCore.TestUtilities;
namespace Microsoft.EntityFrameworkCore.Query
{
public abstract class InheritanceRelationshipsQueryRelationalFixture : InheritanceRelationshipsQueryFixtureBase
{
public TestSqlLoggerFactory TestSqlLoggerFactory
=> (TestSqlLoggerFactory)ListLoggerFactory;
}
}
| 36.5 | 115 | 0.790607 | [
"Apache-2.0"
] | 0b01/efcore | test/EFCore.Relational.Specification.Tests/Query/InheritanceRelationshipsQueryRelationalFixture.cs | 511 | C# |
using System;
namespace ExerciciosAula03
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| 14.153846 | 46 | 0.532609 | [
"MIT"
] | LeonardoLuz2/LPC2019-1 | ExerciciosAula03/ExerciciosAula03/Program.cs | 186 | C# |
#pragma checksum "C:\Users\Khadar Baba Shaik\source\repos\Demo\Demo\Views\Home\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "aaa8e045c83cbb8e4c55c13bad55175c117ef7bc"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Index), @"mvc.1.0.view", @"/Views/Home/Index.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"aaa8e045c83cbb8e4c55c13bad55175c117ef7bc", @"/Views/Home/Index.cshtml")]
public class Views_Home_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\r\n<h1>Home</h1>");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 57.081081 | 176 | 0.749053 | [
"MIT"
] | DevRohith123/asp-test | obj/Debug/netcoreapp3.1/Razor/Views/Home/Index.cshtml.g.cs | 2,112 | C# |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
#nullable enable
using System;
using System.Linq;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal
{
/// <summary>
/// The TypeWrapper class wraps a Type so it may be used in
/// a platform-independent manner.
/// </summary>
public class TypeWrapper : ITypeInfo
{
/// <summary>
/// Construct a TypeWrapper for a specified Type.
/// </summary>
public TypeWrapper(Type type)
{
Guard.ArgumentNotNull(type, nameof(Type));
Type = type;
}
/// <summary>
/// Gets the underlying Type on which this TypeWrapper is based.
/// </summary>
public Type Type { get; private set; }
/// <summary>
/// Gets the base type of this type as an ITypeInfo
/// </summary>
public ITypeInfo? BaseType
{
get
{
var baseType = Type.GetTypeInfo().BaseType;
return baseType != null
? new TypeWrapper(baseType)
: null;
}
}
/// <summary>
/// Gets the Name of the Type
/// </summary>
public string Name
{
get { return Type.Name; }
}
/// <summary>
/// Gets the FullName of the Type
/// </summary>
public string FullName
{
get { return Type.FullName; }
}
/// <summary>
/// Gets the assembly in which the type is declared
/// </summary>
public Assembly Assembly
{
get { return Type.GetTypeInfo().Assembly; }
}
/// <summary>
/// Gets the namespace of the Type
/// </summary>
public string Namespace
{
get { return Type.Namespace; }
}
/// <summary>
/// Gets a value indicating whether the type is abstract.
/// </summary>
public bool IsAbstract
{
get { return Type.GetTypeInfo().IsAbstract; }
}
/// <summary>
/// Gets a value indicating whether the Type is a generic Type
/// </summary>
public bool IsGenericType
{
get { return Type.GetTypeInfo().IsGenericType; }
}
/// <summary>
/// Returns true if the Type wrapped is T
/// </summary>
public bool IsType(Type type)
{
return Type == type;
}
/// <summary>
/// Gets a value indicating whether the Type has generic parameters that have not been replaced by specific Types.
/// </summary>
public bool ContainsGenericParameters
{
get { return Type.GetTypeInfo().ContainsGenericParameters; }
}
/// <summary>
/// Gets a value indicating whether the Type is a generic Type definition
/// </summary>
public bool IsGenericTypeDefinition
{
get { return Type.GetTypeInfo().IsGenericTypeDefinition; }
}
/// <summary>
/// Gets a value indicating whether the type is sealed.
/// </summary>
public bool IsSealed
{
get { return Type.GetTypeInfo().IsSealed; }
}
/// <summary>
/// Gets a value indicating whether this type represents a static class.
/// </summary>
public bool IsStaticClass => Type.IsStatic();
/// <summary>
/// Get the display name for this type
/// </summary>
public string GetDisplayName()
{
return TypeHelper.GetDisplayName(Type);
}
/// <summary>
/// Get the display name for an object of this type, constructed with the specified args.
/// </summary>
public string GetDisplayName(object?[]? args)
{
return TypeHelper.GetDisplayName(Type, args);
}
/// <summary>
/// Returns a new ITypeInfo representing an instance of this generic Type using the supplied Type arguments
/// </summary>
public ITypeInfo MakeGenericType(Type[] typeArgs)
{
return new TypeWrapper(Type.MakeGenericType(typeArgs));
}
/// <summary>
/// Returns a Type representing a generic type definition from which this Type can be constructed.
/// </summary>
public Type GetGenericTypeDefinition()
{
return Type.GetGenericTypeDefinition();
}
/// <summary>
/// Returns an array of custom attributes of the specified type applied to this type
/// </summary>
public T[] GetCustomAttributes<T>(bool inherit) where T : class
{
return Type.GetAttributes<T>(inherit);
}
/// <summary>
/// Returns a value indicating whether the type has an attribute of the specified type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="inherit"></param>
/// <returns></returns>
public bool IsDefined<T>(bool inherit) where T : class
{
return Type.HasAttribute<T>(inherit);
}
/// <summary>
/// Returns a flag indicating whether this type has a method with an attribute of the specified type.
/// </summary>
/// <param name="attributeType"></param>
/// <returns></returns>
public bool HasMethodWithAttribute(Type attributeType)
{
return Reflect.HasMethodWithAttribute(Type, attributeType);
}
/// <summary>
/// Returns an array of IMethodInfos for methods of this Type
/// that match the specified flags.
/// </summary>
public IMethodInfo[] GetMethods(BindingFlags flags)
{
var methods = Type.GetMethods(flags);
var result = new MethodWrapper[methods.Length];
for (int i = 0; i < methods.Length; i++)
result[i] = new MethodWrapper(Type, methods[i]);
return result;
}
/// <summary>
/// Gets the public constructor taking the specified argument Types
/// </summary>
public ConstructorInfo? GetConstructor(Type[] argTypes)
{
return Type.GetConstructor(argTypes);
}
/// <summary>
/// Returns a value indicating whether this Type has a public constructor taking the specified argument Types.
/// </summary>
public bool HasConstructor(Type[] argTypes)
{
return GetConstructor(argTypes) != null;
}
/// <summary>
/// Construct an object of this Type, using the specified arguments.
/// </summary>
public object Construct(object?[]? args)
{
return Reflect.Construct(Type, args);
}
/// <summary>
/// Override ToString() so that error messages in NUnit's own tests make sense
/// </summary>
public override string ToString()
{
return Type.ToString();
}
/// <summary>
/// Returns all methods declared by this type that have the specified attribute, optionally
/// including base classes. Methods from a base class are always returned before methods from a class that
/// inherits from it.
/// </summary>
/// <param name="inherit">Specifies whether to search the fixture type inheritance chain.</param>
public IMethodInfo[] GetMethodsWithAttribute<T>(bool inherit) where T : class
{
if (!inherit)
{
return Type
.GetMethods(Reflect.AllMembers | BindingFlags.DeclaredOnly)
.Where(method => method.IsDefined(typeof(T), inherit: false))
.Select(method => new MethodWrapper(Type, method))
.ToArray();
}
var methodsByDeclaringType = Type
.GetMethods(Reflect.AllMembers | BindingFlags.FlattenHierarchy) // FlattenHierarchy is complex to replicate by looping over base types with DeclaredOnly.
.Where(method => method.IsDefined(typeof(T), inherit: true))
.ToLookup(method => method.DeclaringType);
return Type.TypeAndBaseTypes()
.Reverse()
.SelectMany(declaringType => methodsByDeclaringType[declaringType].Select(method => new MethodWrapper(declaringType, method)))
.ToArray();
}
}
}
| 32.099631 | 169 | 0.554317 | [
"MIT"
] | 304NotModified/nunit | src/NUnitFramework/framework/Internal/TypeWrapper.cs | 8,699 | C# |
using System;
using System.Collections.Generic;
using System.Net;
using RestSharp;
using SimpleAuthentication.Core;
using SimpleAuthentication.Core.Exceptions;
using SimpleAuthentication.Core.Providers;
using SimpleAuthentication.Core.Tracing;
using SimpleAuthentication.ExtraProviders.GitHub;
namespace SimpleAuthentication.ExtraProviders
{
public class GitHubProvider : BaseOAuth20Provider<AccessTokenResult>
{
private const string AccessTokenKey = "access_token";
private const string TokenTypeKey = "token_type";
public GitHubProvider(ProviderParams providerParams) : this("GitHub", providerParams)
{
}
protected GitHubProvider(string name, ProviderParams providerParams) : base(name, providerParams)
{
AuthenticateRedirectionUrl = new Uri("https://github.com/login/oauth/authorize");
}
#region BaseOAuth20Token<AccessTokenResult> Implementation
public override IEnumerable<string> DefaultScopes
{
get { return new[] {"user:email"}; }
}
public override string ScopeSeparator
{
get { return ","; }
}
protected override IRestResponse<AccessTokenResult> ExecuteRetrieveAccessToken(string authorizationCode,
Uri redirectUri)
{
if (string.IsNullOrEmpty(authorizationCode))
{
throw new ArgumentNullException("authorizationCode");
}
if (redirectUri == null ||
string.IsNullOrEmpty(redirectUri.AbsoluteUri))
{
throw new ArgumentNullException("redirectUri");
}
var restRequest = new RestRequest("/login/oauth/access_token", Method.POST);
restRequest.AddParameter("client_id", PublicApiKey);
restRequest.AddParameter("client_secret", SecretApiKey);
restRequest.AddParameter("redirect_uri", redirectUri.AbsoluteUri);
restRequest.AddParameter("code", authorizationCode);
restRequest.AddParameter("grant_type", "authorization_code");
var restClient = RestClientFactory.CreateRestClient("https://github.com");
TraceSource.TraceVerbose("Retrieving Access Token endpoint: {0}",
restClient.BuildUri(restRequest).AbsoluteUri);
return restClient.Execute<AccessTokenResult>(restRequest);
}
protected override AccessToken MapAccessTokenResultToAccessToken(AccessTokenResult accessTokenResult)
{
if (accessTokenResult == null)
{
throw new ArgumentNullException("accessTokenResult");
}
if (string.IsNullOrEmpty(accessTokenResult.AccessToken) ||
string.IsNullOrEmpty(accessTokenResult.TokenType))
{
var errorMessage =
string.Format(
"Retrieved a GitHub Access Token but it doesn't contain one or more of either: {0} or {1}.",
AccessTokenKey, TokenTypeKey);
TraceSource.TraceError(errorMessage);
throw new AuthenticationException(errorMessage);
}
return new AccessToken
{
PublicToken = accessTokenResult.AccessToken
//ExpiresOn = DateTime.UtcNow.AddSeconds(accessTokenResult.ExpiresIn)
};
}
protected override UserInformation RetrieveUserInformation(AccessToken accessToken)
{
if (accessToken == null)
{
throw new ArgumentNullException("accessToken");
}
if (string.IsNullOrEmpty(accessToken.PublicToken))
{
throw new ArgumentException("accessToken.PublicToken");
}
IRestResponse<UserInfoResult> response;
try
{
var restRequest = new RestRequest("/user", Method.GET);
restRequest.AddParameter(AccessTokenKey, accessToken.PublicToken);
var restClient = RestClientFactory.CreateRestClient("https://api.github.com");
restClient.UserAgent = PublicApiKey;
TraceSource.TraceVerbose("Retrieving user information. GitHub Endpoint: {0}",
restClient.BuildUri(restRequest).AbsoluteUri);
response = restClient.Execute<UserInfoResult>(restRequest);
}
catch (Exception exception)
{
throw new AuthenticationException("Failed to obtain User Info from GitHub.", exception);
}
if (response == null ||
response.StatusCode != HttpStatusCode.OK)
{
throw new AuthenticationException(
string.Format(
"Failed to obtain User Info from GitHub OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}",
response == null ? "-- null response --" : response.StatusCode.ToString(),
response == null ? string.Empty : response.StatusDescription));
}
// Lets check to make sure we have some bare minimum data.
if (string.IsNullOrEmpty(response.Data.Id.ToString()) ||
string.IsNullOrEmpty(response.Data.Login))
{
throw new AuthenticationException(
string.Format(
"Retrieve some user info from the GitHub Api, but we're missing one or both: Id: '{0}' and Login: '{1}'.",
string.IsNullOrEmpty(response.Data.Id.ToString()) ? "--missing--" : response.Data.Id.ToString(),
string.IsNullOrEmpty(response.Data.Login) ? "--missing--" : response.Data.Login));
}
return new UserInformation
{
Id = response.Data.Id.ToString(),
Name = response.Data.Name,
Email = response.Data.Email ?? "",
Picture = response.Data.AvatarUrl,
UserName = response.Data.Login
};
}
#endregion
}
} | 41.5 | 165 | 0.566265 | [
"MIT"
] | SimpleAuthentication/SimpleAuthentication | Code/SimpleAuthentication.ExtraProviders/GitHubProvider.cs | 6,559 | C# |
#region Header
/**
* JsonData.cs
* Generic type to hold JSON data (objects, arrays, and so on). This is
* the default type returned by JsonMapper.ToObject().
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
namespace BestHTTP.FTServer.LitJson
{
public class JsonData : IJsonWrapper, IEquatable<JsonData>
{
#region Fields
private IList<JsonData> inst_array;
private bool inst_boolean;
private double inst_double;
private int inst_int;
private long inst_long;
private IDictionary<string, JsonData> inst_object;
private string inst_string;
private string json;
private JsonType type;
// Used to implement the IOrderedDictionary interface
private IList<KeyValuePair<string, JsonData>> object_list;
#endregion
#region Properties
public int Count {
get { return EnsureCollection ().Count; }
}
public bool IsArray {
get { return type == JsonType.Array; }
}
public bool IsBoolean {
get { return type == JsonType.Boolean; }
}
public bool IsDouble {
get { return type == JsonType.Double; }
}
public bool IsInt {
get { return type == JsonType.Int; }
}
public bool IsLong {
get { return type == JsonType.Long; }
}
public bool IsObject {
get { return type == JsonType.Object; }
}
public bool IsString {
get { return type == JsonType.String; }
}
#endregion
#region ICollection Properties
int ICollection.Count {
get {
return Count;
}
}
bool ICollection.IsSynchronized {
get {
return EnsureCollection ().IsSynchronized;
}
}
object ICollection.SyncRoot {
get {
return EnsureCollection ().SyncRoot;
}
}
#endregion
#region IDictionary Properties
bool IDictionary.IsFixedSize {
get {
return EnsureDictionary ().IsFixedSize;
}
}
bool IDictionary.IsReadOnly {
get {
return EnsureDictionary ().IsReadOnly;
}
}
ICollection IDictionary.Keys {
get {
EnsureDictionary ();
IList<string> keys = new List<string> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
keys.Add (entry.Key);
}
return (ICollection) keys;
}
}
ICollection IDictionary.Values {
get {
EnsureDictionary ();
IList<JsonData> values = new List<JsonData> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
values.Add (entry.Value);
}
return (ICollection) values;
}
}
#endregion
#region IJsonWrapper Properties
bool IJsonWrapper.IsArray {
get { return IsArray; }
}
bool IJsonWrapper.IsBoolean {
get { return IsBoolean; }
}
bool IJsonWrapper.IsDouble {
get { return IsDouble; }
}
bool IJsonWrapper.IsInt {
get { return IsInt; }
}
bool IJsonWrapper.IsLong {
get { return IsLong; }
}
bool IJsonWrapper.IsObject {
get { return IsObject; }
}
bool IJsonWrapper.IsString {
get { return IsString; }
}
#endregion
#region IList Properties
bool IList.IsFixedSize {
get {
return EnsureList ().IsFixedSize;
}
}
bool IList.IsReadOnly {
get {
return EnsureList ().IsReadOnly;
}
}
#endregion
#region IDictionary Indexer
object IDictionary.this[object key] {
get {
return EnsureDictionary ()[key];
}
set {
if (! (key is String))
throw new ArgumentException (
"The key has to be a string");
JsonData data = ToJsonData (value);
this[(string) key] = data;
}
}
#endregion
#region IOrderedDictionary Indexer
object IOrderedDictionary.this[int idx] {
get {
EnsureDictionary ();
return object_list[idx].Value;
}
set {
EnsureDictionary ();
JsonData data = ToJsonData (value);
KeyValuePair<string, JsonData> old_entry = object_list[idx];
inst_object[old_entry.Key] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (old_entry.Key, data);
object_list[idx] = entry;
}
}
#endregion
#region IList Indexer
object IList.this[int index] {
get {
return EnsureList ()[index];
}
set {
EnsureList ();
JsonData data = ToJsonData (value);
this[index] = data;
}
}
#endregion
#region Public Indexers
public JsonData this[string prop_name] {
get {
EnsureDictionary ();
return inst_object[prop_name];
}
set {
EnsureDictionary ();
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (prop_name, value);
if (inst_object.ContainsKey (prop_name)) {
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == prop_name) {
object_list[i] = entry;
break;
}
}
} else
object_list.Add (entry);
inst_object[prop_name] = value;
json = null;
}
}
public JsonData this[int index] {
get {
EnsureCollection ();
if (type == JsonType.Array)
return inst_array[index];
return object_list[index].Value;
}
set {
EnsureCollection ();
if (type == JsonType.Array)
inst_array[index] = value;
else {
KeyValuePair<string, JsonData> entry = object_list[index];
KeyValuePair<string, JsonData> new_entry =
new KeyValuePair<string, JsonData> (entry.Key, value);
object_list[index] = new_entry;
inst_object[entry.Key] = value;
}
json = null;
}
}
#endregion
#region Constructors
public JsonData ()
{
}
public JsonData (bool boolean)
{
type = JsonType.Boolean;
inst_boolean = boolean;
}
public JsonData (double number)
{
type = JsonType.Double;
inst_double = number;
}
public JsonData (int number)
{
type = JsonType.Int;
inst_int = number;
}
public JsonData (long number)
{
type = JsonType.Long;
inst_long = number;
}
public JsonData (object obj)
{
if (obj is Boolean) {
type = JsonType.Boolean;
inst_boolean = (bool) obj;
return;
}
if (obj is Double) {
type = JsonType.Double;
inst_double = (double) obj;
return;
}
if (obj is Int32) {
type = JsonType.Int;
inst_int = (int) obj;
return;
}
if (obj is Int64) {
type = JsonType.Long;
inst_long = (long) obj;
return;
}
if (obj is String) {
type = JsonType.String;
inst_string = (string) obj;
return;
}
throw new ArgumentException (
"Unable to wrap the given object with JsonData");
}
public JsonData (string str)
{
type = JsonType.String;
inst_string = str;
}
#endregion
#region Implicit Conversions
public static implicit operator JsonData (Boolean data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Double data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int32 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int64 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (String data)
{
return new JsonData (data);
}
#endregion
#region Explicit Conversions
public static explicit operator Boolean (JsonData data)
{
if (data.type != JsonType.Boolean)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_boolean;
}
public static explicit operator Double (JsonData data)
{
if (data.type != JsonType.Double)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_double;
}
public static explicit operator Int32 (JsonData data)
{
if (data.type != JsonType.Int)
throw new InvalidCastException (
"Instance of JsonData doesn't hold an int");
return data.inst_int;
}
public static explicit operator Int64 (JsonData data)
{
if (data.type != JsonType.Long)
throw new InvalidCastException (
"Instance of JsonData doesn't hold an int");
return data.inst_long;
}
public static explicit operator String (JsonData data)
{
if (data.type != JsonType.String)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a string");
return data.inst_string;
}
#endregion
#region ICollection Methods
void ICollection.CopyTo (Array array, int index)
{
EnsureCollection ().CopyTo (array, index);
}
#endregion
#region IDictionary Methods
void IDictionary.Add (object key, object value)
{
JsonData data = ToJsonData (value);
EnsureDictionary ().Add (key, data);
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> ((string) key, data);
object_list.Add (entry);
json = null;
}
void IDictionary.Clear ()
{
EnsureDictionary ().Clear ();
object_list.Clear ();
json = null;
}
bool IDictionary.Contains (object key)
{
return EnsureDictionary ().Contains (key);
}
IDictionaryEnumerator IDictionary.GetEnumerator ()
{
return ((IOrderedDictionary) this).GetEnumerator ();
}
void IDictionary.Remove (object key)
{
EnsureDictionary ().Remove (key);
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == (string) key) {
object_list.RemoveAt (i);
break;
}
}
json = null;
}
#endregion
#region IEnumerable Methods
IEnumerator IEnumerable.GetEnumerator ()
{
return EnsureCollection ().GetEnumerator ();
}
#endregion
#region IJsonWrapper Methods
bool IJsonWrapper.GetBoolean ()
{
if (type != JsonType.Boolean)
throw new InvalidOperationException (
"JsonData instance doesn't hold a boolean");
return inst_boolean;
}
double IJsonWrapper.GetDouble ()
{
if (type != JsonType.Double)
throw new InvalidOperationException (
"JsonData instance doesn't hold a double");
return inst_double;
}
int IJsonWrapper.GetInt ()
{
if (type != JsonType.Int)
throw new InvalidOperationException (
"JsonData instance doesn't hold an int");
return inst_int;
}
long IJsonWrapper.GetLong ()
{
if (type != JsonType.Long)
throw new InvalidOperationException (
"JsonData instance doesn't hold a long");
return inst_long;
}
string IJsonWrapper.GetString ()
{
if (type != JsonType.String)
throw new InvalidOperationException (
"JsonData instance doesn't hold a string");
return inst_string;
}
void IJsonWrapper.SetBoolean (bool val)
{
type = JsonType.Boolean;
inst_boolean = val;
json = null;
}
void IJsonWrapper.SetDouble (double val)
{
type = JsonType.Double;
inst_double = val;
json = null;
}
void IJsonWrapper.SetInt (int val)
{
type = JsonType.Int;
inst_int = val;
json = null;
}
void IJsonWrapper.SetLong (long val)
{
type = JsonType.Long;
inst_long = val;
json = null;
}
void IJsonWrapper.SetString (string val)
{
type = JsonType.String;
inst_string = val;
json = null;
}
string IJsonWrapper.ToJson ()
{
return ToJson ();
}
void IJsonWrapper.ToJson (JsonWriter writer)
{
ToJson (writer);
}
#endregion
#region IList Methods
int IList.Add (object value)
{
return Add (value);
}
void IList.Clear ()
{
EnsureList ().Clear ();
json = null;
}
bool IList.Contains (object value)
{
return EnsureList ().Contains (value);
}
int IList.IndexOf (object value)
{
return EnsureList ().IndexOf (value);
}
void IList.Insert (int index, object value)
{
EnsureList ().Insert (index, value);
json = null;
}
void IList.Remove (object value)
{
EnsureList ().Remove (value);
json = null;
}
void IList.RemoveAt (int index)
{
EnsureList ().RemoveAt (index);
json = null;
}
#endregion
#region IOrderedDictionary Methods
IDictionaryEnumerator IOrderedDictionary.GetEnumerator ()
{
EnsureDictionary ();
return new OrderedDictionaryEnumerator (
object_list.GetEnumerator ());
}
void IOrderedDictionary.Insert (int idx, object key, object value)
{
string property = (string) key;
JsonData data = ToJsonData (value);
this[property] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (property, data);
object_list.Insert (idx, entry);
}
void IOrderedDictionary.RemoveAt (int idx)
{
EnsureDictionary ();
inst_object.Remove (object_list[idx].Key);
object_list.RemoveAt (idx);
}
#endregion
#region Private Methods
private ICollection EnsureCollection ()
{
if (type == JsonType.Array)
return (ICollection) inst_array;
if (type == JsonType.Object)
return (ICollection) inst_object;
throw new InvalidOperationException (
"The JsonData instance has to be initialized first");
}
private IDictionary EnsureDictionary ()
{
if (type == JsonType.Object)
return (IDictionary) inst_object;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a dictionary");
type = JsonType.Object;
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
return (IDictionary) inst_object;
}
private IList EnsureList ()
{
if (type == JsonType.Array)
return (IList) inst_array;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a list");
type = JsonType.Array;
inst_array = new List<JsonData> ();
return (IList) inst_array;
}
private JsonData ToJsonData (object obj)
{
if (obj == null)
return null;
if (obj is JsonData)
return (JsonData) obj;
return new JsonData (obj);
}
private static void WriteJson (IJsonWrapper obj, JsonWriter writer)
{
if (obj.IsString) {
writer.Write (obj.GetString ());
return;
}
if (obj.IsBoolean) {
writer.Write (obj.GetBoolean ());
return;
}
if (obj.IsDouble) {
writer.Write (obj.GetDouble ());
return;
}
if (obj.IsInt) {
writer.Write (obj.GetInt ());
return;
}
if (obj.IsLong) {
writer.Write (obj.GetLong ());
return;
}
if (obj.IsArray) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteJson ((JsonData) elem, writer);
writer.WriteArrayEnd ();
return;
}
if (obj.IsObject) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in ((IDictionary) obj)) {
writer.WritePropertyName ((string) entry.Key);
WriteJson ((JsonData) entry.Value, writer);
}
writer.WriteObjectEnd ();
return;
}
}
#endregion
public int Add (object value)
{
JsonData data = ToJsonData (value);
json = null;
return EnsureList ().Add (data);
}
public void Clear ()
{
if (IsObject) {
((IDictionary) this).Clear ();
return;
}
if (IsArray) {
((IList) this).Clear ();
return;
}
}
public bool Equals (JsonData x)
{
if (x == null)
return false;
if (x.type != this.type)
return false;
switch (this.type) {
case JsonType.None:
return true;
case JsonType.Object:
return this.inst_object.Equals (x.inst_object);
case JsonType.Array:
return this.inst_array.Equals (x.inst_array);
case JsonType.String:
return this.inst_string.Equals (x.inst_string);
case JsonType.Int:
return this.inst_int.Equals (x.inst_int);
case JsonType.Long:
return this.inst_long.Equals (x.inst_long);
case JsonType.Double:
return this.inst_double.Equals (x.inst_double);
case JsonType.Boolean:
return this.inst_boolean.Equals (x.inst_boolean);
}
return false;
}
public JsonType GetJsonType ()
{
return type;
}
public void SetJsonType (JsonType type)
{
if (this.type == type)
return;
switch (type) {
case JsonType.None:
break;
case JsonType.Object:
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
break;
case JsonType.Array:
inst_array = new List<JsonData> ();
break;
case JsonType.String:
inst_string = default (String);
break;
case JsonType.Int:
inst_int = default (Int32);
break;
case JsonType.Long:
inst_long = default (Int64);
break;
case JsonType.Double:
inst_double = default (Double);
break;
case JsonType.Boolean:
inst_boolean = default (Boolean);
break;
}
this.type = type;
}
public string ToJson ()
{
if (json != null)
return json;
StringWriter sw = new StringWriter ();
JsonWriter writer = new JsonWriter (sw);
writer.Validate = false;
WriteJson (this, writer);
json = sw.ToString ();
return json;
}
public void ToJson (JsonWriter writer)
{
bool old_validate = writer.Validate;
writer.Validate = false;
WriteJson (this, writer);
writer.Validate = old_validate;
}
public override string ToString ()
{
switch (type) {
case JsonType.Array:
return "JsonData array";
case JsonType.Boolean:
return inst_boolean.ToString ();
case JsonType.Double:
return inst_double.ToString ();
case JsonType.Int:
return inst_int.ToString ();
case JsonType.Long:
return inst_long.ToString ();
case JsonType.Object:
return "JsonData object";
case JsonType.String:
return inst_string;
}
return "Uninitialized JsonData";
}
}
internal class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
IEnumerator<KeyValuePair<string, JsonData>> list_enumerator;
public object Current {
get { return Entry; }
}
public DictionaryEntry Entry {
get {
KeyValuePair<string, JsonData> curr = list_enumerator.Current;
return new DictionaryEntry (curr.Key, curr.Value);
}
}
public object Key {
get { return list_enumerator.Current.Key; }
}
public object Value {
get { return list_enumerator.Current.Value; }
}
public OrderedDictionaryEnumerator (
IEnumerator<KeyValuePair<string, JsonData>> enumerator)
{
list_enumerator = enumerator;
}
public bool MoveNext ()
{
return list_enumerator.MoveNext ();
}
public void Reset ()
{
list_enumerator.Reset ();
}
}
}
| 25.197183 | 78 | 0.478 | [
"MIT"
] | frank12001/FT-SocketServer | ClientLib/Unity/Assets/F.T/SocketServer/Lib/Core/Network/Dependencies/Best HTTP (Pro)/Dependencies/LitJson/JsonData.cs | 25,046 | C# |
/*
This file is a part of JustLogic product which is distributed under
the BSD 3-clause "New" or "Revised" License
Copyright (c) 2015. All rights reserved.
Authors: Vladyslav Taranov.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of JustLogic nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using JustLogic.Core;
using UnityEngine;
/// <summary>
/// Base class for units
/// </summary>
/// <remarks>
/// A JL Script is composed of units - <see cref="JLAction"/> and <see cref="JLExpression"/>.
/// An expression differs from an action: it has returning value - the result of its work. This value can be immediately used as an argument for another unit.<br />
/// Examples of actions: move the object, load level, slow down time.<br />
/// Examples of expressions: find the main camera, compare two numbers, get the length of the string.<br />
/// </remarks>
public abstract class JLUnitBase : JLScriptable
{
public static Func<Type, ScriptableObject> CreateInstanceFunc;
/// <summary>
/// ScriptableObject.CreateInstance shortcut
/// </summary>
public new static T CreateInstance<T>() where T : ScriptableObject
{
return (T)(CreateInstanceFunc == null ? Library.Instantiator.CreateScriptable<T>() : CreateInstanceFunc(typeof(T)));
}
/// <summary>
/// ScriptableObject.CreateInstance shortcut
/// </summary>
public new static ScriptableObject CreateInstance(Type type)
{
return CreateInstanceFunc == null ? Library.Instantiator.CreateScriptable(type) : CreateInstanceFunc(type);
}
/// <summary>
/// ScriptableObject.CreateInstance shortcut
/// </summary>
public new static ScriptableObject CreateInstance(string classname)
{
return CreateInstanceFunc == null ? Library.Instantiator.CreateScriptable(classname) : CreateInstanceFunc(Library.FindType(classname));
}
/// <summary>
/// Weather unit is expanded in the inspector
/// </summary>
public bool Expanded = true;
}
| 40.130952 | 164 | 0.739247 | [
"BSD-3-Clause"
] | AqlaSolutions/JustLogic | Assets/JustLogic/Core/JLUnitBase.cs | 3,373 | C# |
namespace Bootstrap4Mvc6.Sample
{
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
public class Startup
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddTransient(typeof(BootstrapMvc.Mvc6.BootstrapHelper<>));
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseStatusCodePages();
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
"controllerActionRoute",
"{controller}/{action}",
new { controller = "Home", action = "Index" },
constraints: null,
dataTokens: new { NameSpace = "default" });
routes.MapRoute(
"controllerRoute",
"{controller}",
new { controller = "Home" });
});
}
}
}
| 29.059701 | 84 | 0.53621 | [
"MIT"
] | kbalint/BootstrapMvc | samples/Bootstrap4Mvc6.Sample/Startup.cs | 1,949 | C# |
/**
* Copyright 2018 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
using Newtonsoft.Json;
namespace IBM.WatsonDeveloperCloud.LanguageTranslator.v2.Model
{
/// <summary>
/// The response type for listing existing translation models.
/// </summary>
public class TranslationModels : BaseModel
{
/// <summary>
/// An array of available models.
/// </summary>
/// <value>
/// An array of available models.
/// </value>
[JsonProperty("models", NullValueHandling = NullValueHandling.Ignore)]
public List<TranslationModel> Models { get; set; }
}
}
| 30.820513 | 78 | 0.68802 | [
"Apache-2.0"
] | johnpisg/dotnet-standard-sdk | src/IBM.WatsonDeveloperCloud.LanguageTranslator.v2/Model/TranslationModels.cs | 1,202 | C# |
using Phantom.AI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
namespace Phantom.Characters
{
public class MoveToWaypoints : State<EnemyController>
{
private Animator animator;
private CharacterController controller;
private NavMeshAgent agent;
protected int hashMove = Animator.StringToHash("Move");
protected int hashMoveSpeed = Animator.StringToHash("MoveSpeed");
public override void OnInitialized()
{
animator = context.GetComponent<Animator>();
controller = context.GetComponent<CharacterController>();
agent = context.GetComponent<NavMeshAgent>();
}
public override void OnEnter()
{
if(context.targetWaypoint == null)
{
context.FindNextWayPoint();
}
if (context.targetWaypoint)
{
agent?.SetDestination(context.targetWaypoint.position);
animator?.SetBool(hashMove, true);
}
}
public override void Update(float deltaTime)
{
Transform enemy = context.SearchEnemy();
if(enemy)
{
if(context.IsAvailableAttack)
{
stateMachine.ChangeState<AttackState>();
}
else
{
stateMachine.ChangeState<MoveState>();
}
}
else
{
if(!agent.pathPending && (agent.remainingDistance <= agent.stoppingDistance))
{
Transform nextDest = context.FindNextWayPoint();
if (nextDest)
{
agent.SetDestination(nextDest.position);
}
stateMachine.ChangeState<IdleState>();
}
else
{
controller.Move(agent.velocity * deltaTime);
animator.SetFloat(hashMoveSpeed, agent.velocity.magnitude / agent.speed, 1f, deltaTime);
}
}
}
public override void OnExit()
{
animator?.SetBool(hashMove, false);
agent.ResetPath();
}
}
}
| 29.08642 | 108 | 0.512733 | [
"Apache-2.0"
] | ChangHo-Github/Unity | Algorithm/Assets/PastCampaus/AI/02.Scripts/MoveToWaypoints.cs | 2,356 | C# |
namespace HREngine.Bots
{
class Pen_Mekka2 : PenTemplate //repairbot
{
// stellt am ende eures zuges bei einem verletzten charakter 6 leben wieder her.
public override int getPlayPenalty(Playfield p, Minion m, Minion target, int choice, bool isLethal)
{
return 0;
}
}
} | 29.090909 | 107 | 0.65 | [
"MIT"
] | chi-rei-den/Silverfish | penalties/Pen_Mekka2.cs | 320 | C# |
namespace P01_StudentSystem.Data
{
using Microsoft.EntityFrameworkCore;
using Models;
public class StudentSystemContext : DbContext
{
public StudentSystemContext()
{ }
public StudentSystemContext(DbContextOptions options)
:base(options)
{ }
public DbSet<Course> Courses { get; set; }
public DbSet<Homework> HomeworkSubmissions { get; set; }
public DbSet<Resource> Resources { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<StudentCourse> StudentCourses { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(Config.ConnectionString);
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
StudentEntity(modelBuilder);
CourseEntity(modelBuilder);
ResourceEntity(modelBuilder);
HomeworkEntity(modelBuilder);
StudentCourseEntity(modelBuilder);
}
private void StudentCourseEntity(ModelBuilder modelBuilder)
{
modelBuilder.Entity<StudentCourse>(entity =>
{
entity.HasKey(e => new { e.StudentId, e.CourseId });
entity.HasOne(e => e.Student)
.WithMany(s => s.CourseEnrollments)
.HasForeignKey(e => e.StudentId);
entity.HasOne(e => e.Course)
.WithMany(c => c.StudentsEnrolled)
.HasForeignKey(e => e.CourseId);
});
}
private void HomeworkEntity(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Homework>()
.HasKey(h => h.HomeworkId);
modelBuilder
.Entity<Homework>()
.Property(h => h.Content);
modelBuilder
.Entity<Homework>()
.HasOne(h => h.Course)
.WithMany(c => c.HomeworkSubmissions)
.HasForeignKey(h => h.CourseId);
modelBuilder
.Entity<Homework>()
.HasOne(h => h.Student)
.WithMany(s => s.HomeworkSubmissions)
.HasForeignKey(h => h.StudentId);
}
private void ResourceEntity(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Resource>()
.HasKey(r => r.ResourceId);
modelBuilder
.Entity<Resource>()
.Property(r => r.Name)
.HasMaxLength(50)
.IsUnicode()
.IsRequired();
modelBuilder
.Entity<Resource>()
.Property(r => r.Url)
.IsRequired();
modelBuilder
.Entity<Resource>()
.HasOne(r => r.Course)
.WithMany(c => c.Resources);
}
private void CourseEntity(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Course>()
.HasKey(c => c.CourseId);
modelBuilder
.Entity<Course>()
.Property(c => c.Name)
.HasMaxLength(80)
.IsUnicode()
.IsRequired();
modelBuilder
.Entity<Course>()
.Property(c => c.Description)
.IsUnicode();
modelBuilder
.Entity<Course>()
.HasMany(c => c.Resources)
.WithOne(r => r.Course)
.HasForeignKey(c => c.ResourceId);
}
private static void StudentEntity(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Student>()
.HasKey(s => s.StudentId);
modelBuilder
.Entity<Student>()
.Property(s => s.Name)
.HasMaxLength(100)
.IsUnicode()
.IsRequired();
modelBuilder
.Entity<Student>()
.Property(s => s.PhoneNumber)
.HasColumnType("CHAR(10)");
modelBuilder
.Entity<Student>()
.Property(e => e.RegisteredOn )
.IsRequired();
modelBuilder
.Entity<Student>().Property(e => e.Birthday)
.IsRequired(false);
}
}
}
| 28.66875 | 85 | 0.485939 | [
"MIT"
] | DanielBankov/SoftUni | C# DB Fundamentals/Databases Advanced - Entity Framework/Entity Relations/1. Student System/Data/StudentSystemContext.cs | 4,589 | 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 Directory = Mono.Lucene.Net.Store.Directory;
namespace Mono.Lucene.Net.Index
{
sealed class FormatPostingsFieldsWriter:FormatPostingsFieldsConsumer
{
internal Directory dir;
internal System.String segment;
internal TermInfosWriter termsOut;
internal FieldInfos fieldInfos;
internal FormatPostingsTermsWriter termsWriter;
internal DefaultSkipListWriter skipListWriter;
internal int totalNumDocs;
public FormatPostingsFieldsWriter(SegmentWriteState state, FieldInfos fieldInfos):base()
{
dir = state.directory;
segment = state.segmentName;
totalNumDocs = state.numDocs;
this.fieldInfos = fieldInfos;
termsOut = new TermInfosWriter(dir, segment, fieldInfos, state.termIndexInterval);
// TODO: this is a nasty abstraction violation (that we
// peek down to find freqOut/proxOut) -- we need a
// better abstraction here whereby these child consumers
// can provide skip data or not
skipListWriter = new DefaultSkipListWriter(termsOut.skipInterval, termsOut.maxSkipLevels, totalNumDocs, null, null);
SupportClass.CollectionsHelper.AddIfNotContains(state.flushedFiles, state.SegmentFileName(IndexFileNames.TERMS_EXTENSION));
SupportClass.CollectionsHelper.AddIfNotContains(state.flushedFiles, state.SegmentFileName(IndexFileNames.TERMS_INDEX_EXTENSION));
termsWriter = new FormatPostingsTermsWriter(state, this);
}
/// <summary>Add a new field </summary>
internal override FormatPostingsTermsConsumer AddField(FieldInfo field)
{
termsWriter.SetField(field);
return termsWriter;
}
/// <summary>Called when we are done adding everything. </summary>
internal override void Finish()
{
termsOut.Close();
termsWriter.Close();
}
}
}
| 35.611111 | 132 | 0.764041 | [
"Apache-2.0"
] | CRivlaldo/mono | mcs/tools/monodoc/Lucene.Net/Lucene.Net/Index/FormatPostingsFieldsWriter.cs | 2,564 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.