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.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chronokeep.Database.SQLite
{
class Participants
{
internal static void AddParticipant(Participant person, SQLiteConnection connection)
{
person.FormatData();
SQLiteCommand command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "INSERT INTO participants (participant_first, participant_last, participant_street, " +
"participant_city, participant_state, participant_zip, participant_birthday, participant_email, " +
"participant_mobile, participant_parent, participant_country, participant_street2, participant_gender, " +
"emergencycontact_name, emergencycontact_phone)" +
" VALUES (@first,@last,@street,@city,@state,@zip,@birthdate,@email,@mobile,@parent,@country,@street2," +
"@gender,@ecname,@ecphone); SELECT participant_id FROM participants WHERE participant_first=@first " +
"AND participant_last=@last AND participant_street=@street AND participant_city=@city AND " +
"participant_state=@state AND participant_zip=@zip;";
command.Parameters.AddRange(new SQLiteParameter[] {
new SQLiteParameter("@first", person.FirstName),
new SQLiteParameter("@last", person.LastName),
new SQLiteParameter("@street", person.Street),
new SQLiteParameter("@city", person.City),
new SQLiteParameter("@state", person.State),
new SQLiteParameter("@zip", person.Zip),
new SQLiteParameter("@birthdate", person.Birthdate),
new SQLiteParameter("@email", person.Email),
new SQLiteParameter("@mobile", person.Mobile),
new SQLiteParameter("@parent", person.Parent),
new SQLiteParameter("@country", person.Country),
new SQLiteParameter("@street2", person.Street2),
new SQLiteParameter("@ecname", person.ECName),
new SQLiteParameter("@ecphone", person.ECPhone),
new SQLiteParameter("@gender", person.Gender) });
command.ExecuteNonQuery();
person.Identifier = GetParticipantID(person, connection);
command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "INSERT INTO eventspecific (participant_id, event_id, distance_id, eventspecific_bib, " +
"eventspecific_checkedin, eventspecific_comments, eventspecific_owes, eventspecific_other, " +
"eventspecific_age_group_name, eventspecific_age_group_id) " +
"VALUES (@participant,@event,@distance,@bib,@checkedin,@comments,@owes,@other,@ageGroupName,@ageGroupId)";
command.Parameters.AddRange(new SQLiteParameter[] {
new SQLiteParameter("@participant", person.Identifier),
new SQLiteParameter("@event", person.EventSpecific.EventIdentifier),
new SQLiteParameter("@distance", person.EventSpecific.DistanceIdentifier),
new SQLiteParameter("@bib", person.EventSpecific.Bib),
new SQLiteParameter("@checkedin", person.EventSpecific.CheckedIn),
new SQLiteParameter("@comments", person.EventSpecific.Comments),
new SQLiteParameter("@owes", person.EventSpecific.Owes),
new SQLiteParameter("@other", person.EventSpecific.Other),
new SQLiteParameter("@ageGroupName", person.EventSpecific.AgeGroupName),
new SQLiteParameter("@ageGroupId", person.EventSpecific.AgeGroupId)
});
command.ExecuteNonQuery();
}
internal static void RemoveParticipant(int identifier, SQLiteConnection connection)
{
SQLiteCommand command = connection.CreateCommand();
command.CommandText = "DELETE FROM eventspecific WHERE participant_id=@0; DELETE FROM participants WHERE participant_id=@0";
command.Parameters.AddRange(new SQLiteParameter[] {
new SQLiteParameter("@0", identifier) });
command.ExecuteNonQuery();
}
internal static void RemoveParticipantEntry(int identifier, SQLiteConnection connection)
{
SQLiteCommand command = connection.CreateCommand();
command.CommandText = "DELETE FROM eventspecific WHERE participant_id=@0;";
command.Parameters.AddRange(new SQLiteParameter[] {
new SQLiteParameter("@0", identifier) });
command.ExecuteNonQuery();
}
internal static void RemoveEntry(int eventId, int participantId, SQLiteConnection connection)
{
SQLiteCommand command = connection.CreateCommand();
command.CommandText = "DELETE FROM eventspecific WHERE participant_id=@participant AND event_id=@event;";
command.Parameters.AddRange(new SQLiteParameter[] {
new SQLiteParameter("@event", eventId),
new SQLiteParameter("@participant", participantId) });
command.ExecuteNonQuery();
}
internal static void UpdateParticipant(Participant person, SQLiteConnection connection)
{
SQLiteCommand command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "UPDATE participants SET participant_first=@first, participant_last=@last, participant_street=@street," +
" participant_city=@city, participant_state=@state, participant_zip=@zip, participant_birthday=@birthdate," +
" emergencycontact_name=@ecname, emergencycontact_phone=@ecphone, participant_email=@email, participant_mobile=@mobile," +
" participant_parent=@parent, participant_country=@country, participant_street2=@street2, participant_gender=@gender WHERE participant_id=@participantid";
command.Parameters.AddRange(new SQLiteParameter[] {
new SQLiteParameter("@first", person.FirstName),
new SQLiteParameter("@last", person.LastName),
new SQLiteParameter("@street", person.Street),
new SQLiteParameter("@city", person.City),
new SQLiteParameter("@state", person.State),
new SQLiteParameter("@zip", person.Zip),
new SQLiteParameter("@birthdate", person.Birthdate),
new SQLiteParameter("@ecname", person.ECName),
new SQLiteParameter("@ecphone", person.ECPhone),
new SQLiteParameter("@email", person.Email),
new SQLiteParameter("@participantid", person.Identifier),
new SQLiteParameter("@mobile", person.Mobile),
new SQLiteParameter("@parent", person.Parent),
new SQLiteParameter("@country", person.Country),
new SQLiteParameter("@street2", person.Street2),
new SQLiteParameter("@gender", person.Gender) });
command.ExecuteNonQuery();
command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "UPDATE eventspecific SET distance_id=@distanceId, eventspecific_bib=@bib, eventspecific_checkedin=@checkedin, " +
"eventspecific_owes=@owes, eventspecific_other=@other, " +
"eventspecific_comments=@comments, eventspecific_status=@status, eventspecific_age_group_name=@ageGroupName, eventspecific_age_group_id=@ageGroupId " +
"WHERE eventspecific_id=@eventspecid";
command.Parameters.AddRange(new SQLiteParameter[] {
new SQLiteParameter("@distanceId", person.EventSpecific.DistanceIdentifier),
new SQLiteParameter("@bib", person.EventSpecific.Bib),
new SQLiteParameter("@checkedin", person.EventSpecific.CheckedIn),
new SQLiteParameter("@eventspecid", person.EventSpecific.Identifier),
new SQLiteParameter("@owes", person.EventSpecific.Owes),
new SQLiteParameter("@other", person.EventSpecific.Other),
new SQLiteParameter("@comments", person.EventSpecific.Comments),
new SQLiteParameter("@status", person.EventSpecific.Status),
new SQLiteParameter("@ageGroupName", person.EventSpecific.AgeGroupName),
new SQLiteParameter("@ageGroupId", person.EventSpecific.AgeGroupId)
});
command.ExecuteNonQuery();
}
internal static List<Participant> GetParticipants(SQLiteConnection connection)
{
Log.D("SQLite.Participants", "Getting all participants for all events.");
return GetParticipantsWorker("SELECT * FROM participants p " +
"JOIN eventspecific s ON p.participant_id = s.participant_id " +
"JOIN distances d ON s.distance_id = d.distance_id ORDER BY p.participant_last ASC, p.participant_first ASC", -1, -1, connection);
}
internal static List<Participant> GetParticipants(int eventId, SQLiteConnection connection)
{
Log.D("SQLite.Participants", "Getting all participants for event with id of " + eventId);
return GetParticipantsWorker("SELECT * FROM participants p " +
"JOIN eventspecific s ON p.participant_id = s.participant_id " +
"JOIN distances d ON s.distance_id = d.distance_id " +
"WHERE s.event_id=@event ORDER BY p.participant_last ASC, p.participant_first ASC", eventId, -1, connection);
}
internal static List<Participant> GetParticipants(int eventId, int distanceId, SQLiteConnection connection)
{
Log.D("SQLite.Participants", "Getting all participants for event with id of " + eventId);
return GetParticipantsWorker("SELECT * FROM participants p " +
"JOIN eventspecific s ON p.participant_id = s.participant_id " +
"JOIN distances d ON s.distance_id = d.distance_id " +
"WHERE s.event_id=@event AND d.distance_id=@distance ORDER BY p.participant_last ASC, p.participant_first ASC", eventId, distanceId, connection);
}
internal static List<Participant> GetParticipantsWorker(string query, int eventId, int distanceId, SQLiteConnection connection)
{
List<Participant> output = new List<Participant>();
SQLiteCommand command = connection.CreateCommand();
command.CommandText = query;
if (eventId != -1)
{
command.Parameters.Add(new SQLiteParameter("@event", eventId));
}
if (distanceId != -1)
{
command.Parameters.Add(new SQLiteParameter("@distance", distanceId));
}
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
output.Add(new Participant(
Convert.ToInt32(reader["participant_id"]),
reader["participant_first"].ToString(),
reader["participant_last"].ToString(),
reader["participant_street"].ToString(),
reader["participant_city"].ToString(),
reader["participant_state"].ToString(),
reader["participant_zip"].ToString(),
reader["participant_birthday"].ToString(),
new EventSpecific(
Convert.ToInt32(reader["eventspecific_id"]),
Convert.ToInt32(reader["event_id"]),
Convert.ToInt32(reader["distance_id"]),
reader["distance_name"].ToString(),
Convert.ToInt32(reader["eventspecific_bib"]),
Convert.ToInt32(reader["eventspecific_checkedin"]),
reader["eventspecific_comments"].ToString(),
reader["eventspecific_owes"].ToString(),
reader["eventspecific_other"].ToString(),
Convert.ToInt32(reader["eventspecific_status"]),
reader["eventspecific_age_group_name"].ToString(),
Convert.ToInt32(reader["eventspecific_age_group_id"])
),
reader["participant_email"].ToString(),
reader["participant_mobile"].ToString(),
reader["participant_parent"].ToString(),
reader["participant_country"].ToString(),
reader["participant_street2"].ToString(),
reader["participant_gender"].ToString(),
reader["emergencycontact_name"].ToString(),
reader["emergencycontact_phone"].ToString()
));
}
reader.Close();
return output;
}
internal static Participant GetParticipantWorker(SQLiteDataReader reader)
{
if (reader.Read())
{
return new Participant(
Convert.ToInt32(reader["participant_id"]),
reader["participant_first"].ToString(),
reader["participant_last"].ToString(),
reader["participant_street"].ToString(),
reader["participant_city"].ToString(),
reader["participant_state"].ToString(),
reader["participant_zip"].ToString(),
reader["participant_birthday"].ToString(),
new EventSpecific(
Convert.ToInt32(reader["eventspecific_id"]),
Convert.ToInt32(reader["event_id"]),
Convert.ToInt32(reader["distance_id"]),
reader["distance_name"].ToString(),
Convert.ToInt32(reader["eventspecific_bib"]),
Convert.ToInt32(reader["eventspecific_checkedin"]),
reader["eventspecific_comments"].ToString(),
reader["eventspecific_owes"].ToString(),
reader["eventspecific_other"].ToString(),
Convert.ToInt32(reader["eventspecific_status"]),
reader["eventspecific_age_group_name"].ToString(),
Convert.ToInt32(reader["eventspecific_age_group_id"])
),
reader["participant_email"].ToString(),
reader["participant_mobile"].ToString(),
reader["participant_parent"].ToString(),
reader["participant_country"].ToString(),
reader["participant_street2"].ToString(),
reader["participant_gender"].ToString(),
reader["emergencycontact_name"].ToString(),
reader["emergencycontact_phone"].ToString()
);
}
return null;
}
internal static Participant GetParticipantEventSpecific(int eventIdentifier, int eventSpecificId, SQLiteConnection connection)
{
SQLiteCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM participants AS p JOIN eventspecific AS s ON p.participant_id=s.participant_id" +
" JOIN distances AS d ON s.distance_id=d.distance_id WHERE s.event_id=@eventid " +
"AND s.eventspecific_id=@eventSpecId";
command.Parameters.Add(new SQLiteParameter("@eventid", eventIdentifier));
command.Parameters.Add(new SQLiteParameter("@eventSpecId", eventSpecificId));
SQLiteDataReader reader = command.ExecuteReader();
Participant output = GetParticipantWorker(reader);
reader.Close();
return output;
}
internal static Participant GetParticipantBib(int eventIdentifier, int bib, SQLiteConnection connection)
{
SQLiteCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM participants AS p JOIN eventspecific AS s ON p.participant_id=s.participant_id" +
" JOIN distances AS d ON s.distance_id=d.distance_id WHERE s.event_id=@eventid " +
"AND s.eventspecific_bib=@bib";
command.Parameters.Add(new SQLiteParameter("@eventid", eventIdentifier));
command.Parameters.Add(new SQLiteParameter("@bib", bib));
SQLiteDataReader reader = command.ExecuteReader();
Participant output = GetParticipantWorker(reader);
reader.Close();
return output;
}
internal static Participant GetParticipant(int eventId, int identifier, SQLiteConnection connection)
{
SQLiteCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM participants AS p, eventspecific AS s, distances AS d WHERE " +
"p.participant_id=s.participant_id AND s.event_id=@eventid AND d.distance_id=s.distance_id " +
"AND p.participant_id=@partId";
command.Parameters.Add(new SQLiteParameter("@eventid", eventId));
command.Parameters.Add(new SQLiteParameter("@partId", identifier));
SQLiteDataReader reader = command.ExecuteReader();
Participant output = GetParticipantWorker(reader);
reader.Close();
return output;
}
internal static Participant GetParticipant(int eventId, Participant unknown, SQLiteConnection connection)
{
SQLiteCommand command = connection.CreateCommand();
if (unknown.EventSpecific.Chip != -1)
{
command.CommandText = "SELECT * FROM participants AS p, eventspecific AS s, distances AS d, " +
"bib_chip_assoc as b WHERE p.participant_id=s.participant_id AND s.event_id=@eventid " +
"AND d.distance_id=s.distance_id AND " +
"s.eventspecific_bib=b.bib AND b.chip=@chip AND b.event_id=s.event_id;";
command.Parameters.AddRange(new SQLiteParameter[] {
new SQLiteParameter("@eventid", eventId),
new SQLiteParameter("@chip", unknown.EventSpecific.Chip),
});
}
else
{
command.CommandText = "SELECT * FROM participants AS p, eventspecific AS s, distances AS d " +
"WHERE p.participant_id=s.participant_id AND s.event_id=@eventid AND d.distance_id=s.distance_id " +
"AND p.participant_first=@first AND p.participant_last=@last AND p.participant_street=@street " +
"AND p.participant_city=@city AND p.participant_state=@state AND p.participant_zip=@zip " +
"AND p.participant_birthday=@birthday";
command.Parameters.AddRange(new SQLiteParameter[] {
new SQLiteParameter("@eventid", eventId),
new SQLiteParameter("@first", unknown.FirstName),
new SQLiteParameter("@last", unknown.LastName),
new SQLiteParameter("@street", unknown.Street),
new SQLiteParameter("@city", unknown.City),
new SQLiteParameter("@state", unknown.State),
new SQLiteParameter("@zip", unknown.Zip),
new SQLiteParameter("@birthday", unknown.Birthdate)
});
}
SQLiteDataReader reader = command.ExecuteReader();
Participant output = GetParticipantWorker(reader);
reader.Close();
return output;
}
internal static int GetParticipantID(Participant person, SQLiteConnection connection)
{
int output = -1;
SQLiteCommand command = connection.CreateCommand();
command.CommandText = "SELECT participant_id FROM participants WHERE participant_first=@first AND" +
" participant_last=@last AND participant_street=@street AND " +
"participant_zip=@zip AND participant_birthday=@birthday";
command.Parameters.AddRange(new SQLiteParameter[]
{
new SQLiteParameter("@first", person.FirstName),
new SQLiteParameter("@last", person.LastName),
new SQLiteParameter("@street", person.Street),
new SQLiteParameter("@zip", person.Zip),
new SQLiteParameter("@birthday", person.Birthdate)
});
SQLiteDataReader reader = command.ExecuteReader();
if (reader.Read())
{
try
{
output = Convert.ToInt32(reader["participant_id"]);
}
catch
{
output = -1;
}
}
reader.Close();
return output;
}
}
}
| 57.798387 | 170 | 0.600298 | [
"MIT"
] | grecaun/chronokeep-windows | ChronoKeep/Database/SQLite/Participants.cs | 21,503 | C# |
// Copyright 2017 Justin Long. All rights reserved.
// Licensed under the MIT License.
namespace TowersWatsonIoC.Syntax
{
/// <summary>
/// Provides the builder syntax for the containers <see cref="IComponentContainerRegisterSyntax{TComponentType}.To(TComponentType)"/> method.
/// </summary>
/// <remarks>This interface is not intended to be used or impmeneted by anything other than the internal builder type.</remarks>
/// <typeparam name="TComponentType"></typeparam>
/// <typeparam name="TImplementation"></typeparam>
public interface IComponentContainerRegisterToSyntax<TComponentType, TImplementation>
where TImplementation : class
{
/// <summary>
/// Replaces the default transient component component with a <see cref="component.SingletonComponentRegistration{T}"/>.
/// </summary>
IComponentContainerRegisterAsSingletonSyntax<TComponentType, TImplementation> AsSingleton();
}
} | 48.1 | 145 | 0.726611 | [
"MIT"
] | dukk/TowersWatsonIoC | Code/TowersWatsonIoC/Syntax/IComponentContainerRegisterToSyntax.cs | 964 | C# |
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using HETSAPI.Models;
using HETSAPI.ViewModels;
using Microsoft.Extensions.Configuration;
namespace HETSAPI.Services.Impl
{
/// <summary>
/// Rental Agreeent Rate Service
/// </summary>
public class RentalAgreementRateService : IRentalAgreementRateService
{
private readonly DbAppContext _context;
private readonly IConfiguration _configuration;
/// <summary>
/// Rental Agreeent Rate Service Constructor
/// </summary>
public RentalAgreementRateService(DbAppContext context, IConfiguration configuration)
{
_context = context;
_configuration = configuration;
}
private void AdjustRecord(RentalAgreementRate item)
{
if (item != null)
{
if (item.RentalAgreement != null)
{
item.RentalAgreement = _context.RentalAgreements.FirstOrDefault(a => a.Id == item.RentalAgreement.Id);
}
if (item.TimeRecords != null)
{
for (int i = 0; i < item.TimeRecords.Count; i++)
{
if (item.TimeRecords[i] != null)
{
item.TimeRecords[i] = _context.TimeRecords.FirstOrDefault(a => a.Id == item.TimeRecords[i].Id);
}
}
}
}
}
/// <summary>
/// Create bulk rental afreement rate records
/// </summary>
/// <param name="items"></param>
/// <response code="201">RentalAgreementRate created</response>
public virtual IActionResult RentalagreementratesBulkPostAsync(RentalAgreementRate[] items)
{
if (items == null)
{
return new BadRequestResult();
}
foreach (RentalAgreementRate item in items)
{
AdjustRecord(item);
bool exists = _context.RentalAgreementRates.Any(a => a.Id == item.Id);
if (exists)
{
_context.RentalAgreementRates.Update(item);
}
else
{
_context.RentalAgreementRates.Add(item);
}
}
// save the changes
_context.SaveChanges();
return new NoContentResult();
}
/// <summary>
/// Delete rental agreement rate
/// </summary>
/// <param name="id">id of Project to delete</param>
/// <response code="200">OK</response>
public virtual IActionResult RentalagreementratesIdDeletePostAsync(int id)
{
bool exists = _context.RentalAgreementRates.Any(a => a.Id == id);
if (exists)
{
RentalAgreementRate item = _context.RentalAgreementRates.First(a => a.Id == id);
if (item != null)
{
_context.RentalAgreementRates.Remove(item);
// save the changes
_context.SaveChanges();
}
return new ObjectResult(new HetsResponse(item));
}
// record not found
return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
}
/// <summary>
/// Update rental agreement rate
/// </summary>
/// <param name="id">id of Project to update</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">Project not found</response>
public virtual IActionResult RentalagreementratesIdPutAsync(int id, RentalAgreementRate item)
{
AdjustRecord(item);
bool exists = _context.RentalAgreementRates.Any(a => a.Id == id);
if (exists && id == item.Id)
{
_context.RentalAgreementRates.Update(item);
// save the changes
_context.SaveChanges();
return new ObjectResult(new HetsResponse(item));
}
// record not found
return new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)));
}
}
}
| 33.876812 | 124 | 0.498396 | [
"Apache-2.0"
] | rstens/hets | Server/src/HETSAPI/Services.Impl/RentalAgreementRateService.cs | 4,677 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Host.Crawler.UI
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
}
}
| 20.956522 | 65 | 0.59751 | [
"MIT"
] | KIWI-ST/kiwi.server | Laboratory/Host.Crawler.UI/Program.cs | 504 | C# |
using System;
namespace SuperGlue.Web.ModelBinding.ValueConverters
{
public class DateTimeValueConverter : ParseValueConverter<DateTime>
{
protected override DateTime Parse(string stringValue, out bool success)
{
DateTime parsed;
success = DateTime.TryParse(stringValue, out parsed);
return parsed;
}
}
} | 26.928571 | 79 | 0.660477 | [
"MIT"
] | MattiasJakobsson/Jajo.Web | src/SuperGlue.Web.ModelBinding/ValueConverters/DateTimeValueConverter.cs | 377 | C# |
// *
// *
// * This file was generated using NASB_Parser_to_xNode by megalon2d
// * https://github.com/megalon/NASB_Parser_to_xNode
// *
// *
using NASB_Parser.FloatSources;
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEditor;
using XNode;
using XNodeEditor;
using NASB_Parser;
using NASB_Parser.Jumps;
using NASB_Parser.CheckThings;
using NASB_Parser.StateActions;
using NASB_Parser.ObjectSources;
using NASB_Moveset_Editor.FloatSources;
using NASB_Moveset_Editor.Jumps;
using NASB_Moveset_Editor.CheckThings;
using NASB_Moveset_Editor.StateActions;
using NASB_Moveset_Editor.ObjectSources;
using static NASB_Parser.StateActions.StateAction;
namespace NASB_Moveset_Editor.StateActions
{
public class SALaunchGrabbedCustomNode : StateActionNode
{
[Input(connectionType = ConnectionType.Override)] public StateAction NodeInput;
public string AtkProp;
[Output(connectionType = ConnectionType.Override)] public FloatSource X;
[Output(connectionType = ConnectionType.Override)] public FloatSource Y;
protected override void Init()
{
base.Init();
TID = TypeId.LaunchGrabbedCustomId;
}
public override object GetValue(NodePort port)
{
return null;
}
public int SetData(SALaunchGrabbedCustom data, MovesetGraph graph, string assetPath, Vector2 nodeDepthXY)
{
name = NodeEditorUtilities.NodeDefaultName(typeof(SALaunchGrabbedCustom));
position.x = nodeDepthXY.x * Consts.NodeXOffset;
position.y = nodeDepthXY.y * Consts.NodeYOffset;
int variableCount = 0;
AtkProp = data.AtkProp;
X = data.X;
switch (X.TID)
{
case FloatSource.TypeId.AgentId:
FSAgentNode AgentId_node_X = graph.AddNode<FSAgentNode>();
GetPort("X").Connect(AgentId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(AgentId_node_X, assetPath);
variableCount += AgentId_node_X.SetData((FSAgent)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.BonesId:
FSBonesNode BonesId_node_X = graph.AddNode<FSBonesNode>();
GetPort("X").Connect(BonesId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(BonesId_node_X, assetPath);
variableCount += BonesId_node_X.SetData((FSBones)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.AttackId:
FSAttackNode AttackId_node_X = graph.AddNode<FSAttackNode>();
GetPort("X").Connect(AttackId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(AttackId_node_X, assetPath);
variableCount += AttackId_node_X.SetData((FSAttack)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.FrameId:
FSFrameNode FrameId_node_X = graph.AddNode<FSFrameNode>();
GetPort("X").Connect(FrameId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(FrameId_node_X, assetPath);
variableCount += FrameId_node_X.SetData((FSFrame)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.InputId:
FSInputNode InputId_node_X = graph.AddNode<FSInputNode>();
GetPort("X").Connect(InputId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(InputId_node_X, assetPath);
variableCount += InputId_node_X.SetData((FSInput)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.FuncId:
FSFuncNode FuncId_node_X = graph.AddNode<FSFuncNode>();
GetPort("X").Connect(FuncId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(FuncId_node_X, assetPath);
variableCount += FuncId_node_X.SetData((FSFunc)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.MovementId:
FSMovementNode MovementId_node_X = graph.AddNode<FSMovementNode>();
GetPort("X").Connect(MovementId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(MovementId_node_X, assetPath);
variableCount += MovementId_node_X.SetData((FSMovement)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.CombatId:
FSCombatNode CombatId_node_X = graph.AddNode<FSCombatNode>();
GetPort("X").Connect(CombatId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(CombatId_node_X, assetPath);
variableCount += CombatId_node_X.SetData((FSCombat)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.GrabsId:
FSGrabsNode GrabsId_node_X = graph.AddNode<FSGrabsNode>();
GetPort("X").Connect(GrabsId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(GrabsId_node_X, assetPath);
variableCount += GrabsId_node_X.SetData((FSGrabs)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.DataId:
FSDataNode DataId_node_X = graph.AddNode<FSDataNode>();
GetPort("X").Connect(DataId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(DataId_node_X, assetPath);
variableCount += DataId_node_X.SetData((FSData)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.ScratchId:
FSScratchNode ScratchId_node_X = graph.AddNode<FSScratchNode>();
GetPort("X").Connect(ScratchId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(ScratchId_node_X, assetPath);
variableCount += ScratchId_node_X.SetData((FSScratch)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.AnimId:
FSAnimNode AnimId_node_X = graph.AddNode<FSAnimNode>();
GetPort("X").Connect(AnimId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(AnimId_node_X, assetPath);
variableCount += AnimId_node_X.SetData((FSAnim)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.SpeedId:
FSSpeedNode SpeedId_node_X = graph.AddNode<FSSpeedNode>();
GetPort("X").Connect(SpeedId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(SpeedId_node_X, assetPath);
variableCount += SpeedId_node_X.SetData((FSSpeed)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.PhysicsId:
FSPhysicsNode PhysicsId_node_X = graph.AddNode<FSPhysicsNode>();
GetPort("X").Connect(PhysicsId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(PhysicsId_node_X, assetPath);
variableCount += PhysicsId_node_X.SetData((FSPhysics)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.CollisionId:
FSCollisionNode CollisionId_node_X = graph.AddNode<FSCollisionNode>();
GetPort("X").Connect(CollisionId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(CollisionId_node_X, assetPath);
variableCount += CollisionId_node_X.SetData((FSCollision)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.TimerId:
FSTimerNode TimerId_node_X = graph.AddNode<FSTimerNode>();
GetPort("X").Connect(TimerId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(TimerId_node_X, assetPath);
variableCount += TimerId_node_X.SetData((FSTimer)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.LagId:
FSLagNode LagId_node_X = graph.AddNode<FSLagNode>();
GetPort("X").Connect(LagId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(LagId_node_X, assetPath);
variableCount += LagId_node_X.SetData((FSLag)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.EffectsId:
FSEffectsNode EffectsId_node_X = graph.AddNode<FSEffectsNode>();
GetPort("X").Connect(EffectsId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(EffectsId_node_X, assetPath);
variableCount += EffectsId_node_X.SetData((FSEffects)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.ColorsId:
FSColorsNode ColorsId_node_X = graph.AddNode<FSColorsNode>();
GetPort("X").Connect(ColorsId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(ColorsId_node_X, assetPath);
variableCount += ColorsId_node_X.SetData((FSColors)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.OnHitId:
FSOnHitNode OnHitId_node_X = graph.AddNode<FSOnHitNode>();
GetPort("X").Connect(OnHitId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(OnHitId_node_X, assetPath);
variableCount += OnHitId_node_X.SetData((FSOnHit)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.RandomId:
FSRandomNode RandomId_node_X = graph.AddNode<FSRandomNode>();
GetPort("X").Connect(RandomId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(RandomId_node_X, assetPath);
variableCount += RandomId_node_X.SetData((FSRandom)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.CameraId:
FSCameraInfoNode CameraId_node_X = graph.AddNode<FSCameraInfoNode>();
GetPort("X").Connect(CameraId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(CameraId_node_X, assetPath);
variableCount += CameraId_node_X.SetData((FSCameraInfo)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.SportsId:
FSSportsNode SportsId_node_X = graph.AddNode<FSSportsNode>();
GetPort("X").Connect(SportsId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(SportsId_node_X, assetPath);
variableCount += SportsId_node_X.SetData((FSSports)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.Vector2Mag:
FSVector2MagNode Vector2Mag_node_X = graph.AddNode<FSVector2MagNode>();
GetPort("X").Connect(Vector2Mag_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(Vector2Mag_node_X, assetPath);
variableCount += Vector2Mag_node_X.SetData((FSVector2Mag)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.CPUHelpId:
FSCpuHelpNode CPUHelpId_node_X = graph.AddNode<FSCpuHelpNode>();
GetPort("X").Connect(CPUHelpId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(CPUHelpId_node_X, assetPath);
variableCount += CPUHelpId_node_X.SetData((FSCpuHelp)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.ItemId:
FSItemNode ItemId_node_X = graph.AddNode<FSItemNode>();
GetPort("X").Connect(ItemId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(ItemId_node_X, assetPath);
variableCount += ItemId_node_X.SetData((FSItem)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.ModeId:
FSModeNode ModeId_node_X = graph.AddNode<FSModeNode>();
GetPort("X").Connect(ModeId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(ModeId_node_X, assetPath);
variableCount += ModeId_node_X.SetData((FSMode)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.JumpsId:
FSJumpsNode JumpsId_node_X = graph.AddNode<FSJumpsNode>();
GetPort("X").Connect(JumpsId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(JumpsId_node_X, assetPath);
variableCount += JumpsId_node_X.SetData((FSJumps)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.RootAnimId:
FSRootAnimNode RootAnimId_node_X = graph.AddNode<FSRootAnimNode>();
GetPort("X").Connect(RootAnimId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(RootAnimId_node_X, assetPath);
variableCount += RootAnimId_node_X.SetData((FSRootAnim)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.FloatId:
FSValueNode FloatId_node_X = graph.AddNode<FSValueNode>();
GetPort("X").Connect(FloatId_node_X.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(FloatId_node_X, assetPath);
variableCount += FloatId_node_X.SetData((FSValue)X, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
}
++variableCount;
Y = data.Y;
switch (Y.TID)
{
case FloatSource.TypeId.AgentId:
FSAgentNode AgentId_node_Y = graph.AddNode<FSAgentNode>();
GetPort("Y").Connect(AgentId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(AgentId_node_Y, assetPath);
variableCount += AgentId_node_Y.SetData((FSAgent)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.BonesId:
FSBonesNode BonesId_node_Y = graph.AddNode<FSBonesNode>();
GetPort("Y").Connect(BonesId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(BonesId_node_Y, assetPath);
variableCount += BonesId_node_Y.SetData((FSBones)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.AttackId:
FSAttackNode AttackId_node_Y = graph.AddNode<FSAttackNode>();
GetPort("Y").Connect(AttackId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(AttackId_node_Y, assetPath);
variableCount += AttackId_node_Y.SetData((FSAttack)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.FrameId:
FSFrameNode FrameId_node_Y = graph.AddNode<FSFrameNode>();
GetPort("Y").Connect(FrameId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(FrameId_node_Y, assetPath);
variableCount += FrameId_node_Y.SetData((FSFrame)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.InputId:
FSInputNode InputId_node_Y = graph.AddNode<FSInputNode>();
GetPort("Y").Connect(InputId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(InputId_node_Y, assetPath);
variableCount += InputId_node_Y.SetData((FSInput)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.FuncId:
FSFuncNode FuncId_node_Y = graph.AddNode<FSFuncNode>();
GetPort("Y").Connect(FuncId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(FuncId_node_Y, assetPath);
variableCount += FuncId_node_Y.SetData((FSFunc)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.MovementId:
FSMovementNode MovementId_node_Y = graph.AddNode<FSMovementNode>();
GetPort("Y").Connect(MovementId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(MovementId_node_Y, assetPath);
variableCount += MovementId_node_Y.SetData((FSMovement)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.CombatId:
FSCombatNode CombatId_node_Y = graph.AddNode<FSCombatNode>();
GetPort("Y").Connect(CombatId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(CombatId_node_Y, assetPath);
variableCount += CombatId_node_Y.SetData((FSCombat)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.GrabsId:
FSGrabsNode GrabsId_node_Y = graph.AddNode<FSGrabsNode>();
GetPort("Y").Connect(GrabsId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(GrabsId_node_Y, assetPath);
variableCount += GrabsId_node_Y.SetData((FSGrabs)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.DataId:
FSDataNode DataId_node_Y = graph.AddNode<FSDataNode>();
GetPort("Y").Connect(DataId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(DataId_node_Y, assetPath);
variableCount += DataId_node_Y.SetData((FSData)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.ScratchId:
FSScratchNode ScratchId_node_Y = graph.AddNode<FSScratchNode>();
GetPort("Y").Connect(ScratchId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(ScratchId_node_Y, assetPath);
variableCount += ScratchId_node_Y.SetData((FSScratch)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.AnimId:
FSAnimNode AnimId_node_Y = graph.AddNode<FSAnimNode>();
GetPort("Y").Connect(AnimId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(AnimId_node_Y, assetPath);
variableCount += AnimId_node_Y.SetData((FSAnim)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.SpeedId:
FSSpeedNode SpeedId_node_Y = graph.AddNode<FSSpeedNode>();
GetPort("Y").Connect(SpeedId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(SpeedId_node_Y, assetPath);
variableCount += SpeedId_node_Y.SetData((FSSpeed)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.PhysicsId:
FSPhysicsNode PhysicsId_node_Y = graph.AddNode<FSPhysicsNode>();
GetPort("Y").Connect(PhysicsId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(PhysicsId_node_Y, assetPath);
variableCount += PhysicsId_node_Y.SetData((FSPhysics)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.CollisionId:
FSCollisionNode CollisionId_node_Y = graph.AddNode<FSCollisionNode>();
GetPort("Y").Connect(CollisionId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(CollisionId_node_Y, assetPath);
variableCount += CollisionId_node_Y.SetData((FSCollision)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.TimerId:
FSTimerNode TimerId_node_Y = graph.AddNode<FSTimerNode>();
GetPort("Y").Connect(TimerId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(TimerId_node_Y, assetPath);
variableCount += TimerId_node_Y.SetData((FSTimer)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.LagId:
FSLagNode LagId_node_Y = graph.AddNode<FSLagNode>();
GetPort("Y").Connect(LagId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(LagId_node_Y, assetPath);
variableCount += LagId_node_Y.SetData((FSLag)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.EffectsId:
FSEffectsNode EffectsId_node_Y = graph.AddNode<FSEffectsNode>();
GetPort("Y").Connect(EffectsId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(EffectsId_node_Y, assetPath);
variableCount += EffectsId_node_Y.SetData((FSEffects)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.ColorsId:
FSColorsNode ColorsId_node_Y = graph.AddNode<FSColorsNode>();
GetPort("Y").Connect(ColorsId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(ColorsId_node_Y, assetPath);
variableCount += ColorsId_node_Y.SetData((FSColors)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.OnHitId:
FSOnHitNode OnHitId_node_Y = graph.AddNode<FSOnHitNode>();
GetPort("Y").Connect(OnHitId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(OnHitId_node_Y, assetPath);
variableCount += OnHitId_node_Y.SetData((FSOnHit)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.RandomId:
FSRandomNode RandomId_node_Y = graph.AddNode<FSRandomNode>();
GetPort("Y").Connect(RandomId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(RandomId_node_Y, assetPath);
variableCount += RandomId_node_Y.SetData((FSRandom)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.CameraId:
FSCameraInfoNode CameraId_node_Y = graph.AddNode<FSCameraInfoNode>();
GetPort("Y").Connect(CameraId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(CameraId_node_Y, assetPath);
variableCount += CameraId_node_Y.SetData((FSCameraInfo)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.SportsId:
FSSportsNode SportsId_node_Y = graph.AddNode<FSSportsNode>();
GetPort("Y").Connect(SportsId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(SportsId_node_Y, assetPath);
variableCount += SportsId_node_Y.SetData((FSSports)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.Vector2Mag:
FSVector2MagNode Vector2Mag_node_Y = graph.AddNode<FSVector2MagNode>();
GetPort("Y").Connect(Vector2Mag_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(Vector2Mag_node_Y, assetPath);
variableCount += Vector2Mag_node_Y.SetData((FSVector2Mag)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.CPUHelpId:
FSCpuHelpNode CPUHelpId_node_Y = graph.AddNode<FSCpuHelpNode>();
GetPort("Y").Connect(CPUHelpId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(CPUHelpId_node_Y, assetPath);
variableCount += CPUHelpId_node_Y.SetData((FSCpuHelp)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.ItemId:
FSItemNode ItemId_node_Y = graph.AddNode<FSItemNode>();
GetPort("Y").Connect(ItemId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(ItemId_node_Y, assetPath);
variableCount += ItemId_node_Y.SetData((FSItem)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.ModeId:
FSModeNode ModeId_node_Y = graph.AddNode<FSModeNode>();
GetPort("Y").Connect(ModeId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(ModeId_node_Y, assetPath);
variableCount += ModeId_node_Y.SetData((FSMode)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.JumpsId:
FSJumpsNode JumpsId_node_Y = graph.AddNode<FSJumpsNode>();
GetPort("Y").Connect(JumpsId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(JumpsId_node_Y, assetPath);
variableCount += JumpsId_node_Y.SetData((FSJumps)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.RootAnimId:
FSRootAnimNode RootAnimId_node_Y = graph.AddNode<FSRootAnimNode>();
GetPort("Y").Connect(RootAnimId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(RootAnimId_node_Y, assetPath);
variableCount += RootAnimId_node_Y.SetData((FSRootAnim)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
case FloatSource.TypeId.FloatId:
FSValueNode FloatId_node_Y = graph.AddNode<FSValueNode>();
GetPort("Y").Connect(FloatId_node_Y.GetPort("NodeInput"));
AssetDatabase.AddObjectToAsset(FloatId_node_Y, assetPath);
variableCount += FloatId_node_Y.SetData((FSValue)Y, graph, assetPath, nodeDepthXY + new Vector2(1, variableCount));
break;
}
return variableCount;
}
public new SALaunchGrabbedCustom GetData()
{
SALaunchGrabbedCustom objToReturn = new SALaunchGrabbedCustom();
objToReturn.TID = TypeId.LaunchGrabbedCustomId;
objToReturn.Version = Version;
objToReturn.AtkProp = AtkProp;
if (GetPort("X").ConnectionCount > 0)
{
FloatSourceNode FloatSource_Node = (FloatSourceNode)GetPort("X").GetConnection(0).node;
switch (FloatSource_Node.TID)
{
case FloatSource.TypeId.AgentId:
FSAgentNode AgentId_FloatSource_Node = (FSAgentNode)GetPort("X").GetConnection(0).node;
objToReturn.X = AgentId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.BonesId:
FSBonesNode BonesId_FloatSource_Node = (FSBonesNode)GetPort("X").GetConnection(0).node;
objToReturn.X = BonesId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.AttackId:
FSAttackNode AttackId_FloatSource_Node = (FSAttackNode)GetPort("X").GetConnection(0).node;
objToReturn.X = AttackId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.FrameId:
FSFrameNode FrameId_FloatSource_Node = (FSFrameNode)GetPort("X").GetConnection(0).node;
objToReturn.X = FrameId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.InputId:
FSInputNode InputId_FloatSource_Node = (FSInputNode)GetPort("X").GetConnection(0).node;
objToReturn.X = InputId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.FuncId:
FSFuncNode FuncId_FloatSource_Node = (FSFuncNode)GetPort("X").GetConnection(0).node;
objToReturn.X = FuncId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.MovementId:
FSMovementNode MovementId_FloatSource_Node = (FSMovementNode)GetPort("X").GetConnection(0).node;
objToReturn.X = MovementId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.CombatId:
FSCombatNode CombatId_FloatSource_Node = (FSCombatNode)GetPort("X").GetConnection(0).node;
objToReturn.X = CombatId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.GrabsId:
FSGrabsNode GrabsId_FloatSource_Node = (FSGrabsNode)GetPort("X").GetConnection(0).node;
objToReturn.X = GrabsId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.DataId:
FSDataNode DataId_FloatSource_Node = (FSDataNode)GetPort("X").GetConnection(0).node;
objToReturn.X = DataId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.ScratchId:
FSScratchNode ScratchId_FloatSource_Node = (FSScratchNode)GetPort("X").GetConnection(0).node;
objToReturn.X = ScratchId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.AnimId:
FSAnimNode AnimId_FloatSource_Node = (FSAnimNode)GetPort("X").GetConnection(0).node;
objToReturn.X = AnimId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.SpeedId:
FSSpeedNode SpeedId_FloatSource_Node = (FSSpeedNode)GetPort("X").GetConnection(0).node;
objToReturn.X = SpeedId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.PhysicsId:
FSPhysicsNode PhysicsId_FloatSource_Node = (FSPhysicsNode)GetPort("X").GetConnection(0).node;
objToReturn.X = PhysicsId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.CollisionId:
FSCollisionNode CollisionId_FloatSource_Node = (FSCollisionNode)GetPort("X").GetConnection(0).node;
objToReturn.X = CollisionId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.TimerId:
FSTimerNode TimerId_FloatSource_Node = (FSTimerNode)GetPort("X").GetConnection(0).node;
objToReturn.X = TimerId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.LagId:
FSLagNode LagId_FloatSource_Node = (FSLagNode)GetPort("X").GetConnection(0).node;
objToReturn.X = LagId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.EffectsId:
FSEffectsNode EffectsId_FloatSource_Node = (FSEffectsNode)GetPort("X").GetConnection(0).node;
objToReturn.X = EffectsId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.ColorsId:
FSColorsNode ColorsId_FloatSource_Node = (FSColorsNode)GetPort("X").GetConnection(0).node;
objToReturn.X = ColorsId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.OnHitId:
FSOnHitNode OnHitId_FloatSource_Node = (FSOnHitNode)GetPort("X").GetConnection(0).node;
objToReturn.X = OnHitId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.RandomId:
FSRandomNode RandomId_FloatSource_Node = (FSRandomNode)GetPort("X").GetConnection(0).node;
objToReturn.X = RandomId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.CameraId:
FSCameraInfoNode CameraId_FloatSource_Node = (FSCameraInfoNode)GetPort("X").GetConnection(0).node;
objToReturn.X = CameraId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.SportsId:
FSSportsNode SportsId_FloatSource_Node = (FSSportsNode)GetPort("X").GetConnection(0).node;
objToReturn.X = SportsId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.Vector2Mag:
FSVector2MagNode Vector2Mag_FloatSource_Node = (FSVector2MagNode)GetPort("X").GetConnection(0).node;
objToReturn.X = Vector2Mag_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.CPUHelpId:
FSCpuHelpNode CPUHelpId_FloatSource_Node = (FSCpuHelpNode)GetPort("X").GetConnection(0).node;
objToReturn.X = CPUHelpId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.ItemId:
FSItemNode ItemId_FloatSource_Node = (FSItemNode)GetPort("X").GetConnection(0).node;
objToReturn.X = ItemId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.ModeId:
FSModeNode ModeId_FloatSource_Node = (FSModeNode)GetPort("X").GetConnection(0).node;
objToReturn.X = ModeId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.JumpsId:
FSJumpsNode JumpsId_FloatSource_Node = (FSJumpsNode)GetPort("X").GetConnection(0).node;
objToReturn.X = JumpsId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.RootAnimId:
FSRootAnimNode RootAnimId_FloatSource_Node = (FSRootAnimNode)GetPort("X").GetConnection(0).node;
objToReturn.X = RootAnimId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.FloatId:
FSValueNode FloatId_FloatSource_Node = (FSValueNode)GetPort("X").GetConnection(0).node;
objToReturn.X = FloatId_FloatSource_Node.GetData();
break;
}
}
if (GetPort("Y").ConnectionCount > 0)
{
FloatSourceNode FloatSource_Node = (FloatSourceNode)GetPort("Y").GetConnection(0).node;
switch (FloatSource_Node.TID)
{
case FloatSource.TypeId.AgentId:
FSAgentNode AgentId_FloatSource_Node = (FSAgentNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = AgentId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.BonesId:
FSBonesNode BonesId_FloatSource_Node = (FSBonesNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = BonesId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.AttackId:
FSAttackNode AttackId_FloatSource_Node = (FSAttackNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = AttackId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.FrameId:
FSFrameNode FrameId_FloatSource_Node = (FSFrameNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = FrameId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.InputId:
FSInputNode InputId_FloatSource_Node = (FSInputNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = InputId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.FuncId:
FSFuncNode FuncId_FloatSource_Node = (FSFuncNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = FuncId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.MovementId:
FSMovementNode MovementId_FloatSource_Node = (FSMovementNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = MovementId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.CombatId:
FSCombatNode CombatId_FloatSource_Node = (FSCombatNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = CombatId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.GrabsId:
FSGrabsNode GrabsId_FloatSource_Node = (FSGrabsNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = GrabsId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.DataId:
FSDataNode DataId_FloatSource_Node = (FSDataNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = DataId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.ScratchId:
FSScratchNode ScratchId_FloatSource_Node = (FSScratchNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = ScratchId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.AnimId:
FSAnimNode AnimId_FloatSource_Node = (FSAnimNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = AnimId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.SpeedId:
FSSpeedNode SpeedId_FloatSource_Node = (FSSpeedNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = SpeedId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.PhysicsId:
FSPhysicsNode PhysicsId_FloatSource_Node = (FSPhysicsNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = PhysicsId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.CollisionId:
FSCollisionNode CollisionId_FloatSource_Node = (FSCollisionNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = CollisionId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.TimerId:
FSTimerNode TimerId_FloatSource_Node = (FSTimerNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = TimerId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.LagId:
FSLagNode LagId_FloatSource_Node = (FSLagNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = LagId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.EffectsId:
FSEffectsNode EffectsId_FloatSource_Node = (FSEffectsNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = EffectsId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.ColorsId:
FSColorsNode ColorsId_FloatSource_Node = (FSColorsNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = ColorsId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.OnHitId:
FSOnHitNode OnHitId_FloatSource_Node = (FSOnHitNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = OnHitId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.RandomId:
FSRandomNode RandomId_FloatSource_Node = (FSRandomNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = RandomId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.CameraId:
FSCameraInfoNode CameraId_FloatSource_Node = (FSCameraInfoNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = CameraId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.SportsId:
FSSportsNode SportsId_FloatSource_Node = (FSSportsNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = SportsId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.Vector2Mag:
FSVector2MagNode Vector2Mag_FloatSource_Node = (FSVector2MagNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = Vector2Mag_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.CPUHelpId:
FSCpuHelpNode CPUHelpId_FloatSource_Node = (FSCpuHelpNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = CPUHelpId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.ItemId:
FSItemNode ItemId_FloatSource_Node = (FSItemNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = ItemId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.ModeId:
FSModeNode ModeId_FloatSource_Node = (FSModeNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = ModeId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.JumpsId:
FSJumpsNode JumpsId_FloatSource_Node = (FSJumpsNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = JumpsId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.RootAnimId:
FSRootAnimNode RootAnimId_FloatSource_Node = (FSRootAnimNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = RootAnimId_FloatSource_Node.GetData();
break;
case FloatSource.TypeId.FloatId:
FSValueNode FloatId_FloatSource_Node = (FSValueNode)GetPort("Y").GetConnection(0).node;
objToReturn.Y = FloatId_FloatSource_Node.GetData();
break;
}
}
return objToReturn;
}
}
}
| 53.804598 | 129 | 0.730747 | [
"MIT"
] | megalon/nasb-moveset-editor | Scripts/Nodes/StateActions/SALaunchGrabbedCustomNode.cs | 37,448 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Cassette.BundleProcessing;
using Cassette.IO;
using Cassette.Spriting.Spritastic;
using Cassette.Stylesheets;
namespace Cassette.Spriting
{
public class SpriteImages : IBundleProcessor<StylesheetBundle>
{
readonly CassetteSettings settings;
readonly Func<ISpriteGenerator> createSpriteGenerator;
internal SpriteImages(CassetteSettings settings, Func<ISpriteGenerator> createSpriteGenerator)
{
this.settings = settings;
this.createSpriteGenerator = createSpriteGenerator;
}
public void Process(StylesheetBundle bundle)
{
if (settings.IsDebuggingEnabled) return;
if (bundle.Assets.Count == 0) return;
var css = ReadCssFromBundle(bundle);
var spritePackage = GenerateSprites(bundle, css);
ReplaceBundleCss(bundle, spritePackage.GeneratedCss);
SaveSpritesToCache(spritePackage.Sprites);
}
void SaveSpritesToCache(IEnumerable<Sprite> sprites)
{
var spritesDirectory = GetOrCreateSpritesDirectory();
foreach (var sprite in sprites)
{
SaveSpriteToCache(spritesDirectory, sprite);
}
}
IDirectory GetOrCreateSpritesDirectory()
{
var spritesDirectory = settings.CacheDirectory.GetDirectory("sprites");
spritesDirectory.Create();
return spritesDirectory;
}
void SaveSpriteToCache(IDirectory spritesDirectory, Sprite sprite)
{
var path = Regex.Replace(sprite.Url, @"/cassette\.axd/cached/sprites/(.*)$", "$1");
var file = spritesDirectory.GetFile(path);
using (var fileStream = file.Open(FileMode.Create, FileAccess.Write, FileShare.None))
{
fileStream.Write(sprite.Image, 0, sprite.Image.Length);
fileStream.Flush();
}
}
string ReadCssFromBundle(StylesheetBundle bundle)
{
using (var reader = new StreamReader(bundle.Assets[0].OpenStream()))
{
return reader.ReadToEnd();
}
}
SpritePackage GenerateSprites(StylesheetBundle bundle, string css)
{
var generator = createSpriteGenerator();
return generator.GenerateFromCss(css, bundle.Path);
}
void ReplaceBundleCss(StylesheetBundle bundle, string newCss)
{
var spritedCss = new SpritedCss(newCss, bundle.Assets[0]);
bundle.Assets.Clear();
bundle.Assets.Add(spritedCss);
bundle.Hash = spritedCss.Hash;
}
}
} | 34.238095 | 103 | 0.604312 | [
"MIT"
] | DanielWare/cassette | src/Cassette.Spriting/SpriteImages.cs | 2,876 | C# |
using System;
using System.Collections.Generic;
using Physics.Interfaces;
using Physics.Systems;
namespace Physics
{
public class Universe
{
public SortedList<int, IEntity> entities = new SortedList<int, IEntity>();
private Random _rand;
public Infrastructure inf;
public Universe() : this(new Random()){}
public Universe(Random rng)
{
_rand = rng;
inf = new Infrastructure(this, _rand);
}
public int LastEntityId()
{
if(entities.Count == 0) return 0;
return entities.Max().Key;
}
public Entity GetEntity()
{
var ef = new EntityFactory();
var entity = ef.GetEntity(LastEntityId());
entities.Add(entity.Id, entity);
return entity;
}
}
} | 23.324324 | 82 | 0.551564 | [
"MIT"
] | jr101dallas/roguelike-tutorial | physics/Universe.cs | 863 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("model.derivative_csharp.webapi_viewer.sample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("model.derivative_csharp.webapi_viewer.sample")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("44f7518f-0d85-4267-a969-18a9681d533b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.472222 | 84 | 0.755806 | [
"MIT"
] | eugsterli/BIM_IOT_Openhab | ASPNET.webapi/Properties/AssemblyInfo.cs | 1,424 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Abp;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Abplus.MqMessages.AuditingStore")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Abplus.MqMessages.AuditingStore")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("b1585b83-25a5-4c8c-a384-b1205e459c16")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion(AbplusConsts.CurrentVersion)]
[assembly: AssemblyFileVersion(AbplusConsts.CurrentVersion)]
| 27.105263 | 62 | 0.738835 | [
"MIT"
] | 1060877180/abplus | src2/Abplus.MqMessages.AuditingStore/Properties/AssemblyInfo.cs | 1,381 | C# |
using DemoByNuget.Events;
using Microsoft.Extensions.DependencyInjection;
using Reface.Core.EventBus;
using System;
namespace DemoByNuget
{
class Program
{
static void Main(string[] args)
{
IServiceProvider serviceProvider = new ServiceCollection()
.AddEventBus()
.AddEventListeners(typeof(Program).Assembly)
.BuildServiceProvider();
IEventBus eventBus = serviceProvider.GetService<IEventBus>();
eventBus.Publish(new TestEvent(1));
}
}
}
| 24.956522 | 73 | 0.616725 | [
"MIT"
] | ShimizuShiori/EventBus | src/Core/Reface.Core.EventBus/DemoByNuget/Program.cs | 576 | C# |
using System;
using NetOffice;
namespace NetOffice.MSProjectApi.Enums
{
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff867686(v=office.14).aspx </remarks>
[SupportByVersionAttribute("MSProject", 11,12,14)]
[EntityTypeAttribute(EntityType.IsEnum)]
public enum PjRecalcDriverType
{
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>1</remarks>
[SupportByVersionAttribute("MSProject", 11,12,14)]
pjDriverActuals = 1,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>2</remarks>
[SupportByVersionAttribute("MSProject", 11,12,14)]
pjDriverLevelingDelay = 2,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>4</remarks>
[SupportByVersionAttribute("MSProject", 11,12,14)]
pjDriverConstraint = 4,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>8</remarks>
[SupportByVersionAttribute("MSProject", 11,12,14)]
pjDriverPredecessor = 8,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>16</remarks>
[SupportByVersionAttribute("MSProject", 11,12,14)]
pjDriverProjectStart = 16,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>32</remarks>
[SupportByVersionAttribute("MSProject", 11,12,14)]
pjDriverCalendar = 32,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>64</remarks>
[SupportByVersionAttribute("MSProject", 11,12,14)]
pjDriverChildTask = 64,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>128</remarks>
[SupportByVersionAttribute("MSProject", 11,12,14)]
pjDriverParentTask = 128,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>256</remarks>
[SupportByVersionAttribute("MSProject", 11,12,14)]
pjDriverDeadlineTask = 256
}
} | 28.157895 | 132 | 0.651402 | [
"MIT"
] | brunobola/NetOffice | Source/MSProject/Enums/PjRecalcDriverType.cs | 2,142 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MxNet.Contrib
{
public abstract class CalibrationCollector
{
public CalibrationCollector()
{
throw new NotImplementedRelease2Exception();
}
public abstract void Collect(string name, string op_name, NDArray arr);
public virtual Dictionary<string, float> PostCollect()
{
throw new NotImplementedRelease2Exception();
}
}
}
| 22.409091 | 79 | 0.653144 | [
"Apache-2.0"
] | SciSharp/MxNet.Sharp | src/MxNet/Contrib/CalibrationCollector.cs | 495 | 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.
namespace Cake.Common.Net
{
/// <summary>
/// Contains settings for <see cref="HttpAliases"/>
/// </summary>
public sealed class DownloadFileSettings
{
/// <summary>
/// Gets or sets the Username to use when downloading the file
/// </summary>
public string Username { get; set; }
/// <summary>
/// Gets or sets the Password to use when downloading the file
/// </summary>
public string Password { get; set; }
}
} | 32.136364 | 71 | 0.625177 | [
"MIT"
] | cpx86/cake | src/Cake.Common/Net/DownloadFileSettings.cs | 709 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Principal;
using System.Threading;
using CultureInfo = System.Globalization.CultureInfo;
using Luid = Interop.Advapi32.LUID;
using static System.Security.Principal.Win32;
namespace System.Security.AccessControl
{
/// <summary>
/// Managed wrapper for NT privileges
/// </summary>
internal sealed class Privilege
{
[ThreadStatic]
private static TlsContents? t_tlsSlotData;
private static readonly Dictionary<Luid, string> privileges = new Dictionary<Luid, string>();
private static readonly Dictionary<string, Luid> luids = new Dictionary<string, Luid>();
private static readonly ReaderWriterLockSlim privilegeLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
private bool needToRevert;
private bool initialState;
private bool stateWasChanged;
private Luid luid;
private readonly Thread currentThread = Thread.CurrentThread;
private TlsContents? tlsContents;
public const string CreateToken = "SeCreateTokenPrivilege";
public const string AssignPrimaryToken = "SeAssignPrimaryTokenPrivilege";
public const string LockMemory = "SeLockMemoryPrivilege";
public const string IncreaseQuota = "SeIncreaseQuotaPrivilege";
public const string UnsolicitedInput = "SeUnsolicitedInputPrivilege";
public const string MachineAccount = "SeMachineAccountPrivilege";
public const string TrustedComputingBase = "SeTcbPrivilege";
public const string Security = "SeSecurityPrivilege";
public const string TakeOwnership = "SeTakeOwnershipPrivilege";
public const string LoadDriver = "SeLoadDriverPrivilege";
public const string SystemProfile = "SeSystemProfilePrivilege";
public const string SystemTime = "SeSystemtimePrivilege";
public const string ProfileSingleProcess = "SeProfileSingleProcessPrivilege";
public const string IncreaseBasePriority = "SeIncreaseBasePriorityPrivilege";
public const string CreatePageFile = "SeCreatePagefilePrivilege";
public const string CreatePermanent = "SeCreatePermanentPrivilege";
public const string Backup = "SeBackupPrivilege";
public const string Restore = "SeRestorePrivilege";
public const string Shutdown = "SeShutdownPrivilege";
public const string Debug = "SeDebugPrivilege";
public const string Audit = "SeAuditPrivilege";
public const string SystemEnvironment = "SeSystemEnvironmentPrivilege";
public const string ChangeNotify = "SeChangeNotifyPrivilege";
public const string RemoteShutdown = "SeRemoteShutdownPrivilege";
public const string Undock = "SeUndockPrivilege";
public const string SyncAgent = "SeSyncAgentPrivilege";
public const string EnableDelegation = "SeEnableDelegationPrivilege";
public const string ManageVolume = "SeManageVolumePrivilege";
public const string Impersonate = "SeImpersonatePrivilege";
public const string CreateGlobal = "SeCreateGlobalPrivilege";
public const string TrustedCredentialManagerAccess = "SeTrustedCredManAccessPrivilege";
public const string ReserveProcessor = "SeReserveProcessorPrivilege";
//
// This routine is a wrapper around a hashtable containing mappings
// of privilege names to LUIDs
//
private static Luid LuidFromPrivilege(string privilege)
{
Luid luid;
luid.LowPart = 0;
luid.HighPart = 0;
//
// Look up the privilege LUID inside the cache
//
try
{
privilegeLock.EnterReadLock();
if (luids.ContainsKey(privilege))
{
luid = luids[privilege];
privilegeLock.ExitReadLock();
}
else
{
privilegeLock.ExitReadLock();
if (false == Interop.Advapi32.LookupPrivilegeValue(null, privilege, out luid))
{
int error = Marshal.GetLastWin32Error();
if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.Errors.ERROR_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
else if (error == Interop.Errors.ERROR_NO_SUCH_PRIVILEGE)
{
throw new ArgumentException(
SR.Format(SR.Argument_InvalidPrivilegeName,
privilege));
}
else
{
System.Diagnostics.Debug.Fail($"LookupPrivilegeValue() failed with unrecognized error code {error}");
throw new InvalidOperationException();
}
}
privilegeLock.EnterWriteLock();
}
}
finally
{
if (privilegeLock.IsReadLockHeld)
{
privilegeLock.ExitReadLock();
}
if (privilegeLock.IsWriteLockHeld)
{
if (!luids.ContainsKey(privilege))
{
luids[privilege] = luid;
privileges[luid] = privilege;
}
privilegeLock.ExitWriteLock();
}
}
return luid;
}
private sealed class TlsContents : IDisposable
{
private bool disposed;
private int referenceCount = 1;
private SafeTokenHandle? threadHandle = new SafeTokenHandle(IntPtr.Zero);
private readonly bool isImpersonating;
private static volatile SafeTokenHandle processHandle = new SafeTokenHandle(IntPtr.Zero);
private static readonly object syncRoot = new object();
#region Constructor and Finalizer
public TlsContents()
{
int error = 0;
int cachingError = 0;
bool success = true;
if (processHandle.IsInvalid)
{
lock (syncRoot)
{
if (processHandle.IsInvalid)
{
SafeTokenHandle localProcessHandle;
if (false == Interop.Advapi32.OpenProcessToken(
Interop.Kernel32.GetCurrentProcess(),
TokenAccessLevels.Duplicate,
out localProcessHandle))
{
cachingError = Marshal.GetLastWin32Error();
success = false;
}
processHandle = localProcessHandle;
}
}
}
try
{
//
// Open the thread token; if there is no thread token, get one from
// the process token by impersonating self.
//
SafeTokenHandle? threadHandleBefore = this.threadHandle;
error = OpenThreadToken(
TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
WinSecurityContext.Process,
out this.threadHandle);
unchecked { error &= ~(int)0x80070000; }
if (error != 0)
{
if (success == true)
{
this.threadHandle = threadHandleBefore;
if (error != Interop.Errors.ERROR_NO_TOKEN)
{
success = false;
}
System.Diagnostics.Debug.Assert(this.isImpersonating == false, "Incorrect isImpersonating state");
if (success == true)
{
error = 0;
if (false == Interop.Advapi32.DuplicateTokenEx(
processHandle,
TokenAccessLevels.Impersonate | TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
IntPtr.Zero,
Interop.Advapi32.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
System.Security.Principal.TokenType.TokenImpersonation,
ref this.threadHandle))
{
error = Marshal.GetLastWin32Error();
success = false;
}
}
if (success == true)
{
error = SetThreadToken(this.threadHandle);
unchecked { error &= ~(int)0x80070000; }
if (error != 0)
{
success = false;
}
}
if (success == true)
{
this.isImpersonating = true;
}
}
else
{
error = cachingError;
}
}
else
{
success = true;
}
}
finally
{
if (!success)
{
Dispose();
}
}
if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.Errors.ERROR_ACCESS_DENIED ||
error == Interop.Errors.ERROR_CANT_OPEN_ANONYMOUS)
{
throw new UnauthorizedAccessException();
}
else if (error != 0)
{
System.Diagnostics.Debug.Fail($"WindowsIdentity.GetCurrentThreadToken() failed with unrecognized error code {error}");
throw new InvalidOperationException();
}
}
~TlsContents()
{
if (!this.disposed)
{
Dispose(false);
}
}
#endregion
#region IDisposable implementation
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (this.disposed) return;
if (disposing)
{
if (this.threadHandle != null)
{
this.threadHandle.Dispose();
this.threadHandle = null!;
}
}
if (this.isImpersonating)
{
Interop.Advapi32.RevertToSelf();
}
this.disposed = true;
}
#endregion
#region Reference Counting
public void IncrementReferenceCount()
{
this.referenceCount++;
}
public int DecrementReferenceCount()
{
int result = --this.referenceCount;
if (result == 0)
{
Dispose();
}
return result;
}
public int ReferenceCountValue
{
get { return this.referenceCount; }
}
#endregion
#region Properties
public SafeTokenHandle ThreadHandle
{
get
{
return this.threadHandle!;
}
}
public bool IsImpersonating
{
get { return this.isImpersonating; }
}
#endregion
}
#region Constructors
public Privilege(string privilegeName)
{
if (privilegeName == null)
{
throw new ArgumentNullException(nameof(privilegeName));
}
this.luid = LuidFromPrivilege(privilegeName);
}
#endregion
//
// Finalizer simply ensures that the privilege was not leaked
//
~Privilege()
{
System.Diagnostics.Debug.Assert(!this.needToRevert, "Must revert privileges that you alter!");
if (this.needToRevert)
{
Revert();
}
}
#region Public interface
public void Enable()
{
this.ToggleState(true);
}
public bool NeedToRevert
{
get { return this.needToRevert; }
}
#endregion
private unsafe void ToggleState(bool enable)
{
int error = 0;
//
// All privilege operations must take place on the same thread
//
if (!this.currentThread.Equals(Thread.CurrentThread))
{
throw new InvalidOperationException(SR.InvalidOperation_MustBeSameThread);
}
//
// This privilege was already altered and needs to be reverted before it can be altered again
//
if (this.needToRevert)
{
throw new InvalidOperationException(SR.InvalidOperation_MustRevertPrivilege);
}
try
{
//
// Retrieve TLS state
//
this.tlsContents = t_tlsSlotData;
if (this.tlsContents == null)
{
this.tlsContents = new TlsContents();
t_tlsSlotData = this.tlsContents;
}
else
{
this.tlsContents.IncrementReferenceCount();
}
Interop.Advapi32.TOKEN_PRIVILEGE newState;
newState.PrivilegeCount = 1;
newState.Privileges.Luid = this.luid;
newState.Privileges.Attributes = enable ? Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED : Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_DISABLED;
Interop.Advapi32.TOKEN_PRIVILEGE previousState = default;
uint previousSize = 0;
//
// Place the new privilege on the thread token and remember the previous state.
//
if (!Interop.Advapi32.AdjustTokenPrivileges(
this.tlsContents.ThreadHandle,
false,
&newState,
(uint)sizeof(Interop.Advapi32.TOKEN_PRIVILEGE),
&previousState,
&previousSize))
{
error = Marshal.GetLastWin32Error();
}
else if (Interop.Errors.ERROR_NOT_ALL_ASSIGNED == Marshal.GetLastWin32Error())
{
error = Interop.Errors.ERROR_NOT_ALL_ASSIGNED;
}
else
{
//
// This is the initial state that revert will have to go back to
//
this.initialState = ((previousState.Privileges.Attributes & Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED) != 0);
//
// Remember whether state has changed at all
//
this.stateWasChanged = (this.initialState != enable);
//
// If we had to impersonate, or if the privilege state changed we'll need to revert
//
this.needToRevert = this.tlsContents.IsImpersonating || this.stateWasChanged;
}
}
finally
{
if (!this.needToRevert)
{
this.Reset();
}
}
if (error == Interop.Errors.ERROR_NOT_ALL_ASSIGNED)
{
throw new PrivilegeNotHeldException(privileges[this.luid]);
}
if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.Errors.ERROR_ACCESS_DENIED ||
error == Interop.Errors.ERROR_CANT_OPEN_ANONYMOUS)
{
throw new UnauthorizedAccessException();
}
else if (error != 0)
{
System.Diagnostics.Debug.Fail($"AdjustTokenPrivileges() failed with unrecognized error code {error}");
throw new InvalidOperationException();
}
}
public unsafe void Revert()
{
int error = 0;
if (!this.currentThread.Equals(Thread.CurrentThread))
{
throw new InvalidOperationException(SR.InvalidOperation_MustBeSameThread);
}
if (!this.NeedToRevert)
{
return;
}
bool success = true;
try
{
//
// Only call AdjustTokenPrivileges if we're not going to be reverting to self,
// on this Revert, since doing the latter obliterates the thread token anyway
//
if (this.stateWasChanged &&
(this.tlsContents!.ReferenceCountValue > 1 ||
!this.tlsContents.IsImpersonating))
{
Interop.Advapi32.TOKEN_PRIVILEGE newState;
newState.PrivilegeCount = 1;
newState.Privileges.Luid = this.luid;
newState.Privileges.Attributes = (this.initialState ? Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED : Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_DISABLED);
if (!Interop.Advapi32.AdjustTokenPrivileges(
this.tlsContents.ThreadHandle,
false,
&newState,
0,
null,
null))
{
error = Marshal.GetLastWin32Error();
success = false;
}
}
}
finally
{
if (success)
{
this.Reset();
}
}
if (error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.Errors.ERROR_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
else if (error != 0)
{
System.Diagnostics.Debug.Fail($"AdjustTokenPrivileges() failed with unrecognized error code {error}");
throw new InvalidOperationException();
}
}
private void Reset()
{
this.stateWasChanged = false;
this.initialState = false;
this.needToRevert = false;
if (this.tlsContents != null)
{
if (0 == this.tlsContents.DecrementReferenceCount())
{
this.tlsContents = null;
t_tlsSlotData = null;
}
}
}
}
}
| 35.576412 | 180 | 0.472242 | [
"MIT"
] | 333fred/runtime | src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Privilege.cs | 21,417 | C# |
using System;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using Hades.Pager.Entity;
using Hades.Framework.Commons;
using Hades.Framework.ControlUtil;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Hades.HR.Entity;
using Hades.HR.IDAL;
namespace Hades.HR.DALSQL
{
/// <summary>
/// WorkSection
/// </summary>
public class WorkSection : BaseDALSQL<WorkSectionInfo>, IWorkSection
{
#region 对象实例及构造函数
public static WorkSection Instance
{
get
{
return new WorkSection();
}
}
public WorkSection() : base("HR_WorkSection", "Id")
{
}
#endregion
/// <summary>
/// 将DataReader的属性值转化为实体类的属性值,返回实体类
/// </summary>
/// <param name="dr">有效的DataReader对象</param>
/// <returns>实体类对象</returns>
protected override WorkSectionInfo DataReaderToEntity(IDataReader dataReader)
{
WorkSectionInfo info = new WorkSectionInfo();
SmartDataReader reader = new SmartDataReader(dataReader);
info.Id = reader.GetString("Id");
info.Name = reader.GetString("Name");
info.Number = reader.GetString("Number");
info.CompanyId = reader.GetString("CompanyId");
info.Caption = reader.GetString("Caption");
info.SortCode = reader.GetString("SortCode");
info.Remark = reader.GetString("Remark");
info.Editor = reader.GetString("Editor");
info.EditorId = reader.GetString("EditorId");
info.EditTime = reader.GetDateTime("EditTime");
info.Deleted = reader.GetInt32("Deleted");
info.Enabled = reader.GetInt32("Enabled");
return info;
}
/// <summary>
/// 将实体对象的属性值转化为Hashtable对应的键值
/// </summary>
/// <param name="obj">有效的实体对象</param>
/// <returns>包含键值映射的Hashtable</returns>
protected override Hashtable GetHashByEntity(WorkSectionInfo obj)
{
WorkSectionInfo info = obj as WorkSectionInfo;
Hashtable hash = new Hashtable();
hash.Add("Id", info.Id);
hash.Add("Name", info.Name);
hash.Add("Number", info.Number);
hash.Add("CompanyId", info.CompanyId);
hash.Add("Caption", info.Caption);
hash.Add("SortCode", info.SortCode);
hash.Add("Remark", info.Remark);
hash.Add("Editor", info.Editor);
hash.Add("EditorId", info.EditorId);
hash.Add("EditTime", info.EditTime);
hash.Add("Deleted", info.Deleted);
hash.Add("Enabled", info.Enabled);
return hash;
}
/// <summary>
/// 获取字段中文别名(用于界面显示)的字典集合
/// </summary>
/// <returns></returns>
public override Dictionary<string, string> GetColumnNameAlias()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
#region 添加别名解析
//dict.Add("ID", "编号");
dict.Add("Id", "");
dict.Add("Name", "工段名称");
dict.Add("Number", "工段编号");
dict.Add("CompanyId", "所属公司");
dict.Add("Caption", "工段长");
dict.Add("SortCode", "排序码");
dict.Add("Remark", "备注");
dict.Add("Editor", "");
dict.Add("EditorId", "");
dict.Add("EditTime", "");
dict.Add("Deleted", "删除状态");
dict.Add("Enabled", "启用状态");
#endregion
return dict;
}
}
} | 32.210526 | 85 | 0.549564 | [
"Apache-2.0"
] | robertzml/Hades.HR | Hades.HR.Core/DAL/DALSQL/Base/WorkSection.cs | 3,930 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Hello_Universal
{
public class Application
{
/// <summary>
/// This is the main entry point of the application.
/// </summary>
static void Main (string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main (args, null, "AppDelegate");
}
}
}
| 21.681818 | 82 | 0.710692 | [
"Apache-2.0"
] | Acidburn0zzz/monotouch-samples | Hello_Universal/Main.cs | 477 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BombNumber")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BombNumber")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("85c5d85b-2163-4e8e-bdfb-26b8b09dcc57")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.648649 | 84 | 0.744436 | [
"MIT"
] | arobertov/Programming-fundametals-course | ListExercises/BombNumber/Properties/AssemblyInfo.cs | 1,396 | C# |
using System;
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.TestingHost;
namespace TestExtensions
{
public abstract class TestClusterPerTest : OrleansTestingBase, IDisposable
{
private readonly ExceptionDispatchInfo preconditionsException;
static TestClusterPerTest()
{
TestDefaultConfiguration.InitializeDefaults();
}
protected TestCluster HostedCluster { get; private set; }
internal IInternalClusterClient InternalClient => (IInternalClusterClient)this.Client;
public IClusterClient Client => this.HostedCluster.Client;
protected IGrainFactory GrainFactory => this.Client;
protected ILogger Logger => this.logger;
protected ILogger logger;
protected TestClusterPerTest()
{
try
{
CheckPreconditionsOrThrow();
}
catch (Exception ex)
{
this.preconditionsException = ExceptionDispatchInfo.Capture(ex);
return;
}
var builder = new TestClusterBuilder();
TestDefaultConfiguration.ConfigureTestCluster(builder);
builder.ConfigureLegacyConfiguration();
this.ConfigureTestCluster(builder);
var testCluster = builder.Build();
if (testCluster.Primary == null)
{
testCluster.Deploy();
}
this.HostedCluster = testCluster;
this.logger = this.Client.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("Application");
}
public void EnsurePreconditionsMet()
{
this.preconditionsException?.Throw();
}
protected virtual void CheckPreconditionsOrThrow() { }
protected virtual void ConfigureTestCluster(TestClusterBuilder builder)
{
}
public virtual void Dispose()
{
this.HostedCluster?.StopAllSilos();
}
}
} | 29.746479 | 119 | 0.629261 | [
"MIT"
] | 1007lu/orleans | test/TestInfrastructure/TestExtensions/TestClusterPerTest.cs | 2,112 | C# |
using System.Collections.Generic;
using Antlr4.Runtime.Tree;
using Mellis.Core.Entities;
using Mellis.Lang.Python3.Exceptions;
using Mellis.Lang.Python3.Extensions;
using Mellis.Lang.Python3.Resources;
using Mellis.Lang.Python3.Syntax;
using Mellis.Lang.Python3.Syntax.Statements;
namespace Mellis.Lang.Python3.Grammar
{
public partial class SyntaxConstructor
{
public override SyntaxNode VisitAssert_stmt(Python3Parser.Assert_stmtContext context)
{
throw context.NotYetImplementedException("assert");
}
public override SyntaxNode VisitAsync_stmt(Python3Parser.Async_stmtContext context)
{
throw context.NotYetImplementedException("async");
}
public override SyntaxNode VisitIf_stmt(Python3Parser.If_stmtContext context)
{
// if_stmt: 'if' test ':' suite
// ('elif' test ':' suite)*
// ['else' ':' suite]
context.GetChildOrThrow(0, Python3Parser.IF);
Python3Parser.TestContext testRule = context.GetChildOrThrow<Python3Parser.TestContext>(1);
context.GetChildOrThrow(2, Python3Parser.COLON)
.ThrowIfMissing(nameof(Localized_Python3_Parser.Ex_Syntax_If_MissingColon));
Python3Parser.SuiteContext suiteRule = context.GetChildOrThrow<Python3Parser.SuiteContext>(3);
ExpressionNode testExpr = VisitTest(testRule)
.AsTypeOrThrow<ExpressionNode>();
Statement suiteStmt = VisitSuite(suiteRule)
.AsTypeOrThrow<Statement>();
Statement elseStmt = null;
var elIfStatements = new List<(
SourceReference source,
ExpressionNode testExpr,
Statement suite
)>();
// note: increment by 4
for (int i = 4; i < context.ChildCount; i += 4)
{
ITerminalNode elseOrElif = context.GetChildOrThrow<ITerminalNode>(i);
switch (elseOrElif.Symbol.Type)
{
case Python3Parser.ELSE when elseStmt != null:
case Python3Parser.ELIF when elseStmt != null:
throw context.UnexpectedChildType(elseOrElif);
case Python3Parser.ELIF:
Python3Parser.TestContext elifTestRule = context.GetChildOrThrow<Python3Parser.TestContext>(i + 1);
context.GetChildOrThrow(i + 2, Python3Parser.COLON)
.ThrowIfMissing(nameof(Localized_Python3_Parser.Ex_Syntax_If_Elif_MissingColon));
Python3Parser.SuiteContext elifSuiteRule =
context.GetChildOrThrow<Python3Parser.SuiteContext>(i + 3);
ExpressionNode elifExpr = VisitTest(elifTestRule)
.AsTypeOrThrow<ExpressionNode>();
Statement elifStmt = VisitSuite(elifSuiteRule)
.AsTypeOrThrow<Statement>();
var source = SourceReference.Merge(
elseOrElif.GetSourceReference(),
elifSuiteRule.GetSourceReference()
);
elIfStatements.Add((
source,
elifExpr,
elifStmt
));
break;
case Python3Parser.ELSE:
context.GetChildOrThrow(i + 1, Python3Parser.COLON)
.ThrowIfMissing(nameof(Localized_Python3_Parser.Ex_Syntax_If_Else_MissingColon));
Python3Parser.SuiteContext elseRule = context.GetChildOrThrow<Python3Parser.SuiteContext>(i + 2);
elseStmt = VisitSuite(elseRule)
.AsTypeOrThrow<Statement>();
break;
default:
throw context.UnexpectedChildType(elseOrElif);
}
}
// Combine elif statements into the elseStmt var
for (int i = elIfStatements.Count - 1; i >= 0; i--)
{
(SourceReference elifSource,
ExpressionNode elifCondition,
Statement elifSuite) = elIfStatements[i];
elseStmt = new IfStatement(
source: elifSource,
condition: elifCondition,
ifSuite: elifSuite,
elseSuite: elseStmt
);
}
return new IfStatement(context.GetSourceReference(),
condition: testExpr,
ifSuite: suiteStmt,
elseSuite: elseStmt
);
}
public override SyntaxNode VisitWhile_stmt(Python3Parser.While_stmtContext context)
{
// while_stmt: 'while' test ':' suite ['else' ':' suite]
context.GetChildOrThrow(0, Python3Parser.WHILE);
Python3Parser.TestContext testNode = context.GetChildOrThrow<Python3Parser.TestContext>(1);
context.GetChildOrThrow(2, Python3Parser.COLON)
.ThrowIfMissing(nameof(Localized_Python3_Parser.Ex_Syntax_While_MissingColon));
Python3Parser.SuiteContext suiteNode = context.GetChildOrThrow<Python3Parser.SuiteContext>(3);
if (context.ChildCount > 4)
{
ITerminalNode elseTerm = context.GetChildOrThrow(4, Python3Parser.ELSE);
context.GetChildOrThrow(5, Python3Parser.COLON)
.ThrowIfMissing(nameof(Localized_Python3_Parser.Ex_Syntax_While_Else_MissingColon));
context.GetChildOrThrow<Python3Parser.SuiteContext>(6);
if (context.ChildCount > 7)
{
throw context.UnexpectedChildType(context.GetChild(7));
}
throw elseTerm.NotYetImplementedException("while..else");
}
ExpressionNode testExpr = VisitTest(testNode)
.AsTypeOrThrow<ExpressionNode>();
Statement suiteStmt = VisitSuite(suiteNode)
.AsTypeOrThrow<Statement>();
return new WhileStatement(context.GetSourceReference(), testExpr, suiteStmt);
}
public override SyntaxNode VisitFor_stmt(Python3Parser.For_stmtContext context)
{
// for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
context.GetChildOrThrow(0, Python3Parser.FOR);
Python3Parser.ExprlistContext operandNode = context.GetChildOrThrow<Python3Parser.ExprlistContext>(1);
context.GetChildOrThrow(2, Python3Parser.IN)
.ThrowIfMissing(nameof(Localized_Python3_Parser.Ex_Syntax_For_MissingIn));
Python3Parser.TestlistContext iterNode = context.GetChildOrThrow<Python3Parser.TestlistContext>(3);
context.GetChildOrThrow(4, Python3Parser.COLON)
.ThrowIfMissing(nameof(Localized_Python3_Parser.Ex_Syntax_For_MissingColon));
Python3Parser.SuiteContext suiteNode = context.GetChildOrThrow<Python3Parser.SuiteContext>(5);
if (context.ChildCount > 6)
{
ITerminalNode elseTerm = context.GetChildOrThrow(6, Python3Parser.ELSE);
context.GetChildOrThrow(7, Python3Parser.COLON)
.ThrowIfMissing(nameof(Localized_Python3_Parser.Ex_Syntax_For_Else_MissingColon));
context.GetChildOrThrow<Python3Parser.SuiteContext>(8);
if (context.ChildCount > 9)
{
throw context.UnexpectedChildType(context.GetChild(9));
}
throw elseTerm.NotYetImplementedException("for..else");
}
ExpressionNode operandExpr = VisitExprlist(operandNode)
.AsTypeOrThrow<ExpressionNode>();
ExpressionNode iterExpr = VisitTestlist(iterNode)
.AsTypeOrThrow<ExpressionNode>();
Statement suiteStmt = VisitSuite(suiteNode)
.AsTypeOrThrow<Statement>();
return new ForStatement(context.GetSourceReference(), operandExpr, iterExpr, suiteStmt);
}
public override SyntaxNode VisitTry_stmt(Python3Parser.Try_stmtContext context)
{
throw context.NotYetImplementedException("try");
}
public override SyntaxNode VisitWith_stmt(Python3Parser.With_stmtContext context)
{
throw context.NotYetImplementedException("with");
}
}
} | 42.606965 | 119 | 0.60007 | [
"MIT"
] | jontebackis4/TestCompiler | src/Mellis.Lang.Python3/Grammar/SyntaxConstructor.Compound.cs | 8,566 | C# |
//
// RedundantObjectCreationArgumentListIssueTests.cs
//
// Author:
// Mansheng Yang <lightyang0@gmail.com>
//
// Copyright (c) 2012 Mansheng Yang <lightyang0@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using ICSharpCode.NRefactory.CSharp.Refactoring;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.CSharp.CodeIssues
{
[TestFixture]
public class RedundantObjectCreationArgumentListIssueTests : InspectionActionTestBase
{
[Test]
public void Test ()
{
var input = @"
class TestClass
{
public int Prop { get; set; }
void TestMethod ()
{
var x = new TestClass () {
Prop = 1
};
}
}";
var output = @"
class TestClass
{
public int Prop { get; set; }
void TestMethod ()
{
var x = new TestClass {
Prop = 1
};
}
}";
Test<RedundantObjectCreationArgumentListIssue> (input, 1, output);
}
[Test]
public void TestNoIssue ()
{
var input = @"
class TestClass
{
public TestClass () { }
public TestClass (int i) { }
void TestMethod ()
{
var x = new TestClass { };
var y = new TestClass (1) { };
}
}";
Test<RedundantObjectCreationArgumentListIssue> (input, 0);
}
}
}
| 26.240964 | 86 | 0.714876 | [
"MIT"
] | 4lab/ILSpy | NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/RedundantObjectCreationArgumentListIssueTests.cs | 2,180 | C# |
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using System.Text;
namespace Cosmos.Test
{
/// <summary>Helper class that weaver populates with all writer types.</summary>
// Note that c# creates a different static variable for each type
// -> Weaver.ReaderWriterProcessor.InitializeReaderAndWriters() populates it
public static class Writer<T>
{
public static Action<NetworkWriter, T> write;
}
/// <summary>Network Writer for most simple types like floats, ints, buffers, structs, etc. Use NetworkWriterPool.GetReader() to avoid allocations.</summary>
public class NetworkWriter
{
public const int MaxStringLength = 1024 * 32;
// create writer immediately with it's own buffer so no one can mess with it and so that we can resize it.
// note: BinaryWriter allocates too much, so we only use a MemoryStream
// => 1500 bytes by default because on average, most packets will be <= MTU
byte[] buffer = new byte[1500];
// 'int' is the best type for .Position. 'short' is too small if we send >32kb which would result in negative .Position
// -> converting long to int is fine until 2GB of data (MAX_INT), so we don't have to worry about overflows here
int position;
int length;
/// <summary>Number of bytes writen to the buffer</summary>
public int Length => length;
/// <summary>Next position to write to the buffer</summary>
public int Position
{
get => position;
set
{
position = value;
EnsureLength(value);
}
}
/// <summary>Reset both the position and length of the stream</summary>
// Leaves the capacity the same so that we can reuse this writer without
// extra allocations
public void Reset()
{
position = 0;
length = 0;
}
/// <summary>Sets length, moves position if it is greater than new length</summary>
/// Zeros out any extra length created by setlength
public void SetLength(int newLength)
{
int oldLength = length;
// ensure length & capacity
EnsureLength(newLength);
// zero out new length
if (oldLength < newLength)
{
Array.Clear(buffer, oldLength, newLength - oldLength);
}
length = newLength;
position = Mathf.Min(position, length);
}
void EnsureLength(int value)
{
if (length < value)
{
length = value;
EnsureCapacity(value);
}
}
void EnsureCapacity(int value)
{
if (buffer.Length < value)
{
int capacity = Math.Max(value, buffer.Length * 2);
Array.Resize(ref buffer, capacity);
}
}
/// <summary>Copies buffer to new array of size 'Length'. Ignores 'Position'.</summary>
public byte[] ToArray()
{
byte[] data = new byte[length];
Array.ConstrainedCopy(buffer, 0, data, 0, length);
return data;
}
/// <summary>Returns allocatin-free ArraySegment which points to buffer up to 'Length' (ignores 'Position').</summary>
public ArraySegment<byte> ToArraySegment()
{
return new ArraySegment<byte>(buffer, 0, length);
}
public void WriteByte(byte value)
{
EnsureLength(position + 1);
buffer[position++] = value;
}
// for byte arrays with consistent size, where the reader knows how many to read
// (like a packet opcode that's always the same)
public void WriteBytes(byte[] buffer, int offset, int count)
{
EnsureLength(position + count);
Array.ConstrainedCopy(buffer, offset, this.buffer, position, count);
position += count;
}
/// <summary>Writes any type that mirror supports. Uses weaver populated Writer(T).write.</summary>
public void Write<T>(T value)
{
Action<NetworkWriter, T> writeDelegate = Writer<T>.write;
if (writeDelegate == null)
{
Debug.LogError($"No writer found for {typeof(T)}. Use a type supported by Mirror or define a custom writer");
}
else
{
writeDelegate(this, value);
}
}
}
// Mirror's Weaver automatically detects all NetworkWriter function types,
// but they do all need to be extensions.
public static class NetworkWriterExtensions
{
// cache encoding instead of creating it with BinaryWriter each time
// 1000 readers before: 1MB GC, 30ms
// 1000 readers after: 0.8MB GC, 18ms
static readonly UTF8Encoding encoding = new UTF8Encoding(false, true);
static readonly byte[] stringBuffer = new byte[NetworkWriter.MaxStringLength];
public static void WriteByte(this NetworkWriter writer, byte value) => writer.WriteByte(value);
public static void WriteSByte(this NetworkWriter writer, sbyte value) => writer.WriteByte((byte)value);
public static void WriteChar(this NetworkWriter writer, char value) => writer.WriteUInt16(value);
public static void WriteBoolean(this NetworkWriter writer, bool value) => writer.WriteByte((byte)(value ? 1 : 0));
public static void WriteUInt16(this NetworkWriter writer, ushort value)
{
writer.WriteByte((byte)value);
writer.WriteByte((byte)(value >> 8));
}
public static void WriteInt16(this NetworkWriter writer, short value) => writer.WriteUInt16((ushort)value);
public static void WriteUInt32(this NetworkWriter writer, uint value)
{
writer.WriteByte((byte)value);
writer.WriteByte((byte)(value >> 8));
writer.WriteByte((byte)(value >> 16));
writer.WriteByte((byte)(value >> 24));
}
public static void WriteInt32(this NetworkWriter writer, int value) => writer.WriteUInt32((uint)value);
public static void WriteUInt64(this NetworkWriter writer, ulong value)
{
writer.WriteByte((byte)value);
writer.WriteByte((byte)(value >> 8));
writer.WriteByte((byte)(value >> 16));
writer.WriteByte((byte)(value >> 24));
writer.WriteByte((byte)(value >> 32));
writer.WriteByte((byte)(value >> 40));
writer.WriteByte((byte)(value >> 48));
writer.WriteByte((byte)(value >> 56));
}
public static void WriteInt64(this NetworkWriter writer, long value) => writer.WriteUInt64((ulong)value);
public static void WriteSingle(this NetworkWriter writer, float value)
{
UIntFloat converter = new UIntFloat
{
floatValue = value
};
writer.WriteUInt32(converter.intValue);
}
public static void WriteDouble(this NetworkWriter writer, double value)
{
UIntDouble converter = new UIntDouble
{
doubleValue = value
};
writer.WriteUInt64(converter.longValue);
}
public static void WriteDecimal(this NetworkWriter writer, decimal value)
{
// the only way to read it without allocations is to both read and
// write it with the FloatConverter (which is not binary compatible
// to writer.Write(decimal), hence why we use it here too)
UIntDecimal converter = new UIntDecimal
{
decimalValue = value
};
writer.WriteUInt64(converter.longValue1);
writer.WriteUInt64(converter.longValue2);
}
public static void WriteString(this NetworkWriter writer, string value)
{
// write 0 for null support, increment real size by 1
// (note: original HLAPI would write "" for null strings, but if a
// string is null on the server then it should also be null
// on the client)
if (value == null)
{
writer.WriteUInt16(0);
return;
}
// write string with same method as NetworkReader
// convert to byte[]
int size = encoding.GetBytes(value, 0, value.Length, stringBuffer, 0);
// check if within max size
if (size >= NetworkWriter.MaxStringLength)
{
throw new IndexOutOfRangeException("NetworkWriter.Write(string) too long: " + size + ". Limit: " + NetworkWriter.MaxStringLength);
}
// write size and bytes
writer.WriteUInt16(checked((ushort)(size + 1)));
writer.WriteBytes(stringBuffer, 0, size);
}
// for byte arrays with dynamic size, where the reader doesn't know how many will come
// (like an inventory with different items etc.)
public static void WriteBytesAndSize(this NetworkWriter writer, byte[] buffer, int offset, int count)
{
// null is supported because [SyncVar]s might be structs with null byte[] arrays
// write 0 for null array, increment normal size by 1 to save bandwidth
// (using size=-1 for null would limit max size to 32kb instead of 64kb)
if (buffer == null)
{
writer.WriteUInt32(0u);
return;
}
writer.WriteUInt32(checked((uint)count) + 1u);
writer.WriteBytes(buffer, offset, count);
}
// Weaver needs a write function with just one byte[] parameter
// (we don't name it .Write(byte[]) because it's really a WriteBytesAndSize since we write size / null info too)
public static void WriteBytesAndSize(this NetworkWriter writer, byte[] buffer)
{
// buffer might be null, so we can't use .Length in that case
writer.WriteBytesAndSize(buffer, 0, buffer != null ? buffer.Length : 0);
}
public static void WriteBytesAndSizeSegment(this NetworkWriter writer, ArraySegment<byte> buffer)
{
writer.WriteBytesAndSize(buffer.Array, buffer.Offset, buffer.Count);
}
public static void WriteVector2(this NetworkWriter writer, Vector2 value)
{
writer.WriteSingle(value.x);
writer.WriteSingle(value.y);
}
public static void WriteVector3(this NetworkWriter writer, Vector3 value)
{
writer.WriteSingle(value.x);
writer.WriteSingle(value.y);
writer.WriteSingle(value.z);
}
public static void WriteVector4(this NetworkWriter writer, Vector4 value)
{
writer.WriteSingle(value.x);
writer.WriteSingle(value.y);
writer.WriteSingle(value.z);
writer.WriteSingle(value.w);
}
public static void WriteVector2Int(this NetworkWriter writer, Vector2Int value)
{
writer.WriteInt32(value.x);
writer.WriteInt32(value.y);
}
public static void WriteVector3Int(this NetworkWriter writer, Vector3Int value)
{
writer.WriteInt32(value.x);
writer.WriteInt32(value.y);
writer.WriteInt32(value.z);
}
public static void WriteColor(this NetworkWriter writer, Color value)
{
writer.WriteSingle(value.r);
writer.WriteSingle(value.g);
writer.WriteSingle(value.b);
writer.WriteSingle(value.a);
}
public static void WriteColor32(this NetworkWriter writer, Color32 value)
{
writer.WriteByte(value.r);
writer.WriteByte(value.g);
writer.WriteByte(value.b);
writer.WriteByte(value.a);
}
public static void WriteQuaternion(this NetworkWriter writer, Quaternion value)
{
writer.WriteSingle(value.x);
writer.WriteSingle(value.y);
writer.WriteSingle(value.z);
writer.WriteSingle(value.w);
}
public static void WriteRect(this NetworkWriter writer, Rect value)
{
writer.WriteSingle(value.xMin);
writer.WriteSingle(value.yMin);
writer.WriteSingle(value.width);
writer.WriteSingle(value.height);
}
public static void WritePlane(this NetworkWriter writer, Plane value)
{
writer.WriteVector3(value.normal);
writer.WriteSingle(value.distance);
}
public static void WriteRay(this NetworkWriter writer, Ray value)
{
writer.WriteVector3(value.origin);
writer.WriteVector3(value.direction);
}
public static void WriteMatrix4x4(this NetworkWriter writer, Matrix4x4 value)
{
writer.WriteSingle(value.m00);
writer.WriteSingle(value.m01);
writer.WriteSingle(value.m02);
writer.WriteSingle(value.m03);
writer.WriteSingle(value.m10);
writer.WriteSingle(value.m11);
writer.WriteSingle(value.m12);
writer.WriteSingle(value.m13);
writer.WriteSingle(value.m20);
writer.WriteSingle(value.m21);
writer.WriteSingle(value.m22);
writer.WriteSingle(value.m23);
writer.WriteSingle(value.m30);
writer.WriteSingle(value.m31);
writer.WriteSingle(value.m32);
writer.WriteSingle(value.m33);
}
public static void WriteGuid(this NetworkWriter writer, Guid value)
{
byte[] data = value.ToByteArray();
writer.WriteBytes(data, 0, data.Length);
}
public static void WriteUri(this NetworkWriter writer, Uri uri)
{
writer.WriteString(uri.ToString());
}
public static void WriteList<T>(this NetworkWriter writer, List<T> list)
{
if (list is null)
{
writer.WriteInt32(-1);
return;
}
writer.WriteInt32(list.Count);
for (int i = 0; i < list.Count; i++)
writer.Write(list[i]);
}
public static void WriteArray<T>(this NetworkWriter writer, T[] array)
{
if (array is null)
{
writer.WriteInt32(-1);
return;
}
writer.WriteInt32(array.Length);
for (int i = 0; i < array.Length; i++)
writer.Write(array[i]);
}
public static void WriteArraySegment<T>(this NetworkWriter writer, ArraySegment<T> segment)
{
int length = segment.Count;
writer.WriteInt32(length);
for (int i = 0; i < length; i++)
{
writer.Write(segment.Array[segment.Offset + i]);
}
}
}
} | 39.68171 | 165 | 0.530588 | [
"MIT"
] | DonHitYep/CosmosFramework | Assets/Examples/ExampleScripts/Network/NetworkComponent/Components/NetworkWriter.cs | 16,708 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using Diadoc.Api.Cryptography;
using Diadoc.Api.Http;
using Diadoc.Api.Proto;
using Diadoc.Api.Proto.Certificates;
using Diadoc.Api.Proto.Docflow;
using Diadoc.Api.Proto.Documents;
using Diadoc.Api.Proto.Documents.Types;
using Diadoc.Api.Proto.Dss;
using Diadoc.Api.Proto.Employees.Subscriptions;
using Diadoc.Api.Proto.Employees;
using Diadoc.Api.Proto.Employees.PowersOfAttorney;
using Diadoc.Api.Proto.Events;
using Diadoc.Api.Proto.Forwarding;
using Diadoc.Api.Proto.Invoicing;
using Diadoc.Api.Proto.Invoicing.Signers;
using Diadoc.Api.Proto.KeyValueStorage;
using Diadoc.Api.Proto.Organizations;
using Diadoc.Api.Proto.PowersOfAttorney;
using Diadoc.Api.Proto.Recognition;
using Diadoc.Api.Proto.Registration;
using Diadoc.Api.Proto.Users;
using JetBrains.Annotations;
using Department = Diadoc.Api.Proto.Department;
using DocumentType = Diadoc.Api.Proto.DocumentType;
using Employee = Diadoc.Api.Proto.Employees.Employee;
using Departments = Diadoc.Api.Proto.Departments;
using RevocationRequestInfo = Diadoc.Api.Proto.Invoicing.RevocationRequestInfo;
namespace Diadoc.Api
{
public partial class DiadocApi : IDiadocApi
{
private readonly DiadocHttpApi diadocHttpApi;
public DiadocApi(string apiClientId, string diadocApiBaseUrl, ICrypt crypt)
: this(new DiadocHttpApi(apiClientId, new HttpClient(diadocApiBaseUrl), crypt))
{
}
public DiadocApi([NotNull] DiadocHttpApi diadocHttpApi)
{
if (diadocHttpApi == null) throw new ArgumentNullException("diadocHttpApi");
this.diadocHttpApi = diadocHttpApi;
Docflow = new DocflowApi(diadocHttpApi.Docflow);
}
/// <summary>
/// The default value is true
/// </summary>
public bool UsingSystemProxy
{
get { return diadocHttpApi.HttpClient.UseSystemProxy; }
}
public IDocflowApi Docflow { get; }
public void SetProxyUri([CanBeNull] string uri)
{
diadocHttpApi.HttpClient.SetProxyUri(uri);
}
public void EnableSystemProxyUsage()
{
diadocHttpApi.HttpClient.UseSystemProxy = true;
}
public void DisableSystemProxyUsage()
{
diadocHttpApi.HttpClient.UseSystemProxy = false;
}
public void SetProxyCredentials([CanBeNull] NetworkCredential proxyCredentials)
{
diadocHttpApi.HttpClient.SetProxyCredentials(proxyCredentials);
}
public void SetProxyCredentials([NotNull] string user, [NotNull] string password)
{
diadocHttpApi.HttpClient.SetProxyCredentials(user, password);
}
public void SetProxyCredentials([NotNull] string user, [NotNull] SecureString password)
{
diadocHttpApi.HttpClient.SetProxyCredentials(user, password);
}
public string Authenticate(string login, string password, string key = null, string id = null)
{
return diadocHttpApi.Authenticate(login, password, key, id);
}
public string AuthenticateByKey([NotNull] string key, [NotNull] string id)
{
if (key == null) throw new ArgumentNullException("key");
if (id == null) throw new ArgumentNullException("id");
return diadocHttpApi.AuthenticateByKey(key, id);
}
public string AuthenticateBySid([NotNull] string sid)
{
if (sid == null) throw new ArgumentNullException("sid");
return diadocHttpApi.AuthenticateBySid(sid);
}
public string Authenticate(byte[] certificateBytes, bool useLocalSystemStorage = false)
{
if (certificateBytes == null) throw new ArgumentNullException("certificateBytes");
return diadocHttpApi.Authenticate(certificateBytes, useLocalSystemStorage);
}
public string Authenticate(string thumbprint, bool useLocalSystemStorage = false)
{
if (thumbprint == null) throw new ArgumentNullException("thumbprint");
return diadocHttpApi.Authenticate(thumbprint, useLocalSystemStorage);
}
public string AuthenticateWithKey(string thumbprint, bool useLocalSystemStorage = false, string key = null, string id = null, bool autoConfirm = true)
{
if (thumbprint == null) throw new ArgumentNullException("thumbprint");
return diadocHttpApi.AuthenticateWithKey(thumbprint, useLocalSystemStorage, key, id, autoConfirm);
}
public string AuthenticateWithKey(byte[] certificateBytes, bool useLocalSystemStorage = false, string key = null, string id = null, bool autoConfirm = true)
{
if (certificateBytes == null) throw new ArgumentNullException("certificateBytes");
return diadocHttpApi.AuthenticateWithKey(certificateBytes, useLocalSystemStorage, key, id, autoConfirm);
}
public string AuthenticateWithKeyConfirm(byte[] certificateBytes, string token, bool saveBinding = false)
{
if (certificateBytes == null) throw new ArgumentNullException("certificateBytes");
if (string.IsNullOrEmpty(token)) throw new ArgumentNullException("token");
return diadocHttpApi.AuthenticateWithKeyConfirm(certificateBytes, token, saveBinding);
}
public string AuthenticateWithKeyConfirm(string thumbprint, string token, bool saveBinding = false)
{
if (thumbprint == null) throw new ArgumentNullException("thumbprint");
if (string.IsNullOrEmpty(token)) throw new ArgumentNullException("token");
return diadocHttpApi.AuthenticateWithKeyConfirm(thumbprint, token, saveBinding);
}
public OrganizationUserPermissions GetMyPermissions(string authToken, string orgId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (orgId == null) throw new ArgumentNullException("orgId");
return diadocHttpApi.GetMyPermissions(authToken, orgId);
}
public OrganizationList GetMyOrganizations(string authToken, bool autoRegister = true)
{
if (authToken == null) throw new ArgumentNullException("authToken");
return diadocHttpApi.GetMyOrganizations(authToken, autoRegister);
}
public User GetMyUser(string authToken)
{
if (authToken == null) throw new ArgumentNullException("authToken");
return diadocHttpApi.GetMyUser(authToken);
}
public UserV2 GetMyUserV2(string authToken)
{
if (authToken == null) throw new ArgumentNullException("authToken");
return diadocHttpApi.GetMyUserV2(authToken);
}
public UserV2 UpdateMyUser(string authToken, UserToUpdate userToUpdate)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (userToUpdate == null) throw new ArgumentNullException("userToUpdate");
return diadocHttpApi.UpdateMyUser(authToken, userToUpdate);
}
public CertificateList GetMyCertificates(string authToken, string boxId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetMyCertificates(authToken, boxId);
}
public OrganizationList GetOrganizationsByInnKpp(string inn, string kpp, bool includeRelations = false)
{
if (inn == null) throw new ArgumentNullException("inn");
return diadocHttpApi.GetOrganizationsByInnKpp(inn, kpp, includeRelations);
}
public Organization GetOrganizationById(string orgId)
{
if (orgId == null) throw new ArgumentNullException("orgId");
return diadocHttpApi.GetOrganizationById(orgId);
}
public Organization GetOrganizationByBoxId(string boxId)
{
if (boxId == null) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetOrganizationByBoxId(boxId);
}
public Organization GetOrganizationByFnsParticipantId(string fnsParticipantId)
{
if (fnsParticipantId == null) throw new ArgumentException("fnsParticipantId");
return diadocHttpApi.GetOrganizationByFnsParticipantId(fnsParticipantId);
}
public Organization GetOrganizationByInnKpp(string inn, string kpp)
{
if (inn == null) throw new ArgumentException("inn");
return diadocHttpApi.GetOrganizationByInnKpp(inn, kpp);
}
public Box GetBox(string boxId)
{
if (boxId == null) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetBox(boxId);
}
public Department GetDepartment(string authToken, string orgId, string departmentId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (orgId == null) throw new ArgumentNullException("orgId");
if (departmentId == null) throw new ArgumentNullException("departmentId");
return diadocHttpApi.GetDepartment(authToken, orgId, departmentId);
}
public void UpdateOrganizationProperties(string authToken, OrganizationPropertiesToUpdate orgProps)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (orgProps == null) throw new ArgumentNullException("orgProps");
diadocHttpApi.UpdateOrganizationProperties(authToken, orgProps);
}
public OrganizationFeatures GetOrganizationFeatures(string authToken, string boxId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetOrganizationFeatures(authToken, boxId);
}
public BoxEventList GetNewEvents(
string authToken,
string boxId,
string afterEventId = null,
string afterIndexKey = null,
string departmentId = null,
string[] messageTypes = null,
string[] typeNamedIds = null,
string[] documentDirections = null,
long? timestampFromTicks = null,
long? timestampToTicks = null,
string counteragentBoxId = null,
string orderBy = null,
int? limit = null)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetNewEvents(authToken, boxId, afterEventId, afterIndexKey, departmentId, messageTypes, typeNamedIds, documentDirections, timestampFromTicks, timestampToTicks, counteragentBoxId, orderBy, limit);
}
public BoxEvent GetEvent(string authToken, string boxId, string eventId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (eventId == null) throw new ArgumentNullException("eventId");
return diadocHttpApi.GetEvent(authToken, boxId, eventId);
}
public Message PostMessage(string authToken, MessageToPost msg, string operationId = null)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (msg == null) throw new ArgumentNullException("msg");
return diadocHttpApi.PostMessage(authToken, msg, operationId);
}
public Template PostTemplate(string authToken, TemplateToPost template, string operationId = null)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (template == null) throw new ArgumentNullException("template");
return diadocHttpApi.PostTemplate(authToken, template, operationId);
}
public Message TransformTemplateToMessage(string authToken, TemplateTransformationToPost templateTransformation, string operationId = null)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (templateTransformation == null) throw new ArgumentNullException("templateTransformation");
return diadocHttpApi.TransformTemplateToMessage(authToken, templateTransformation, operationId);
}
public MessagePatch PostMessagePatch(string authToken, MessagePatchToPost patch, string operationId = null)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (patch == null) throw new ArgumentNullException("patch");
return diadocHttpApi.PostMessagePatch(authToken, patch, operationId);
}
public MessagePatch PostTemplatePatch(string authToken, string boxId, string templateId, TemplatePatchToPost patch, string operationId = null)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (templateId == null) throw new ArgumentNullException("templateId");
if (patch == null) throw new ArgumentNullException("patch");
return diadocHttpApi.PostTemplatePatch(authToken, boxId, templateId, patch, operationId);
}
public void PostRoamingNotification(string authToken, RoamingNotificationToPost notification)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (notification == null) throw new ArgumentNullException("notification");
diadocHttpApi.PostRoamingNotification(authToken, notification);
}
public void Delete(string authToken, string boxId, string messageId, string documentId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
diadocHttpApi.Delete(authToken, boxId, messageId, documentId);
}
public void Restore(string authToken, string boxId, string messageId, string documentId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
diadocHttpApi.Restore(authToken, boxId, messageId, documentId);
}
public void MoveDocuments(string authToken, DocumentsMoveOperation query)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (query == null) throw new ArgumentNullException("query");
diadocHttpApi.MoveDocuments(authToken, query);
}
public byte[] GetEntityContent(string authToken, string boxId, string messageId, string entityId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
if (entityId == null) throw new ArgumentNullException("entityId");
return diadocHttpApi.GetEntityContent(authToken, boxId, messageId, entityId);
}
[Obsolete("Use GenerateReceiptXml()")]
public GeneratedFile GenerateDocumentReceiptXml(string authToken, string boxId, string messageId, string attachmentId, Signer signer)
{
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
if (attachmentId == null) throw new ArgumentNullException("attachmentId");
if (signer == null) throw new ArgumentNullException("signer");
return diadocHttpApi.GenerateReceiptXml(authToken, boxId, messageId, attachmentId, signer);
}
[Obsolete("Use GenerateReceiptXml()")]
public GeneratedFile GenerateInvoiceDocumentReceiptXml(string authToken, string boxId, string messageId, string attachmentId, Signer signer)
{
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
if (attachmentId == null) throw new ArgumentNullException("attachmentId");
if (signer == null) throw new ArgumentNullException("signer");
return diadocHttpApi.GenerateReceiptXml(authToken, boxId, messageId, attachmentId, signer);
}
public GeneratedFile GenerateReceiptXml(string authToken, string boxId, string messageId, string attachmentId, Signer signer)
{
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
if (attachmentId == null) throw new ArgumentNullException("attachmentId");
if (signer == null) throw new ArgumentNullException("signer");
return diadocHttpApi.GenerateReceiptXml(authToken, boxId, messageId, attachmentId, signer);
}
public GeneratedFile GenerateInvoiceCorrectionRequestXml(string authToken,
string boxId,
string messageId,
string attachmentId,
InvoiceCorrectionRequestInfo correctionInfo)
{
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
if (attachmentId == null) throw new ArgumentNullException("attachmentId");
return diadocHttpApi.GenerateInvoiceCorrectionRequestXml(authToken, boxId, messageId, attachmentId, correctionInfo);
}
public GeneratedFile GenerateRevocationRequestXml(string authToken,
string boxId,
string messageId,
string attachmentId,
RevocationRequestInfo revocationRequestInfo,
string contentTypeId = null)
{
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
if (attachmentId == null) throw new ArgumentNullException("attachmentId");
return diadocHttpApi.GenerateRevocationRequestXml(authToken, boxId, messageId, attachmentId, revocationRequestInfo, contentTypeId);
}
public GeneratedFile GenerateSignatureRejectionXml(string authToken,
string boxId,
string messageId,
string attachmentId,
SignatureRejectionInfo signatureRejectionInfo)
{
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
if (attachmentId == null) throw new ArgumentNullException("attachmentId");
return diadocHttpApi.GenerateSignatureRejectionXml(authToken, boxId, messageId, attachmentId, signatureRejectionInfo);
}
public InvoiceCorrectionRequestInfo GetInvoiceCorrectionRequestInfo(string authToken,
string boxId,
string messageId,
string entityId)
{
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
if (entityId == null) throw new ArgumentNullException("entityId");
return diadocHttpApi.GetInvoiceCorrectionRequestInfo(authToken, boxId, messageId, entityId);
}
public GeneratedFile GenerateInvoiceXml(string authToken, InvoiceInfo invoiceInfo, bool disableValidation = false)
{
if (invoiceInfo == null) throw new ArgumentNullException("invoiceInfo");
return diadocHttpApi.GenerateInvoiceXml(authToken, invoiceInfo, disableValidation);
}
public GeneratedFile GenerateInvoiceRevisionXml(string authToken,
InvoiceInfo invoiceRevisionInfo,
bool disableValidation = false)
{
if (invoiceRevisionInfo == null) throw new ArgumentNullException("invoiceRevisionInfo");
return diadocHttpApi.GenerateInvoiceRevisionXml(authToken, invoiceRevisionInfo, disableValidation);
}
public GeneratedFile GenerateInvoiceCorrectionXml(string authToken,
InvoiceCorrectionInfo invoiceCorrectionInfo,
bool disableValidation = false)
{
if (invoiceCorrectionInfo == null) throw new ArgumentNullException("invoiceCorrectionInfo");
return diadocHttpApi.GenerateInvoiceCorrectionXml(authToken, invoiceCorrectionInfo, disableValidation);
}
public GeneratedFile GenerateInvoiceCorrectionRevisionXml(string authToken,
InvoiceCorrectionInfo invoiceCorrectionRevision,
bool disableValidation = false)
{
if (invoiceCorrectionRevision == null) throw new ArgumentNullException("invoiceCorrectionRevision");
return diadocHttpApi.GenerateInvoiceCorrectionRevisionXml(authToken, invoiceCorrectionRevision, disableValidation);
}
public GeneratedFile GenerateTorg12XmlForSeller(string authToken, Torg12SellerTitleInfo sellerInfo, bool disableValidation = false)
{
if (sellerInfo == null) throw new ArgumentNullException("sellerInfo");
return diadocHttpApi.GenerateTorg12XmlForSeller(authToken, sellerInfo, disableValidation);
}
public GeneratedFile GenerateTovTorg551XmlForSeller(string authToken, TovTorgSellerTitleInfo sellerInfo, bool disableValidation = false)
{
if (sellerInfo == null) throw new ArgumentNullException("sellerInfo");
return diadocHttpApi.GenerateTovTorg551XmlForSeller(authToken, sellerInfo, disableValidation);
}
public GeneratedFile GenerateTorg12XmlForBuyer(string authToken, Torg12BuyerTitleInfo buyerInfo, string boxId, string sellerTitleMessageId, string sellerTitleAttachmentId)
{
if (buyerInfo == null) throw new ArgumentNullException("buyerInfo");
return diadocHttpApi.GenerateTorg12XmlForBuyer(authToken, buyerInfo, boxId, sellerTitleMessageId, sellerTitleAttachmentId);
}
public GeneratedFile GenerateTovTorg551XmlForBuyer(string authToken, TovTorgBuyerTitleInfo buyerInfo, string boxId, string sellerTitleMessageId, string sellerTitleAttachmentId, string documentVersion = null)
{
if (buyerInfo == null) throw new ArgumentNullException("buyerInfo");
return diadocHttpApi.GenerateTovTorg551XmlForBuyer(authToken, buyerInfo, boxId, sellerTitleMessageId, sellerTitleAttachmentId, documentVersion);
}
public GeneratedFile GenerateAcceptanceCertificateXmlForSeller(string authToken,
AcceptanceCertificateSellerTitleInfo sellerInfo,
bool disableValidation = false)
{
if (sellerInfo == null) throw new ArgumentNullException("sellerInfo");
return diadocHttpApi.GenerateAcceptanceCertificateXmlForSeller(authToken, sellerInfo, disableValidation);
}
public GeneratedFile GenerateAcceptanceCertificateXmlForBuyer(string authToken,
AcceptanceCertificateBuyerTitleInfo buyerInfo,
string boxId,
string sellerTitleMessageId,
string sellerTitleAttachmentId)
{
if (buyerInfo == null) throw new ArgumentNullException("buyerInfo");
return diadocHttpApi.GenerateAcceptanceCertificateXmlForBuyer(authToken, buyerInfo, boxId, sellerTitleMessageId,
sellerTitleAttachmentId);
}
public GeneratedFile GenerateAcceptanceCertificate552XmlForSeller(string authToken,
AcceptanceCertificate552SellerTitleInfo sellerInfo,
bool disableValidation = false)
{
if (sellerInfo == null) throw new ArgumentNullException("sellerInfo");
return diadocHttpApi.GenerateAcceptanceCertificate552XmlForSeller(authToken, sellerInfo, disableValidation);
}
public GeneratedFile GenerateAcceptanceCertificate552XmlForBuyer(string authToken,
AcceptanceCertificate552BuyerTitleInfo buyerInfo,
string boxId,
string sellerTitleMessageId,
string sellerTitleAttachmentId)
{
if (buyerInfo == null) throw new ArgumentNullException("buyerInfo");
return diadocHttpApi.GenerateAcceptanceCertificate552XmlForBuyer(authToken, buyerInfo, boxId, sellerTitleMessageId,
sellerTitleAttachmentId);
}
public GeneratedFile GenerateUniversalTransferDocumentXmlForSeller(
string authToken,
UniversalTransferDocumentSellerTitleInfo sellerInfo,
bool disableValidation = false,
string documentVersion = null)
{
if (sellerInfo == null) throw new ArgumentNullException("sellerInfo");
return diadocHttpApi.GenerateUniversalTransferDocumentXmlForSeller(authToken, sellerInfo, disableValidation, documentVersion);
}
public GeneratedFile GenerateUniversalCorrectionDocumentXmlForSeller(
string authToken,
UniversalCorrectionDocumentSellerTitleInfo sellerInfo,
bool disableValidation = false,
string documentVersion = null)
{
if (sellerInfo == null) throw new ArgumentNullException("sellerInfo");
return diadocHttpApi.GenerateUniversalCorrectionDocumentXmlForSeller(authToken, sellerInfo, disableValidation, documentVersion);
}
public GeneratedFile GenerateUniversalTransferDocumentXmlForBuyer(string authToken,
UniversalTransferDocumentBuyerTitleInfo buyerInfo,
string boxId,
string sellerTitleMessageId,
string sellerTitleAttachmentId)
{
if (buyerInfo == null) throw new ArgumentNullException("buyerInfo");
return diadocHttpApi.GenerateUniversalTransferDocumentXmlForBuyer(authToken, buyerInfo, boxId, sellerTitleMessageId, sellerTitleAttachmentId);
}
public GeneratedFile GenerateTitleXml(
string authToken,
string boxId,
string documentTypeNamedId,
string documentFunction,
string documentVersion,
int titleIndex,
byte[] userContractData,
bool disableValidation = false,
string editingSettingId = null,
string letterId = null,
string documentId = null)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (documentTypeNamedId == null) throw new ArgumentNullException("documentTypeNamedId");
if (documentFunction == null) throw new ArgumentNullException("documentFunction");
if (documentVersion == null) throw new ArgumentNullException("documentVersion");
if (userContractData == null) throw new ArgumentNullException("userContractData");
return diadocHttpApi.GenerateTitleXml(
authToken,
boxId,
documentTypeNamedId,
documentFunction,
documentVersion,
titleIndex,
userContractData,
disableValidation,
editingSettingId,
letterId,
documentId);
}
public GeneratedFile GenerateSenderTitleXml(string authToken, string boxId, string documentTypeNamedId, string documentFunction, string documentVersion, byte[] userContractData, bool disableValidation = false, string editingSettingId = null)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (documentTypeNamedId == null) throw new ArgumentNullException("documentTypeNamedId");
if (documentFunction == null) throw new ArgumentNullException("documentFunction");
if (documentVersion == null) throw new ArgumentNullException("documentVersion");
if (userContractData == null) throw new ArgumentNullException("userContractData");
return diadocHttpApi.GenerateSenderTitleXml(authToken, boxId, documentTypeNamedId, documentFunction, documentVersion, userContractData, disableValidation, editingSettingId);
}
public GeneratedFile GenerateRecipientTitleXml(string authToken, string boxId, string senderTitleMessageId, string senderTitleAttachmentId, byte[] userContractData, string documentVersion = null)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (senderTitleMessageId == null) throw new ArgumentNullException("senderTitleMessageId");
if (senderTitleAttachmentId == null) throw new ArgumentNullException("senderTitleAttachmentId");
if (userContractData == null) throw new ArgumentNullException("userContractData");
return diadocHttpApi.GenerateRecipientTitleXml(authToken, boxId, senderTitleMessageId, senderTitleAttachmentId, userContractData, documentVersion);
}
public Message GetMessage(string authToken, string boxId, string messageId, bool withOriginalSignature = false, bool injectEntityContent = false)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
return diadocHttpApi.GetMessage(authToken, boxId, messageId, withOriginalSignature, injectEntityContent);
}
public Message GetMessage(string authToken, string boxId, string messageId, string entityId, bool withOriginalSignature = false, bool injectEntityContent = false)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
if (entityId == null) throw new ArgumentNullException("entityId");
return diadocHttpApi.GetMessage(authToken, boxId, messageId, entityId, withOriginalSignature, injectEntityContent);
}
public Template GetTemplate(string authToken, string boxId, string templateId, string entityId = null)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (templateId == null) throw new ArgumentNullException("templateId");
return diadocHttpApi.GetTemplate(authToken, boxId, templateId, entityId);
}
public void RecycleDraft(string authToken, string boxId, string draftId)
{
diadocHttpApi.RecycleDraft(authToken, boxId, draftId);
}
public Message SendDraft(string authToken, DraftToSend draftToSend, string operationId = null)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (draftToSend == null) throw new ArgumentNullException("draftToSend");
return diadocHttpApi.SendDraft(authToken, draftToSend, operationId);
}
public PrintFormResult GeneratePrintForm(string authToken, string boxId, string messageId, string documentId)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
if (string.IsNullOrEmpty(messageId)) throw new ArgumentNullException("messageId");
if (string.IsNullOrEmpty(documentId)) throw new ArgumentNullException("documentId");
return diadocHttpApi.GeneratePrintForm(authToken, boxId, messageId, documentId);
}
public string GeneratePrintFormFromAttachment(string authToken,
DocumentType documentType,
byte[] content,
string fromBoxId = null)
{
return diadocHttpApi.GeneratePrintFormFromAttachment(authToken, documentType, content, fromBoxId);
}
[Obsolete("Use GetGeneratedPrintForm without `documentType` parameter")]
public PrintFormResult GetGeneratedPrintForm(string authToken, DocumentType documentType, string printFormId)
{
if (string.IsNullOrEmpty(printFormId)) throw new ArgumentNullException("printFormId");
return diadocHttpApi.GetGeneratedPrintForm(authToken, documentType, printFormId);
}
public PrintFormResult GetGeneratedPrintForm(string authToken, string printFormId)
{
if (string.IsNullOrEmpty(printFormId)) throw new ArgumentNullException("printFormId");
return diadocHttpApi.GetGeneratedPrintForm(authToken, printFormId);
}
public string Recognize(string fileName, byte[] content)
{
if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName");
return diadocHttpApi.Recognize(fileName, content);
}
public Recognized GetRecognized(string recognitionId)
{
if (string.IsNullOrEmpty(recognitionId)) throw new ArgumentNullException("recognitionId");
return diadocHttpApi.GetRecognized(recognitionId);
}
public DocumentList GetDocuments(string authToken,
string boxId,
string filterCategory,
string counteragentBoxId,
DateTime? timestampFrom,
DateTime? timestampTo,
string fromDocumentDate,
string toDocumentDate,
string departmentId,
bool excludeSubdepartments,
string afterIndexKey,
int? count = null)
{
return diadocHttpApi.GetDocuments(authToken, boxId, filterCategory, counteragentBoxId, timestampFrom, timestampTo,
fromDocumentDate, toDocumentDate, departmentId, excludeSubdepartments, afterIndexKey, count);
}
public DocumentList GetDocuments(string authToken, DocumentsFilter filter)
{
return diadocHttpApi.GetDocuments(authToken, filter);
}
public Document GetDocument(string authToken, string boxId, string messageId, string entityId)
{
return diadocHttpApi.GetDocument(authToken, boxId, messageId, entityId);
}
public SignatureInfo GetSignatureInfo(string authToken, string boxId, string messageId, string entityId)
{
return diadocHttpApi.GetSignatureInfo(authToken, boxId, messageId, entityId);
}
public ExtendedSignerDetails GetExtendedSignerDetails(string token, string boxId, string thumbprint, DocumentTitleType documentTitleType)
{
return diadocHttpApi.GetExtendedSignerDetails(token, boxId, thumbprint, documentTitleType);
}
public ExtendedSignerDetails GetExtendedSignerDetails(string token, string boxId, byte[] certificateBytes, DocumentTitleType documentTitleType)
{
return diadocHttpApi.GetExtendedSignerDetails(token, boxId, certificateBytes, documentTitleType);
}
public ExtendedSignerDetails PostExtendedSignerDetails(string token, string boxId, string thumbprint, DocumentTitleType documentTitleType, ExtendedSignerDetailsToPost signerDetails)
{
return diadocHttpApi.PostExtendedSignerDetails(token, boxId, thumbprint, documentTitleType, signerDetails);
}
public ExtendedSignerDetails PostExtendedSignerDetails(string token, string boxId, byte[] certificateBytes, DocumentTitleType documentTitleType, ExtendedSignerDetailsToPost signerDetails)
{
return diadocHttpApi.PostExtendedSignerDetails(token, boxId, certificateBytes, documentTitleType, signerDetails);
}
public GetDocflowBatchResponse GetDocflows(string authToken, string boxId, GetDocflowBatchRequest request)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetDocflows(authToken, boxId, request);
}
public GetDocflowEventsResponse GetDocflowEvents(string authToken, string boxId, GetDocflowEventsRequest request)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetDocflowEvents(authToken, boxId, request);
}
public SearchDocflowsResponse SearchDocflows(string authToken, string boxId, SearchDocflowsRequest request)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
return diadocHttpApi.SearchDocflows(authToken, boxId, request);
}
public GetDocflowsByPacketIdResponse GetDocflowsByPacketId(string authToken,
string boxId,
GetDocflowsByPacketIdRequest request)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetDocflowsByPacketId(authToken, boxId, request);
}
public ForwardDocumentResponse ForwardDocument(string authToken, string boxId, ForwardDocumentRequest request)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
return diadocHttpApi.ForwardDocument(authToken, boxId, request);
}
public GetForwardedDocumentsResponse GetForwardedDocuments(string authToken,
string boxId,
GetForwardedDocumentsRequest request)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetForwardedDocuments(authToken, boxId, request);
}
public GetForwardedDocumentEventsResponse GetForwardedDocumentEvents(string authToken,
string boxId,
GetForwardedDocumentEventsRequest request)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetForwardedDocumentEvents(authToken, boxId, request);
}
public byte[] GetForwardedEntityContent(string authToken,
string boxId,
ForwardedDocumentId forwardedDocumentId,
string entityId)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetForwardedEntityContent(authToken, boxId, forwardedDocumentId, entityId);
}
public DocumentProtocolResult GenerateForwardedDocumentProtocol(string authToken,
string boxId,
ForwardedDocumentId forwardedDocumentId)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
return diadocHttpApi.GenerateForwardedDocumentProtocol(authToken, boxId, forwardedDocumentId);
}
public PrintFormResult GenerateForwardedDocumentPrintForm(string authToken, string boxId, ForwardedDocumentId forwardedDocumentId)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
return diadocHttpApi.GenerateForwardedDocumentPrintForm(authToken, boxId, forwardedDocumentId);
}
public bool CanSendInvoice(string authToken, string boxId, byte[] certificateBytes)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
if (certificateBytes == null || certificateBytes.Length == 0) throw new ArgumentNullException("certificateBytes");
return diadocHttpApi.CanSendInvoice(authToken, boxId, certificateBytes);
}
public void SendFnsRegistrationMessage(string authToken,
string boxId,
FnsRegistrationMessageInfo fnsRegistrationMessageInfo)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
if (!fnsRegistrationMessageInfo.Certificates.Any()) throw new ArgumentException("fnsRegistrationMessageInfo");
diadocHttpApi.SendFnsRegistrationMessage(authToken, boxId, fnsRegistrationMessageInfo);
}
public Counteragent GetCounteragent(string authToken, string myOrgId, string counteragentOrgId)
{
if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(myOrgId)) throw new ArgumentNullException("myOrgId");
if (string.IsNullOrEmpty(counteragentOrgId)) throw new ArgumentNullException("counteragentOrgId");
return diadocHttpApi.GetCounteragent(authToken, myOrgId, counteragentOrgId);
}
public CounteragentList GetCounteragents(string authToken, string myOrgId, string counteragentStatus, string afterIndexKey, string query = null, int? pageSize = null)
{
if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(myOrgId)) throw new ArgumentNullException("myOrgId");
return diadocHttpApi.GetCounteragents(authToken, myOrgId, counteragentStatus, afterIndexKey, query, pageSize);
}
public CounteragentCertificateList GetCounteragentCertificates(string authToken,
string myOrgId,
string counteragentOrgId)
{
if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(myOrgId)) throw new ArgumentNullException("myOrgId");
if (string.IsNullOrEmpty(counteragentOrgId)) throw new ArgumentNullException("counteragentOrgId");
return diadocHttpApi.GetCounteragentCertificates(authToken, myOrgId, counteragentOrgId);
}
public void BreakWithCounteragent(string authToken, string myOrgId, string counteragentOrgId, string comment)
{
if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(myOrgId)) throw new ArgumentNullException("myOrgId");
if (string.IsNullOrEmpty(counteragentOrgId)) throw new ArgumentNullException("counteragentOrgId");
diadocHttpApi.BreakWithCounteragent(authToken, myOrgId, counteragentOrgId, comment);
}
public string UploadFileToShelf(string authToken, byte[] data)
{
if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException("authToken");
if (data == null) throw new ArgumentNullException("data");
return diadocHttpApi.UploadFileToShelf(authToken, data);
}
public byte[] GetFileFromShelf(string authToken, string nameOnShelf)
{
if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(nameOnShelf)) throw new ArgumentNullException("nameOnShelf");
return diadocHttpApi.GetFileFromShelf(authToken, nameOnShelf);
}
public RussianAddress ParseRussianAddress(string address)
{
return diadocHttpApi.ParseRussianAddress(address);
}
public InvoiceInfo ParseInvoiceXml(byte[] invoiceXmlContent)
{
return diadocHttpApi.ParseInvoiceXml(invoiceXmlContent);
}
public Torg12SellerTitleInfo ParseTorg12SellerTitleXml(byte[] xmlContent)
{
return diadocHttpApi.ParseTorg12SellerTitleXml(xmlContent);
}
public Torg12BuyerTitleInfo ParseTorg12BuyerTitleXml(byte[] xmlContent)
{
return diadocHttpApi.ParseTorg12BuyerTitleXml(xmlContent);
}
public TovTorgSellerTitleInfo ParseTovTorg551SellerTitleXml(byte[] xmlContent)
{
return diadocHttpApi.ParseTovTorg551SellerTitleXml(xmlContent);
}
public TovTorgBuyerTitleInfo ParseTovTorg551BuyerTitleXml(byte[] xmlContent)
{
return diadocHttpApi.ParseTovTorg551BuyerTitleXml(xmlContent);
}
public AcceptanceCertificateSellerTitleInfo ParseAcceptanceCertificateSellerTitleXml(byte[] xmlContent)
{
return diadocHttpApi.ParseAcceptanceCertificateSellerTitleXml(xmlContent);
}
public AcceptanceCertificateBuyerTitleInfo ParseAcceptanceCertificateBuyerTitleXml(byte[] xmlContent)
{
return diadocHttpApi.ParseAcceptanceCertificateBuyerTitleXml(xmlContent);
}
public AcceptanceCertificate552SellerTitleInfo ParseAcceptanceCertificate552SellerTitleXml(byte[] xmlContent)
{
return diadocHttpApi.ParseAcceptanceCertificate552SellerTitleXml(xmlContent);
}
public AcceptanceCertificate552BuyerTitleInfo ParseAcceptanceCertificate552BuyerTitleXml(byte[] xmlContent)
{
return diadocHttpApi.ParseAcceptanceCertificate552BuyerTitleXml(xmlContent);
}
public UniversalTransferDocumentSellerTitleInfo ParseUniversalTransferDocumentSellerTitleXml(byte[] xmlContent, string documentVersion = DefaultDocumentVersions.Utd)
{
return diadocHttpApi.ParseUniversalTransferDocumentSellerTitleXml(xmlContent, documentVersion);
}
public UniversalTransferDocumentBuyerTitleInfo ParseUniversalTransferDocumentBuyerTitleXml(byte[] xmlContent)
{
return diadocHttpApi.ParseUniversalTransferDocumentBuyerTitleXml(xmlContent);
}
public UniversalCorrectionDocumentSellerTitleInfo ParseUniversalCorrectionDocumentSellerTitleXml(byte[] xmlContent, string documentVersion = DefaultDocumentVersions.Ucd)
{
return diadocHttpApi.ParseUniversalCorrectionDocumentSellerTitleXml(xmlContent, documentVersion);
}
public UniversalTransferDocumentBuyerTitleInfo ParseUniversalCorrectionDocumentBuyerTitleXml(byte[] xmlContent)
{
return diadocHttpApi.ParseUniversalCorrectionDocumentBuyerTitleXml(xmlContent);
}
public byte[] ParseTitleXml(
string authToken,
string boxId,
string documentTypeNamedId,
string documentFunction,
string documentVersion,
int titleIndex,
byte[] content)
{
if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException(nameof(authToken));
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException(nameof(boxId));
if (string.IsNullOrEmpty(documentTypeNamedId)) throw new ArgumentNullException(nameof(documentTypeNamedId));
if (string.IsNullOrEmpty(documentFunction)) throw new ArgumentNullException(nameof(documentFunction));
if (string.IsNullOrEmpty(documentVersion)) throw new ArgumentNullException(nameof(documentVersion));
if (content == null) throw new ArgumentNullException(nameof(content));
return diadocHttpApi.ParseTitleXml(
authToken,
boxId,
documentTypeNamedId,
documentFunction,
documentVersion,
titleIndex,
content);
}
public OrganizationUsersList GetOrganizationUsers(string authToken, string orgId)
{
if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(orgId)) throw new ArgumentNullException("orgId");
return diadocHttpApi.GetOrganizationUsers(authToken, orgId);
}
public List<Organization> GetOrganizationsByInnList(GetOrganizationsByInnListRequest innList)
{
if (innList == null)
throw new ArgumentNullException("innList");
return diadocHttpApi.GetOrganizationsByInnList(innList);
}
public List<OrganizationWithCounteragentStatus> GetOrganizationsByInnList(string authToken,
string myOrgId,
GetOrganizationsByInnListRequest innList)
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(myOrgId))
throw new ArgumentNullException("myOrgId");
if (innList == null)
throw new ArgumentNullException("innList");
return diadocHttpApi.GetOrganizationsByInnList(authToken, myOrgId, innList);
}
public RevocationRequestInfo ParseRevocationRequestXml(byte[] revocationRequestXmlContent)
{
return diadocHttpApi.ParseRevocationRequestXml(revocationRequestXmlContent);
}
public SignatureRejectionInfo ParseSignatureRejectionXml(byte[] signatureRejectionXmlContent)
{
return diadocHttpApi.ParseSignatureRejectionXml(signatureRejectionXmlContent);
}
public DocumentProtocolResult GenerateDocumentProtocol(string authToken,
string boxId,
string messageId,
string documentId)
{
return diadocHttpApi.GenerateDocumentProtocol(authToken, boxId, messageId, documentId);
}
public DocumentZipGenerationResult GenerateDocumentZip(string authToken,
string boxId,
string messageId,
string documentId,
bool fullDocflow)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
if (documentId == null) throw new ArgumentNullException("documentId");
return diadocHttpApi.GenerateDocumentZip(authToken, boxId, messageId, documentId, fullDocflow);
}
public DocumentList GetDocumentsByCustomId(string authToken, string boxId, string customDocumentId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (customDocumentId == null) throw new ArgumentNullException("customDocumentId");
return diadocHttpApi.GetDocumentsByCustomId(authToken, boxId, customDocumentId);
}
public PrepareDocumentsToSignResponse PrepareDocumentsToSign(string authToken,
PrepareDocumentsToSignRequest request,
bool excludeContent = false)
{
if (authToken == null) throw new ArgumentNullException("authToken");
return diadocHttpApi.PrepareDocumentsToSign(authToken, request, excludeContent);
}
public AsyncMethodResult CloudSign(string authToken, CloudSignRequest request, string certificateThumbprint)
{
if (request == null) throw new ArgumentNullException("request");
return diadocHttpApi.CloudSign(authToken, request, certificateThumbprint);
}
public CloudSignResult WaitCloudSignResult(string authToken, string taskId, TimeSpan? timeout = null)
{
if (string.IsNullOrEmpty(taskId)) throw new ArgumentNullException("taskId");
return diadocHttpApi.WaitCloudSignResult(authToken, taskId, timeout);
}
public AsyncMethodResult CloudSignConfirm(string authToken,
string cloudSignToken,
string confirmationCode,
ContentLocationPreference? locationPreference = null)
{
if (string.IsNullOrEmpty(cloudSignToken)) throw new ArgumentNullException("cloudSignToken");
if (string.IsNullOrEmpty(confirmationCode)) throw new ArgumentNullException("confirmationCode");
return diadocHttpApi.CloudSignConfirm(authToken, cloudSignToken, confirmationCode, locationPreference);
}
public CloudSignConfirmResult WaitCloudSignConfirmResult(string authToken, string taskId, TimeSpan? timeout = null)
{
if (string.IsNullOrEmpty(taskId)) throw new ArgumentNullException("taskId");
return diadocHttpApi.WaitCloudSignConfirmResult(authToken, taskId, timeout);
}
public AsyncMethodResult DssSign(string authToken, string boxId, DssSignRequest request, string certificateThumbprint = null)
{
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
if (request == null) throw new ArgumentNullException("request");
return diadocHttpApi.DssSign(authToken, boxId, request, certificateThumbprint);
}
public DssSignResult DssSignResult(string authToken, string boxId, string taskId)
{
if (string.IsNullOrEmpty(taskId)) throw new ArgumentNullException("taskId");
if (string.IsNullOrEmpty(boxId)) throw new ArgumentNullException("boxId");
return diadocHttpApi.DssSignResult(authToken, boxId, taskId);
}
public AsyncMethodResult AcquireCounteragent(string authToken,
string myOrgId,
AcquireCounteragentRequest request,
string myDepartmentId = null)
{
if (request == null) throw new ArgumentNullException("request");
return diadocHttpApi.AcquireCounteragent(authToken, myOrgId, request, myDepartmentId);
}
public AcquireCounteragentResult WaitAcquireCounteragentResult(string authToken, string taskId, TimeSpan? timeout = null, TimeSpan? delay = null)
{
if (string.IsNullOrEmpty(taskId)) throw new ArgumentNullException("taskId");
return diadocHttpApi.WaitAcquireCounteragentResult(authToken, taskId, timeout, delay);
}
public DocumentList GetDocumentsByMessageId(string authToken, string boxId, string messageId)
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
if (string.IsNullOrEmpty(messageId))
throw new ArgumentNullException("messageId");
return diadocHttpApi.GetDocumentsByMessageId(authToken, boxId, messageId);
}
public List<KeyValueStorageEntry> GetOrganizationStorageEntries(
string authToken,
string boxId,
IEnumerable<string> keys)
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
if (keys == null)
throw new ArgumentNullException("keys");
return diadocHttpApi.GetOrganizationStorageEntries(authToken, boxId, keys);
}
public void PutOrganizationStorageEntries(
string authToken,
string boxId,
IEnumerable<KeyValueStorageEntry> entries)
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
if (entries == null)
throw new ArgumentNullException("entries");
diadocHttpApi.PutOrganizationStorageEntries(authToken, boxId, entries);
}
public AsyncMethodResult AutoSignReceipts(string authToken, string boxId, string certificateThumbprint, string batchKey)
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
return diadocHttpApi.AutoSignReceipts(authToken, boxId, certificateThumbprint, batchKey);
}
public AutosignReceiptsResult WaitAutosignReceiptsResult(string authToken, string taskId, TimeSpan? timeout = null)
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(taskId))
throw new ArgumentNullException("taskId");
return diadocHttpApi.WaitAutosignReceiptsResult(authToken, taskId, timeout);
}
public ExternalServiceAuthInfo GetExternalServiceAuthInfo(string key)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
return diadocHttpApi.GetExternalServiceAuthInfo(key);
}
public ExtendedSignerDetails GetExtendedSignerDetails(string token, string boxId, string thumbprint, bool forBuyer, bool forCorrection)
{
if (string.IsNullOrEmpty(token))
throw new ArgumentNullException("token");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
if (string.IsNullOrEmpty(thumbprint))
throw new ArgumentNullException("thumbprint");
return diadocHttpApi.GetExtendedSignerDetails(token, boxId, thumbprint, forBuyer, forCorrection);
}
public ExtendedSignerDetails GetExtendedSignerDetails(string token, string boxId, byte[] certificateBytes, bool forBuyer, bool forCorrection)
{
if (string.IsNullOrEmpty(token))
throw new ArgumentNullException("token");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
if (certificateBytes == null)
throw new ArgumentNullException("certificateBytes");
return diadocHttpApi.GetExtendedSignerDetails(token, boxId, certificateBytes, forBuyer, forCorrection);
}
public ExtendedSignerDetails PostExtendedSignerDetails(string token, string boxId, byte[] certificateBytes, bool forBuyer, bool forCorrection, ExtendedSignerDetailsToPost signerDetails)
{
if (string.IsNullOrEmpty(token))
throw new ArgumentNullException("token");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
if (certificateBytes == null)
throw new ArgumentNullException("certificateBytes");
if (signerDetails == null)
throw new ArgumentNullException("signerDetails");
return diadocHttpApi.PostExtendedSignerDetails(token, boxId, certificateBytes, forBuyer, forCorrection, signerDetails);
}
public ExtendedSignerDetails PostExtendedSignerDetails(string token, string boxId, string thumbprint, bool forBuyer, bool forCorrection, ExtendedSignerDetailsToPost signerDetails)
{
if (string.IsNullOrEmpty(token))
throw new ArgumentNullException("token");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
if (string.IsNullOrEmpty(thumbprint))
throw new ArgumentNullException("thumbprint");
if (signerDetails == null)
throw new ArgumentNullException("signerDetails");
return diadocHttpApi.PostExtendedSignerDetails(token, boxId, thumbprint, forBuyer, forCorrection, signerDetails);
}
public ResolutionRouteList GetResolutionRoutesForOrganization(string authToken, string orgId)
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(orgId))
throw new ArgumentNullException("orgId");
return diadocHttpApi.GetResolutionRoutesForOrganization(authToken, orgId);
}
public GetDocumentTypesResponseV2 GetDocumentTypesV2(string authToken, string boxId)
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
return diadocHttpApi.GetDocumentTypesV2(authToken, boxId);
}
[Obsolete("Use DetectDocumentTitles")]
public DetectDocumentTypesResponse DetectDocumentTypes(string authToken, string boxId, string nameOnShelf)
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
if (string.IsNullOrEmpty(nameOnShelf))
throw new ArgumentNullException("nameOnShelf");
return diadocHttpApi.DetectDocumentTypes(authToken, boxId, nameOnShelf);
}
[Obsolete("Use DetectDocumentTitles")]
public DetectDocumentTypesResponse DetectDocumentTypes(string authToken, string boxId, byte[] content)
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
return diadocHttpApi.DetectDocumentTypes(authToken, boxId, content);
}
public DetectTitleResponse DetectDocumentTitles(string authToken, string boxId, string nameOnShelf)
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
if (string.IsNullOrEmpty(nameOnShelf))
throw new ArgumentNullException("nameOnShelf");
return diadocHttpApi.DetectDocumentTitles(authToken, boxId, nameOnShelf);
}
public DetectTitleResponse DetectDocumentTitles(string authToken, string boxId, byte[] content)
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(boxId))
throw new ArgumentNullException("boxId");
return diadocHttpApi.DetectDocumentTitles(authToken, boxId, content);
}
public FileContent GetContent(string authToken, string typeNamedId, string function, string version, int titleIndex, XsdContentType contentType = default(XsdContentType))
{
if (string.IsNullOrEmpty(authToken))
throw new ArgumentNullException("authToken");
if (string.IsNullOrEmpty(typeNamedId))
throw new ArgumentNullException("typeNamedId");
if (string.IsNullOrEmpty(function))
throw new ArgumentNullException("function");
if (string.IsNullOrEmpty(version))
throw new ArgumentNullException("version");
if (titleIndex < 0)
throw new ArgumentOutOfRangeException("titleIndex", titleIndex, "Title index should be non-negative");
return diadocHttpApi.GetContent(authToken, typeNamedId, function, version, titleIndex, contentType);
}
public Employee GetEmployee(string authToken, string boxId, string userId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (userId == null) throw new ArgumentNullException("userId");
return diadocHttpApi.GetEmployee(authToken, boxId, userId);
}
public EmployeeList GetEmployees(string authToken, string boxId, int? page, int? count)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (page < 1)
throw new ArgumentOutOfRangeException("page", page, "page must be 1 or greater");
if (count < 1)
throw new ArgumentOutOfRangeException("count", count, "count must be 1 or greater");
return diadocHttpApi.GetEmployees(authToken, boxId, page, count);
}
public Employee CreateEmployee(string authToken, string boxId, EmployeeToCreate employeeToCreate)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (employeeToCreate == null) throw new ArgumentNullException("employeeToCreate");
return diadocHttpApi.CreateEmployee(authToken, boxId, employeeToCreate);
}
public Employee UpdateEmployee(string authToken, string boxId, string userId, EmployeeToUpdate employeeToUpdate)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (userId == null) throw new ArgumentNullException("userId");
if (employeeToUpdate == null) throw new ArgumentNullException("employeeToUpdate");
return diadocHttpApi.UpdateEmployee(authToken, boxId, userId, employeeToUpdate);
}
public void DeleteEmployee(string authToken, string boxId, string userId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (userId == null) throw new ArgumentNullException("userId");
diadocHttpApi.DeleteEmployee(authToken, boxId, userId);
}
public Employee GetMyEmployee(string authToken, string boxId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetMyEmployee(authToken, boxId);
}
public EmployeeSubscriptions GetSubscriptions(string authToken, string boxId, string userId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (userId == null) throw new ArgumentNullException("userId");
return diadocHttpApi.GetSubscriptions(authToken, boxId, userId);
}
public EmployeeSubscriptions UpdateSubscriptions(string authToken, string boxId, string userId, SubscriptionsToUpdate subscriptionsToUpdate)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (userId == null) throw new ArgumentNullException("userId");
return diadocHttpApi.UpdateSubscriptions(authToken, boxId, userId, subscriptionsToUpdate);
}
public EmployeePowerOfAttorneyList GetEmployeePowersOfAttorney(string authToken, string boxId, [CanBeNull] string userId = null, bool onlyActual = false)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetEmployeePowersOfAttorney(authToken, boxId, userId, onlyActual);
}
public EmployeePowerOfAttorney UpdateEmployeePowerOfAttorney(
string authToken,
string boxId,
[CanBeNull] string userId,
string registrationNumber,
string issuerInn,
EmployeePowerOfAttorneyToUpdate powerOfAttorneyToUpdate)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (registrationNumber == null) throw new ArgumentNullException("registrationNumber");
if (issuerInn == null) throw new ArgumentNullException("issuerInn");
if (powerOfAttorneyToUpdate == null) throw new ArgumentNullException("powerOfAttorneyToUpdate");
return diadocHttpApi.UpdateEmployeePowerOfAttorney(authToken, boxId, userId, registrationNumber, issuerInn, powerOfAttorneyToUpdate);
}
public EmployeePowerOfAttorney AddEmployeePowerOfAttorney(string authToken, string boxId, [CanBeNull] string userId, string registrationNumber, string issuerInn)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (registrationNumber == null) throw new ArgumentNullException("registrationNumber");
if (issuerInn == null) throw new ArgumentNullException("issuerInn");
return diadocHttpApi.AddEmployeePowerOfAttorney(authToken, boxId, userId, registrationNumber, issuerInn);
}
public void DeleteEmployeePowerOfAttorney(string authToken, string boxId, [CanBeNull] string userId, string registrationNumber, string issuerInn)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (registrationNumber == null) throw new ArgumentNullException("registrationNumber");
if (issuerInn == null) throw new ArgumentNullException("issuerInn");
diadocHttpApi.DeleteEmployeePowerOfAttorney(authToken, boxId, userId, registrationNumber, issuerInn);
}
public Departments.Department GetDepartmentByFullId(string authToken, string boxId, string departmentId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (departmentId == null) throw new ArgumentNullException("departmentId");
return diadocHttpApi.GetDepartmentByFullId(authToken, boxId, departmentId);
}
public Departments.DepartmentList GetDepartments(string authToken, string boxId, int? page = null, int? count = null)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetDepartments(authToken, boxId, page, count);
}
public Departments.Department CreateDepartment(string authToken, string boxId, Departments.DepartmentToCreate departmentToCreate)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
return diadocHttpApi.CreateDepartment(authToken, boxId, departmentToCreate);
}
public Departments.Department UpdateDepartment(string authToken, string boxId, string departmentId, Departments.DepartmentToUpdate departmentToUpdate)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (departmentId == null) throw new ArgumentNullException("departmentId");
return diadocHttpApi.UpdateDepartment(authToken, boxId, departmentId, departmentToUpdate);
}
public void DeleteDepartment(string authToken, string boxId, string departmentId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (departmentId == null) throw new ArgumentNullException("departmentId");
diadocHttpApi.DeleteDepartment(authToken, boxId, departmentId);
}
public RegistrationResponse Register(string authToken, RegistrationRequest registrationRequest)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (registrationRequest == null) throw new ArgumentNullException("registrationRequest");
return diadocHttpApi.Register(authToken, registrationRequest);
}
public void RegisterConfirm(string authToken, RegistrationConfirmRequest registrationConfirmRequest)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (registrationConfirmRequest == null) throw new ArgumentNullException("registrationConfirmRequest");
diadocHttpApi.RegisterConfirm(authToken, registrationConfirmRequest);
}
public CustomPrintFormDetectionResult DetectCustomPrintForms(
string authToken,
string boxId,
CustomPrintFormDetectionRequest request)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (request == null) throw new ArgumentNullException("request");
return diadocHttpApi.DetectCustomPrintForms(authToken, boxId, request);
}
public BoxEvent GetLastEvent(string authToken, string boxId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
return diadocHttpApi.GetLastEvent(authToken, boxId);
}
public AsyncMethodResult RegisterPowerOfAttorney(string authToken, string boxId, PowerOfAttorneyToRegister powerOfAttorneyToRegister)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (powerOfAttorneyToRegister == null) throw new ArgumentNullException("powerOfAttorneyToRegister");
return diadocHttpApi.RegisterPowerOfAttorney(authToken, boxId, powerOfAttorneyToRegister);
}
public PowerOfAttorneyRegisterResult RegisterPowerOfAttorneyResult(string authToken, string boxId, string taskId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (taskId == null) throw new ArgumentNullException("taskId");
return diadocHttpApi.RegisterPowerOfAttorneyResult(authToken, boxId, taskId);
}
public PowerOfAttorneyPrevalidateResult PrevalidatePowerOfAttorney(
string authToken,
string boxId,
string registrationNumber,
string issuerInn,
PowerOfAttorneyPrevalidateRequest request)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (registrationNumber == null) throw new ArgumentNullException("registrationNumber");
if (issuerInn == null) throw new ArgumentNullException("issuerInn");
if (request == null) throw new ArgumentNullException("request");
return diadocHttpApi.PrevalidatePowerOfAttorney(authToken, boxId, registrationNumber, issuerInn, request);
}
public PowerOfAttorney GetPowerOfAttorneyInfo(string authToken, string boxId, string messageId, string entityId)
{
if (authToken == null) throw new ArgumentNullException("authToken");
if (boxId == null) throw new ArgumentNullException("boxId");
if (messageId == null) throw new ArgumentNullException("messageId");
if (entityId == null) throw new ArgumentNullException("entityId");
return diadocHttpApi.GetPowerOfAttorneyInfo(authToken, boxId, messageId, entityId);
}
}
}
| 44.015333 | 243 | 0.783151 | [
"MIT"
] | DonMorozov/diadocsdk-csharp | src/DiadocApi.cs | 66,025 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Runtime.Serialization;
namespace Nest
{
public class XPackInfoResponse : ResponseBase
{
[DataMember(Name ="build")]
public XPackBuildInformation Build { get; internal set; }
[DataMember(Name ="features")]
public XPackFeatures Features { get; internal set; }
[DataMember(Name ="license")]
public MinimalLicenseInformation License { get; internal set; }
[DataMember(Name ="tagline")]
public string Tagline { get; internal set; }
}
public class XPackBuildInformation
{
[DataMember(Name ="date")]
public DateTimeOffset Date { get; internal set; }
[DataMember(Name ="hash")]
public string Hash { get; internal set; }
}
public class MinimalLicenseInformation
{
[DataMember(Name ="expiry_date_in_millis")]
public long ExpiryDateInMilliseconds { get; set; }
[DataMember(Name ="mode")]
public LicenseType Mode { get; internal set; }
[DataMember(Name ="status")]
public LicenseStatus Status { get; internal set; }
[DataMember(Name ="type")]
public LicenseType Type { get; internal set; }
[DataMember(Name ="uid")]
public string UID { get; internal set; }
}
public class XPackFeatures
{
[DataMember(Name = "analytics")]
public XPackFeature Analytics { get; internal set; }
[DataMember(Name = "ccr")]
public XPackFeature Ccr { get; internal set; }
[DataMember(Name = "enrich")]
public XPackFeature Enrich { get; internal set; }
[Obsolete("Changed to Transform in 7.5.0")]
[DataMember(Name = "data_frame")]
public XPackFeature DataFrame { get; internal set; }
[DataMember(Name = "flattened")]
public XPackFeature Flattened { get; internal set; }
[DataMember(Name = "frozen_indices")]
public XPackFeature FrozenIndices { get; internal set; }
[DataMember(Name = "data_science")]
public XPackFeature DataScience { get; internal set; }
[DataMember(Name = "graph")]
public XPackFeature Graph { get; internal set; }
// TODO! Expand to fullname in 8.0?
[DataMember(Name = "ilm")]
public XPackFeature Ilm { get; internal set; }
[DataMember(Name = "logstash")]
public XPackFeature Logstash { get; internal set; }
[DataMember(Name = "ml")]
public XPackFeature MachineLearning { get; internal set; }
[DataMember(Name = "monitoring")]
public XPackFeature Monitoring { get; internal set; }
[DataMember(Name = "rollup")]
public XPackFeature Rollup { get; internal set; }
[DataMember(Name = "security")]
public XPackFeature Security { get; internal set; }
[DataMember(Name = "slm")]
public XPackFeature SnapshotLifecycleManagement { get; internal set; }
[DataMember(Name = "spatial")]
public XPackFeature Spatial { get; internal set; }
[DataMember(Name = "sql")]
public XPackFeature Sql { get; internal set; }
[DataMember(Name = "transform")]
public XPackFeature Transform { get; internal set; }
[DataMember(Name = "vectors")]
public XPackFeature Vectors { get; internal set; }
[DataMember(Name = "voting_only")]
public XPackFeature VotingOnly { get; internal set; }
[DataMember(Name = "watcher")]
public XPackFeature Watcher { get; internal set; }
}
public class XPackFeature
{
[DataMember(Name = "available")]
public bool Available { get; internal set; }
[DataMember(Name ="description")]
public string Description { get; internal set; }
[DataMember(Name ="enabled")]
public bool Enabled { get; internal set; }
[DataMember(Name ="native_code_info")]
public NativeCodeInformation NativeCodeInformation { get; internal set; }
}
public class NativeCodeInformation
{
[DataMember(Name ="build_hash")]
public string BuildHash { get; internal set; }
[DataMember(Name ="version")]
public string Version { get; internal set; }
}
}
| 27.93617 | 76 | 0.705509 | [
"Apache-2.0"
] | Brightspace/elasticsearch-net | src/Nest/XPack/Info/XPackInfo/XPackInfoResponse.cs | 3,941 | C# |
/*******************************************************************************
* Copyright 2012-2019 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.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.QuickSight;
using Amazon.QuickSight.Model;
namespace Amazon.PowerShell.Cmdlets.QS
{
/// <summary>
/// Removes a user from a group so that the user is no longer a member of the group.
/// </summary>
[Cmdlet("Remove", "QSGroupMembership", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)]
[OutputType("Amazon.QuickSight.Model.DeleteGroupMembershipResponse")]
[AWSCmdlet("Calls the Amazon QuickSight DeleteGroupMembership API operation.", Operation = new[] {"DeleteGroupMembership"}, SelectReturnType = typeof(Amazon.QuickSight.Model.DeleteGroupMembershipResponse))]
[AWSCmdletOutput("Amazon.QuickSight.Model.DeleteGroupMembershipResponse",
"This cmdlet returns an Amazon.QuickSight.Model.DeleteGroupMembershipResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class RemoveQSGroupMembershipCmdlet : AmazonQuickSightClientCmdlet, IExecutor
{
#region Parameter AwsAccountId
/// <summary>
/// <para>
/// <para>The ID for the Amazon Web Services account that the group is in. Currently, you use
/// the ID for the Amazon Web Services account that contains your Amazon QuickSight account.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String AwsAccountId { get; set; }
#endregion
#region Parameter GroupName
/// <summary>
/// <para>
/// <para>The name of the group that you want to delete the user from.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String GroupName { get; set; }
#endregion
#region Parameter MemberName
/// <summary>
/// <para>
/// <para>The name of the user that you want to delete from the group membership.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String MemberName { get; set; }
#endregion
#region Parameter Namespace
/// <summary>
/// <para>
/// <para>The namespace. Currently, you should set this to <code>default</code>.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String Namespace { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is '*'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.QuickSight.Model.DeleteGroupMembershipResponse).
/// Specifying the name of a property of type Amazon.QuickSight.Model.DeleteGroupMembershipResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the MemberName parameter.
/// The -PassThru parameter is deprecated, use -Select '^MemberName' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^MemberName' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.MemberName), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Remove-QSGroupMembership (DeleteGroupMembership)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.QuickSight.Model.DeleteGroupMembershipResponse, RemoveQSGroupMembershipCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.MemberName;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.AwsAccountId = this.AwsAccountId;
#if MODULAR
if (this.AwsAccountId == null && ParameterWasBound(nameof(this.AwsAccountId)))
{
WriteWarning("You are passing $null as a value for parameter AwsAccountId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.GroupName = this.GroupName;
#if MODULAR
if (this.GroupName == null && ParameterWasBound(nameof(this.GroupName)))
{
WriteWarning("You are passing $null as a value for parameter GroupName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.MemberName = this.MemberName;
#if MODULAR
if (this.MemberName == null && ParameterWasBound(nameof(this.MemberName)))
{
WriteWarning("You are passing $null as a value for parameter MemberName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.Namespace = this.Namespace;
#if MODULAR
if (this.Namespace == null && ParameterWasBound(nameof(this.Namespace)))
{
WriteWarning("You are passing $null as a value for parameter Namespace which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.QuickSight.Model.DeleteGroupMembershipRequest();
if (cmdletContext.AwsAccountId != null)
{
request.AwsAccountId = cmdletContext.AwsAccountId;
}
if (cmdletContext.GroupName != null)
{
request.GroupName = cmdletContext.GroupName;
}
if (cmdletContext.MemberName != null)
{
request.MemberName = cmdletContext.MemberName;
}
if (cmdletContext.Namespace != null)
{
request.Namespace = cmdletContext.Namespace;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.QuickSight.Model.DeleteGroupMembershipResponse CallAWSServiceOperation(IAmazonQuickSight client, Amazon.QuickSight.Model.DeleteGroupMembershipRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon QuickSight", "DeleteGroupMembership");
try
{
#if DESKTOP
return client.DeleteGroupMembership(request);
#elif CORECLR
return client.DeleteGroupMembershipAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String AwsAccountId { get; set; }
public System.String GroupName { get; set; }
public System.String MemberName { get; set; }
public System.String Namespace { get; set; }
public System.Func<Amazon.QuickSight.Model.DeleteGroupMembershipResponse, RemoveQSGroupMembershipCmdlet, object> Select { get; set; } =
(response, cmdlet) => response;
}
}
}
| 46.633663 | 283 | 0.619321 | [
"Apache-2.0"
] | aws/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/QuickSight/Basic/Remove-QSGroupMembership-Cmdlet.cs | 14,130 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.Azure.IIoT.Modules.OpcUa.Twin {
/// <summary>
/// Twin Module information
/// </summary>
public static class ServiceInfo {
/// <summary>
/// Name of service
/// </summary>
public const string NAME = "OpcTwin";
/// <summary>
/// Number used for routing requests
/// </summary>
public const string NUMBER = "2";
/// <summary>
/// Full path used in the URL
/// </summary>
public const string PATH = "v" + NUMBER;
/// <summary>
/// Date when the API version has been published
/// </summary>
public const string DATE = "201904";
/// <summary>
/// Description of service
/// </summary>
public const string DESCRIPTION = "Opc Twin IoT Edge Module";
}
}
| 29.358974 | 99 | 0.499563 | [
"MIT"
] | TheWaywardHayward/Industrial-IoT | modules/opc-twin/src/v2/ServiceInfo.cs | 1,145 | C# |
using StoreModels;
using System.Collections.Generic;
namespace StoreBL
{
public interface ICustomerOrderLineItemBL
{
List<CustomerOrderLineItem> GetCustomerOrderLineItems();
void AddCustomerOrderLineItem(CustomerOrderLineItem newCustomerOrderLineItem);
CustomerOrderLineItem GetCustomerOrderLineItemById(int id);
CustomerOrderLineItem GetCustomerOrderLineItemById(int orderId, int prodId);
void DeleteCustomerOrderLineItem(CustomerOrderLineItem customerOrderLineItem2BDeleted);
void UpdateCustomerOrderLineItem(CustomerOrderLineItem customerOrderLineItem2BUpdated, CustomerOrderLineItem updatedDetails);
int Ident_Curr();
}
} | 43.375 | 133 | 0.802594 | [
"MIT"
] | rjhakes/Richard_Hakes-P0 | StoreApp/StoreBL/ICustomerOrderLineItemBL.cs | 694 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace TesseractSharp.Hocr
{
public struct WConf
{
public WConf(float confidence)
{
Confidence = confidence;
}
public float Confidence { get; }
}
public struct Baseline
{
public Baseline(float slope, float constant)
{
Slope = slope;
Constant = constant;
}
public float Slope { get; }
public float Constant { get; }
}
public struct BBox
{
public BBox(int x0, int y0, int x1, int y1)
{
X0 = x0;
Y0 = y0;
X1 = x1;
Y1 = y1;
}
public int X0 { get; }
public int Y0 { get; }
public int X1 { get; }
public int Y1 { get; }
public int Width => X1 - X0;
public int Height => Y1 - Y0;
}
public abstract class HTitle
{
protected HTitle(string value)
{
Title = value;
var rawFields = new Dictionary<string, string>();
var fields = value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var field in fields)
{
var subfields = field.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (subfields.Length == 0)
throw new HOCRException($"Invalid title format {value}");
rawFields[subfields[0]] = string.Join(" ", subfields.Where(((s, i) => i > 0)));
if (subfields[0].Equals("bbox") || subfields[0].Equals("x_bboxes"))
{
if (subfields.Length != 5)
throw new HOCRException($"Invalid title format {value}");
BBox = new BBox(
x0: int.Parse(subfields[1]),
y0: int.Parse(subfields[2]),
x1: int.Parse(subfields[3]),
y1: int.Parse(subfields[4]));
}
else if (subfields[0].Equals("baseline"))
{
if (subfields.Length != 3)
throw new HOCRException($"Invalid title format {value}");
Baseline = new Baseline(
slope: float.Parse(subfields[1], CultureInfo.InvariantCulture.NumberFormat),
constant: float.Parse(subfields[2], CultureInfo.InvariantCulture.NumberFormat));
}
else if (subfields[0].Equals("x_wconf"))
{
if (subfields.Length != 2)
throw new HOCRException($"Invalid title format {value}");
WConf = new WConf(confidence: float.Parse(subfields[1], CultureInfo.InvariantCulture.NumberFormat));
}
}
Fields = rawFields;
}
public string Title { get; }
public IReadOnlyDictionary<string, string> Fields { get; }
public BBox BBox { get; }
public Baseline Baseline { get; }
public WConf WConf { get; }
}
public abstract class HObject : HTitle
{
public string Id { get; }
protected HObject(string id, string title) : base(title)
{
Id = id;
}
}
public class HCInfo : HTitle
{
public HCInfo(string title, string value) : base(title)
{
Value = value;
}
public string Value { get; }
}
public class HWord : HObject
{
public HWord(string id, string title, string lang, string dir, string value, IEnumerable<HCInfo> hCInfos = null) : base(id, title)
{
Lang = lang;
Dir = dir;
CInfos = hCInfos?.ToArray() ?? new HCInfo[0];
Value = hCInfos == null ? value : string.Join("", CInfos.Select(i => i.Value));
}
public string Lang { get; }
public string Dir { get; }
public string Value { get; }
public HCInfo[] CInfos { get; }
}
public class HLine : HObject
{
public HLine(string id, string title, IEnumerable<HWord> words) : base(id, title)
{
Words = words.ToArray();
}
public string ConcatenatedWords => string.Join(" ", Words.Select(w => w.Value));
public HWord[] Words { get; }
}
public class HPar : HObject
{
public HPar(string id, string title, string lang, string dir, IEnumerable<HLine> lines) : base(id, title)
{
Lang = lang;
Dir = dir;
Lines = lines.ToArray();
}
public string Lang { get; }
public string Dir { get; }
public HLine[] Lines { get; }
}
public class HCarea : HObject
{
public HCarea(string id, string title, IEnumerable<HPar> paragraphs) : base(id, title)
{
Paragraphs = paragraphs.ToArray();
}
public HPar[] Paragraphs { get; }
}
public class HPage : HObject
{
public HPage(string id, string title, IEnumerable<HCarea> areas) : base(id, title)
{
Areas = areas.ToArray();
}
public HCarea[] Areas { get; }
}
public class HDocument
{
public HDocument(IEnumerable<HPage> pages)
{
Pages = pages.ToArray();
}
public HPage[] Pages { get; }
}
}
| 27.809045 | 138 | 0.503614 | [
"Apache-2.0"
] | Beniyoo/TesseractSharp | src/Hocr/HObject.cs | 5,536 | C# |
using System;
namespace FP.Spartakiade2015.WebservicePersistence.TestConsole
{
class Program
{
static void Main(string[] args)
{
try
{
using (BookCapacityService client = new BookCapacityService { Url = "http://localhost:49874/EnergyService.asmx" })
{
var request = new BookCapacityRequestType
{
Customer = "Frank Pommerening",
MessageIdentifier = Guid.NewGuid().ToString("D"),
Quantity = 5000,
Unit = CapacityUnit.KWh,
ValidFrom = DateTime.Now.AddDays(1),
ValidTo = DateTime.Now.AddMonths(1).AddDays(1)
};
Console.WriteLine("Starte Kapazitätsanfrage");
var result = client.BookCapacity(request);
Console.WriteLine("{0}: {1} {2}", result.MessageIdentifier, result.Quantity, result.Unit);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
Console.ReadLine();
}
}
}
| 33.837838 | 130 | 0.472843 | [
"MIT"
] | forki/Spartakiade2015 | WebservicePersistence/TestConsole/Program.cs | 1,255 | C# |
using Chip8.Chip8;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Chip8
{
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
private Texture2D _pixelTexture;
private CPU _cpu { get; set; }
private int PixelSize { get; set; }
public Game1()
{
Window.AllowUserResizing = true;
_graphics = new GraphicsDeviceManager(this);
_cpu = new CPU(new Chip8.Keyboard(), new Speaker());
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
/// <summary>
/// This method is called after the constructor, but before the main game loop(Update/Draw).
/// This is where you can query any required services and load any non-graphic related content.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
IsMouseVisible = false;
_graphics.PreferredBackBufferWidth = CPU.DisplayWidth;
_graphics.PreferredBackBufferHeight = CPU.DisplayHeight;
_graphics.ApplyChanges();
base.Initialize();
}
/// <summary>
/// This method is used to load your game content.
/// It is called only once per game, after Initialize method,
/// but before the main game loop methods.
/// </summary>
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
_cpu.LoadSpritesIntoMemory();
_cpu.LoadROM(@"C:\Users\rodri\source\repos\Chip8\Chip8\roms\Space Invaders [David Winter].ch8");
_pixelTexture = Content.Load<Texture2D>("pixel");
_cpu.LoadSoundEffect(Content.Load<SoundEffect>("sound"));
}
/// <summary>
/// This method is called multiple times per second,
/// and is used to update your game state
/// (checking for collisions, gathering input, playing audio, etc.).
/// </summary>
/// <param name="gameTime"></param>
protected override void Update(GameTime gameTime)
{
var keyboardState = Microsoft.Xna.Framework.Input.Keyboard.GetState();
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed
|| keyboardState.IsKeyDown(Keys.Escape))
Exit();
// Toggle fulscreen
if ((keyboardState.IsKeyDown(Keys.LeftAlt) || keyboardState.IsKeyDown(Keys.RightAlt)) && keyboardState.IsKeyDown(Keys.Enter))
_graphics.ToggleFullScreen();
// Volume controls
if (keyboardState.IsKeyDown(Keys.N))
_cpu.RaiseSoundEffectVolume();
else if (keyboardState.IsKeyDown(Keys.M))
_cpu.LowerSoundEffectVolume();
// Refer to the DisplayWidth formula
PixelSize = _graphics.GraphicsDevice.Viewport.Width / (CPU.DisplayWidth / 8);
_cpu.Cycle();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
_spriteBatch.Begin();
for (int i = 0; i < CPU.DisplayWidth; i++)
{
for (int j = 0; j < CPU.DisplayHeight; j++)
{
if (_cpu.Display[i, j])
_spriteBatch.Draw(
_pixelTexture,
new Rectangle(
i * PixelSize,
j * PixelSize,
PixelSize,
PixelSize),
Color.White);
}
}
_spriteBatch.End();
base.Draw(gameTime);
}
}
}
| 32.464567 | 137 | 0.55348 | [
"MIT"
] | RodrigoFNascimento/MonoChip8 | Chip8/Game1.cs | 4,125 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Scintilla;
using Scintilla.Forms;
using Scintilla.Configuration;
using Scintilla.Configuration.SciTE;
using WeifenLuo.WinFormsUI.Docking;
namespace MyGeneration
{
public interface IMyGenerationMDI
{
FindForm FindDialog { get; }
ReplaceForm ReplaceDialog { get; }
ScintillaConfigureDelegate ConfigureDelegate { get; }
DockPanel DockPanel { get; }
}
} | 24.578947 | 61 | 0.738758 | [
"BSD-3-Clause"
] | cafephin/mygeneration | src/mygeneration/MyGeneration/IMyGenerationMDI.cs | 467 | C# |
namespace _03.ConvertDecimalToHex
{
using System;
using System.Text;
class Program
{
// Write a program to convert decimal numbers to their hexadecimal representation.
static char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
static void Main(string[] args)
{
int decimalNumber = -256;
string hexNumber = DecimalToHex(decimalNumber);
Console.WriteLine(hexNumber);
decimalNumber = 255;
hexNumber = DecimalToHex(decimalNumber);
Console.WriteLine(hexNumber);
}
private static string DecimalToHex(int decimalNumber)
{
bool isNegative = decimalNumber < 0 ? true : false;
if (isNegative)
{
decimalNumber = -decimalNumber; //get the positive value
//get the length of the bits in decimalNumber without left zeroes
int length = Convert.ToString(decimalNumber, 2).Length;
//we have to split the binary code by 4 bits
int addition = 0;
if (length % 4 != 0)
{
//get the difference between length and 4 if it doesn't devide exactly
addition = 4 - length % 4;
}
int lengthBits = length + addition;
//invert the bits till lengthbits with the XOR operator
int mask = 1;
for (int i = 0; i < lengthBits; i++)
{
mask = 1 << i;
decimalNumber = decimalNumber ^ mask;
}
//we add + 1
decimalNumber += 1;
}
StringBuilder sb = new StringBuilder();
while (decimalNumber != 0)
{
//match the remaining with the coresponding element in the hex array
sb.Append(hexArray[decimalNumber % 16]);
decimalNumber /= 16;
}
string hex = sb.ToString();
int lengthHex = hex.Length;
sb.Clear();
//reverse the array in the right way
for (int i = lengthHex - 1; i >= 0; i--)
{
sb.Append(hex[i]);
}
if (isNegative)
{
hex = sb.ToString();
sb.Clear();
//fill the left spaces with F
sb.Append(hex.PadLeft(8, 'F'));
}
return sb.ToString();
}
}
}
| 31.045977 | 117 | 0.453165 | [
"MIT"
] | bstaykov/Telerik-CSharp-Part-2 | Numeral-Systems/03.ConvertDecimalToHex/Program.cs | 2,703 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.Interaction.Toolkit;
public class ARInteractionManager : MonoBehaviour
{
[SerializeField] XRInteractionManager interactionManager;
[SerializeField] Toggle toggle;
private void OnEnable()
{
toggle.onValueChanged.AddListener(delegate {
ToggleValueChanged(toggle);
});
}
private void OnDisable()
{
toggle.onValueChanged.RemoveAllListeners();
}
void ToggleValueChanged(Toggle change)
{
interactionManager.enabled = change.isOn;
}
}
| 19.333333 | 61 | 0.708333 | [
"MIT"
] | 3diab/oscp-unity-client | Assets/NGI/Scripts/InDevelopment/ARInteractionManager.cs | 696 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the alexaforbusiness-2017-11-09.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AlexaForBusiness.Model
{
/// <summary>
/// Container for the parameters to the RevokeInvitation operation.
/// Revokes an invitation and invalidates the enrollment URL.
/// </summary>
public partial class RevokeInvitationRequest : AmazonAlexaForBusinessRequest
{
private string _enrollmentId;
private string _userArn;
/// <summary>
/// Gets and sets the property EnrollmentId.
/// <para>
/// The ARN of the enrollment invitation to revoke. Required.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=128)]
public string EnrollmentId
{
get { return this._enrollmentId; }
set { this._enrollmentId = value; }
}
// Check to see if EnrollmentId property is set
internal bool IsSetEnrollmentId()
{
return this._enrollmentId != null;
}
/// <summary>
/// Gets and sets the property UserArn.
/// <para>
/// The ARN of the user for whom to revoke an enrollment invitation. Required.
/// </para>
/// </summary>
public string UserArn
{
get { return this._userArn; }
set { this._userArn = value; }
}
// Check to see if UserArn property is set
internal bool IsSetUserArn()
{
return this._userArn != null;
}
}
} | 30.324675 | 114 | 0.629979 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/AlexaForBusiness/Generated/Model/RevokeInvitationRequest.cs | 2,335 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace WpfUtilV2.Mvvm.CustomControls
{
public class ListBoxEx : ListBox
{
public ListBoxEx() : base()
{
SelectionChanged += lb_SelectionChanged;
}
/// <summary>
/// 選択行変更時イベント
/// </summary>
private void lb_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (var item in e.RemovedItems.Cast<ISelectableItem>())
item.IsSelected = false;
foreach (var item in e.AddedItems.Cast<ISelectableItem>())
item.IsSelected = true;
}
/// <summary>
/// ItemsSource項目数変更時イベント
/// </summary>
private void lvw_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (Items.Count == 0) return;
ScrollIntoView(Items[0]);
}
protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
if (!object.Equals(oldValue, newValue) && newValue != null)
{
(newValue as INotifyCollectionChanged).CollectionChanged +=
new NotifyCollectionChangedEventHandler(lvw_CollectionChanged);
}
base.OnItemsSourceChanged(oldValue, newValue);
}
}
}
| 29.423077 | 96 | 0.614379 | [
"MIT"
] | twinbird827/WpfUtilV2 | Mvvm/CustomControls/ListBoxEx.cs | 1,576 | 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.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Xunit;
// ReSharper disable AssignNullToNotNullAttribute
namespace Microsoft.EntityFrameworkCore.Query
{
public class ExpressionEqualityComparerTest
{
[Fact]
public void Member_init_expressions_are_compared_correctly()
{
var expressionComparer = new ExpressionEqualityComparer();
var addMethod = typeof(List<string>).GetTypeInfo().GetDeclaredMethod("Add");
var bindingMessages = Expression.ListBind(
typeof(Node).GetProperty("Messages"),
Expression.ElementInit(addMethod, Expression.Constant("Constant1"))
);
var bindingDescriptions = Expression.ListBind(
typeof(Node).GetProperty("Descriptions"),
Expression.ElementInit(addMethod, Expression.Constant("Constant2"))
);
Expression e1 = Expression.MemberInit(
Expression.New(typeof(Node)),
new List<MemberBinding>
{
bindingMessages
}
);
Expression e2 = Expression.MemberInit(
Expression.New(typeof(Node)),
new List<MemberBinding>
{
bindingMessages,
bindingDescriptions
}
);
Assert.NotEqual(expressionComparer.GetHashCode(e1), expressionComparer.GetHashCode(e2));
Assert.False(expressionComparer.Equals(e1, e2));
Assert.Equal(expressionComparer.GetHashCode(e1), expressionComparer.GetHashCode(e1));
Assert.True(expressionComparer.Equals(e1, e1));
}
private class Node
{
[UsedImplicitly]
public List<string> Messages { set; get; }
[UsedImplicitly]
public List<string> Descriptions { set; get; }
}
}
}
| 33.41791 | 111 | 0.610094 | [
"Apache-2.0"
] | EasonDongH/EntityFrameworkCore | test/EFCore.Tests/Query/ExpressionEqualityComparerTest.cs | 2,241 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Engine.Editing;
using Engine.Saving;
namespace Anomaly
{
public class ExternalResource : EditableProperty, Saveable
{
public ExternalResource(String path)
{
this.Path = path;
}
public String Path { get; set; }
#region EditableProperty Members
public string getValue(int column)
{
return Path;
}
public Object getRealValue(int column)
{
return Path;
}
public void setValue(int column, Object value)
{
Path = (String)value;
}
public void setValueStr(int column, string value)
{
Path = value;
}
public bool canParseString(int column, string value, out string errorMessage)
{
errorMessage = "";
return true;
}
public Type getPropertyType(int column)
{
return typeof(String);
}
public bool hasBrowser(int column)
{
return false;
}
public Browser getBrowser(int column, EditUICallback uiCallback)
{
return null;
}
public bool readOnly(int column)
{
return false;
}
/// <summary>
/// Set this to true to indicate to the ui that this property is advanced.
/// </summary>
public bool Advanced
{
get
{
return false;
}
}
#endregion
#region Saveable Members
private const String PATH = "Path";
protected ExternalResource(LoadInfo info)
{
Path = info.GetString(PATH);
}
public void getInfo(SaveInfo info)
{
info.AddValue(PATH, Path);
}
#endregion
}
}
| 21.134021 | 86 | 0.492195 | [
"MIT"
] | AnomalousMedical/Engine | Anomaly/Controller/ProjectManagement/ExternalResource.cs | 2,052 | C# |
/**
* The MIT License
* Copyright (c) 2016 Population Register Centre (VRK)
*
* 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.
*/
namespace PTV.Domain.Model.Models
{
/// <summary>
/// View model of results from fulltext search of general descritpion
/// </summary>
public class VmGeneralDescriptionSearchListItem : VmGeneralDescriptionListItem
{
}
}
| 43.8125 | 82 | 0.750357 | [
"MIT"
] | MikkoVirenius/ptv-1.7 | src/PTV.Domain.Model/Models/VmGeneralDescriptionSearchListItem.cs | 1,404 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Metastore.V1Beta.Snippets
{
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Metastore.V1Beta;
using Google.LongRunning;
using System.Threading.Tasks;
public sealed partial class GeneratedDataprocMetastoreClientStandaloneSnippets
{
/// <summary>Snippet for CreateServiceAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task CreateServiceRequestObjectAsync()
{
// Create client
DataprocMetastoreClient dataprocMetastoreClient = await DataprocMetastoreClient.CreateAsync();
// Initialize request argument(s)
CreateServiceRequest request = new CreateServiceRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ServiceId = "",
Service = new Service(),
RequestId = "",
};
// Make the request
Operation<Service, OperationMetadata> response = await dataprocMetastoreClient.CreateServiceAsync(request);
// Poll until the returned long-running operation is complete
Operation<Service, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Service result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Service, OperationMetadata> retrievedResponse = await dataprocMetastoreClient.PollOnceCreateServiceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Service retrievedResult = retrievedResponse.Result;
}
}
}
}
| 43.828125 | 142 | 0.671658 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/metastore/v1beta/google-cloud-metastore-v1beta-csharp/Google.Cloud.Metastore.V1Beta.StandaloneSnippets/DataprocMetastoreClient.CreateServiceRequestObjectAsyncSnippet.g.cs | 2,805 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
// If you see intermittent failures on devices that are created by this file, check to see if you have multiple suites
// running at the same time because one test run could be accidentally destroying devices created by a different test run.
namespace Microsoft.Azure.Devices.E2ETests
{
public class TestUtil
{
public const string FaultType_Tcp = "KillTcp";
public const string FaultType_AmqpConn = "KillAmqpConnection";
public const string FaultType_AmqpSess = "KillAmqpSession";
public const string FaultType_AmqpCBSReq = "KillAmqpCBSLinkReq";
public const string FaultType_AmqpCBSResp = "KillAmqpCBSLinkResp";
public const string FaultType_AmqpD2C = "KillAmqpD2CLink";
public const string FaultType_AmqpC2D = "KillAmqpC2DLink";
public const string FaultType_AmqpTwinReq = "KillAmqpTwinLinkReq";
public const string FaultType_AmqpTwinResp = "KillAmqpTwinLinkResp";
public const string FaultType_AmqpMethodReq = "KillAmqpMethodReqLink";
public const string FaultType_AmqpMethodResp = "KillAmqpMethodRespLink";
public const string FaultType_Throttle = "InvokeThrottling";
public const string FaultType_QuotaExceeded = "InvokeMaxMessageQuota";
public const string FaultType_Auth = "InvokeAuthError";
public const string FaultType_ShutdownAmqp = "ShutDownAmqp";
public const string FaultType_ShutdownMqtt = "ShutDownMqtt";
public const string FaultCloseReason_Boom = "Boom";
public const string FaultCloseReason_Bye = "byebye";
public const int DefaultDelayInSec = 1;
public const int DefaultDurationInSec = 5;
public static string GetHostName(string connectionString)
{
Regex regex = new Regex("HostName=([^;]+)", RegexOptions.None);
return regex.Match(connectionString).Groups[1].Value;
}
public static string GetDeviceConnectionString(Device device, string hostName)
{
var connectionString = new StringBuilder();
connectionString.AppendFormat("HostName={0}", hostName);
connectionString.AppendFormat(";DeviceId={0}", device.Id);
connectionString.AppendFormat(";SharedAccessKey={0}", device.Authentication.SymmetricKey.PrimaryKey);
return connectionString.ToString();
}
public static Tuple<string, RegistryManager> InitializeEnvironment(string devicePrefix)
{
string iotHubConnectionString = Environment.GetEnvironmentVariable("IOTHUB_CONN_STRING_CSHARP");
RegistryManager rm = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
// Ensure to remove all previous devices.
foreach (Device device in rm.GetDevicesAsync(int.MaxValue).Result)
{
if (device.Id.StartsWith(devicePrefix))
{
RemoveDevice(device.Id, rm);
}
}
return new Tuple<string, RegistryManager>(iotHubConnectionString, rm);
}
public static void UnInitializeEnvironment(RegistryManager rm)
{
Task.Run(async () =>
{
await rm.CloseAsync();
}).Wait();
}
public static Tuple<string, string> CreateDevice(string devicePrefix, string hostName, RegistryManager registryManager)
{
string deviceName = null;
string deviceConnectionString = null;
Task.Run(async () =>
{
deviceName = devicePrefix + Guid.NewGuid();
Debug.WriteLine("Creating device " + deviceName);
var device = await registryManager.AddDeviceAsync(new Device(deviceName));
deviceConnectionString = TestUtil.GetDeviceConnectionString(device, hostName);
Debug.WriteLine("Device successfully created");
}).Wait();
Thread.Sleep(1000);
return new Tuple<string, string>(deviceName, deviceConnectionString);
}
public static void RemoveDevice(string deviceName, RegistryManager registryManager)
{
Task.Run(async () =>
{
Debug.WriteLine("Removing device " + deviceName);
await registryManager.RemoveDeviceAsync(deviceName);
Debug.WriteLine("Device successfully removed");
}).Wait();
}
public static Client.Message ComposeErrorInjectionProperties(string faultType, string reason, int delayInSecs, int durationInSecs = 0)
{
string dataBuffer = Guid.NewGuid().ToString();
return new Client.Message(Encoding.UTF8.GetBytes(dataBuffer))
{
Properties =
{
["AzIoTHub_FaultOperationType"] = faultType,
["AzIoTHub_FaultOperationCloseReason"] = reason,
["AzIoTHub_FaultOperationDelayInSecs"] = delayInSecs.ToString(),
["AzIoTHub_FaultOperationDurationInSecs"] = durationInSecs.ToString()
}
};
}
}
} | 43.539683 | 142 | 0.651294 | [
"MIT"
] | harunpehlivan/azure-iot-sdk-csharp | e2e/Microsoft.Azure.Devices.E2ETests/TestUtil.cs | 5,488 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
namespace BO.Base
{
public class BaseDao<T> : IBaseDao<T> where T : class
{
public BaseDao()
{
}
public bool Delete(T entity)
{
var success = false;
if (entity != null)
{
//ApplicationDbContextSingleton.ContextInstance.Entry(entity).State = EntityState.Deleted;
ApplicationDbContextSingleton.ContextInstance.Set<T>().Remove(entity);
}
return success;
}
public List<T> GetAll()
{
List<T> result = null;
result = ApplicationDbContextSingleton.ContextInstance.Set<T>().ToList();
return result;
}
public T GetByID(int id)
{
T result = null;
result = ApplicationDbContextSingleton.ContextInstance.Set<T>().Find(id);
return result;
}
public bool Insert(T entity)
{
var success = false;
if (entity != null)
{
ApplicationDbContextSingleton.ContextInstance.Set<T>().Add(entity);
success = true;
}
return success;
}
public bool Update(T entity)
{
var success = false;
if (entity != null)
{
//ApplicationDbContextSingleton.ContextInstance.Entry(entity).State = EntityState.Modified;
ApplicationDbContextSingleton.ContextInstance.Set<T>().AddOrUpdate(entity);
success = true;
}
return success;
}
public bool Commit()
{
var success = false;
try
{
ApplicationDbContextSingleton.ContextInstance.SaveChanges();
success = true;
}
catch (Exception e)
{
throw e;
}
return success;
}
}
}
| 24.045455 | 107 | 0.502836 | [
"MIT"
] | Alexandre-Delaunay/ENI_Projet_Sport | ENI_Projet_Sport/BO/Base/BaseDao.cs | 2,118 | C# |
using System;
using StartFinance.ViewModels;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using System.Collections.ObjectModel;
namespace StartFinance.Views
{
public sealed partial class MainPage : Page
{
public MainPage()
{
InitializeComponent();
NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
}
}
}
| 21.9 | 89 | 0.69863 | [
"MIT"
] | AasthaBabbar/Assignment5TSD | StartFinanceMaster/InstaRichie/Views/MainPage.xaml.cs | 438 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using Xunit;
namespace System.CodeDom.Compiler.Tests
{
public class CompilerResultsTests
{
public static IEnumerable<object[]> Ctor_TempFileCollection_TestData()
{
yield return new object[] { null };
yield return new object[] { new TempFileCollection() };
}
[Theory]
[MemberData(nameof(Ctor_TempFileCollection_TestData))]
public void Ctor_TempFileCollection(TempFileCollection tempFiles)
{
var results = new CompilerResults(tempFiles);
Assert.Null(results.CompiledAssembly);
Assert.Empty(results.Errors);
Assert.Equal(0, results.NativeCompilerReturnValue);
Assert.Null(results.PathToAssembly);
Assert.Empty(results.Output);
Assert.Same(tempFiles, results.TempFiles);
}
[Fact]
[ActiveIssue(30252, ~TargetFrameworkMonikers.NetFramework)]
public void CompiledAssembly_ValidPathToAssembly_ReturnsExpected()
{
var results = new CompilerResults(null) { PathToAssembly = typeof(int).Assembly.EscapedCodeBase };
Assert.Equal(typeof(int).Assembly, results.CompiledAssembly);
Assert.Same(results.CompiledAssembly, results.CompiledAssembly);
}
[Fact]
public void CompiledAssembly_Set_GetReturnsExpecte()
{
Assembly assembly = typeof(CompilerResultsTests).Assembly;
var results = new CompilerResults(null) { CompiledAssembly = assembly };
Assert.Same(assembly, results.CompiledAssembly);
}
}
}
| 37.54 | 110 | 0.666489 | [
"MIT"
] | L-Dogg/corefx | src/System.CodeDom/tests/System/CodeDom/Compiler/CompilerResultsTests.cs | 1,877 | C# |
namespace GamingInterfaceClient.Models
{
public enum CommandKey { DOWN, UP }
}
| 16.8 | 39 | 0.738095 | [
"Apache-2.0"
] | Tjalfi/GamingInterfaceClient | GamingInterfaceClient/GamingInterfaceClient/Models/CommandKey.cs | 86 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ratp.Hidalgo.Web.ViewModel
{
public class CriteresVm
{
public string LibelleCritere { get; set; }
public string ValeurMinCritere { get; set; }
public string ValeurMaxCritere { get; set; }
}
} | 21.666667 | 52 | 0.683077 | [
"MIT"
] | yarraf/MyWork | Src.Ratp.Lot03Dev/Ratp.Hidalgo.Web/ViewModel/CriteresVm.cs | 327 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Jag.VictimServices.Interfaces.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// competitorsalesliterature
/// </summary>
public partial class MicrosoftDynamicsCRMcompetitorsalesliterature
{
/// <summary>
/// Initializes a new instance of the
/// MicrosoftDynamicsCRMcompetitorsalesliterature class.
/// </summary>
public MicrosoftDynamicsCRMcompetitorsalesliterature()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// MicrosoftDynamicsCRMcompetitorsalesliterature class.
/// </summary>
public MicrosoftDynamicsCRMcompetitorsalesliterature(string competitorid = default(string), string salesliteratureid = default(string), long? versionnumber = default(long?), string competitorsalesliteratureid = default(string))
{
Competitorid = competitorid;
Salesliteratureid = salesliteratureid;
Versionnumber = versionnumber;
Competitorsalesliteratureid = competitorsalesliteratureid;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "competitorid")]
public string Competitorid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "salesliteratureid")]
public string Salesliteratureid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "versionnumber")]
public long? Versionnumber { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "competitorsalesliteratureid")]
public string Competitorsalesliteratureid { get; set; }
}
}
| 32.878788 | 235 | 0.630876 | [
"Apache-2.0"
] | JonTaylorBCGov2/pssg-cscp-cpu | cpu-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMcompetitorsalesliterature.cs | 2,170 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 the OpenSimulator Project 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 DEVELOPERS ``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 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 Nini.Config;
using log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Avatar
{
public class AvatarServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IAvatarService m_AvatarService;
public AvatarServerPostHandler(IAvatarService service) :
base("POST", "/avatar")
{
m_AvatarService = service;
}
public override byte[] Handle(string path, Stream requestData,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"].ToString();
switch (method)
{
case "getavatar":
return GetAvatar(request);
case "setavatar":
return SetAvatar(request);
case "resetavatar":
return ResetAvatar(request);
case "setitems":
return SetItems(request);
case "removeitems":
return RemoveItems(request);
}
m_log.DebugFormat("[AVATAR HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.Debug("[AVATAR HANDLER]: Exception {0}" + e);
}
return FailureResult();
}
byte[] GetAvatar(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
if (!request.ContainsKey("UserID"))
return FailureResult();
if (UUID.TryParse(request["UserID"].ToString(), out user))
{
AvatarData avatar = m_AvatarService.GetAvatar(user);
if (avatar == null)
return FailureResult();
Dictionary<string, object> result = new Dictionary<string, object>();
if (avatar == null)
result["result"] = "null";
else
result["result"] = avatar.ToKeyValuePairs();
string xmlString = ServerUtils.BuildXmlResponse(result);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
return FailureResult();
}
byte[] SetAvatar(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
if (!request.ContainsKey("UserID"))
return FailureResult();
if (!UUID.TryParse(request["UserID"].ToString(), out user))
return FailureResult();
AvatarData avatar = new AvatarData(request);
if (m_AvatarService.SetAvatar(user, avatar))
return SuccessResult();
return FailureResult();
}
byte[] ResetAvatar(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
if (!request.ContainsKey("UserID"))
return FailureResult();
if (!UUID.TryParse(request["UserID"].ToString(), out user))
return FailureResult();
if (m_AvatarService.ResetAvatar(user))
return SuccessResult();
return FailureResult();
}
byte[] SetItems(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
string[] names, values;
if (!request.ContainsKey("UserID") || !request.ContainsKey("Names") || !request.ContainsKey("Values"))
return FailureResult();
if (!UUID.TryParse(request["UserID"].ToString(), out user))
return FailureResult();
if (!(request["Names"] is List<string> || request["Values"] is List<string>))
return FailureResult();
List<string> _names = (List<string>)request["Names"];
names = _names.ToArray();
List<string> _values = (List<string>)request["Values"];
values = _values.ToArray();
if (m_AvatarService.SetItems(user, names, values))
return SuccessResult();
return FailureResult();
}
byte[] RemoveItems(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
string[] names;
if (!request.ContainsKey("UserID") || !request.ContainsKey("Names"))
return FailureResult();
if (!UUID.TryParse(request["UserID"].ToString(), out user))
return FailureResult();
if (!(request["Names"] is List<string>))
return FailureResult();
List<string> _names = (List<string>)request["Names"];
names = _names.ToArray();
if (m_AvatarService.RemoveItems(user, names))
return SuccessResult();
return FailureResult();
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] FailureResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
}
}
}
| 33.503704 | 114 | 0.574287 | [
"BSD-3-Clause"
] | N3X15/VoxelSim | OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs | 9,046 | C# |
#region License
//
// InputNodeMap.cs July 2006
//
// Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net>
//
// 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
#region Using directives
using System.Collections.Generic;
using System;
#endregion
namespace SimpleFramework.Xml.Stream {
/// <summary>
/// The <c>InputNodeMap</c> object represents a map to contain
/// attributes used by an input node. This can be used as an empty
/// node map, it can be used to extract its values from a start
/// element. This creates <c>InputAttribute</c> objects for
/// each node added to the map, these can then be used by an element
/// input node to represent attributes as input nodes.
/// </summary>
class InputNodeMap : LinkedHashMap<String, InputNode> : NodeMap<InputNode> {
/// <summary>
/// This is the source node that this node map belongs to.
/// </summary>
private readonly InputNode source;
/// <summary>
/// Constructor for the <c>InputNodeMap</c> object. This
/// is used to create an empty input node map, which will create
/// <c>InputAttribute</c> object for each inserted node.
/// </summary>
/// <param name="source">
/// this is the node this node map belongs to
/// </param>
protected InputNodeMap(InputNode source) {
this.source = source;
}
/// <summary>
/// Constructor for the <c>InputNodeMap</c> object. This
/// is used to create an input node map, which will be populated
/// with the attributes from the <c>StartElement</c> that
/// is specified.
/// </summary>
/// <param name="source">
/// this is the node this node map belongs to
/// </param>
/// <param name="element">
/// the element to populate the node map with
/// </param>
public InputNodeMap(InputNode source, EventNode element) {
this.source = source;
this.Build(element);
}
/// <summary>
/// This is used to insert all attributes belonging to the start
/// element to the map. All attributes acquired from the element
/// are converted into <c>InputAttribute</c> objects so
/// that they can be used as input nodes by an input node.
/// </summary>
/// <param name="element">
/// the element to acquire attributes from
/// </param>
public void Build(EventNode element) {
for(Attribute entry : element) {
InputAttribute value = new InputAttribute(source, entry);
if(!entry.isReserved()) {
Put(value.Name, value);
}
}
}
/// <summary>
/// This is used to acquire the actual node this map represents.
/// The source node provides further details on the context of
/// the node, such as the parent name, the namespace, and even
/// the value in the node. Care should be taken when using this.
/// </summary>
/// <returns>
/// this returns the node that this map represents
/// </returns>
public InputNode Node {
get {
return source;
}
}
//public InputNode GetNode() {
// return source;
//}
/// This is used to get the name of the element that owns the
/// nodes for the specified map. This can be used to determine
/// which element the node map belongs to.
/// </summary>
/// <returns>
/// this returns the name of the owning element
/// </returns>
public String Name {
get {
return source.Name;
}
}
//public String GetName() {
// return source.Name;
//}
/// This is used to add a new <c>InputAttribute</c> node to
/// the map. The created node can be used by an input node to
/// to represent the attribute as another input node. Once the
/// node is created it can be acquired using the specified name.
/// </summary>
/// <param name="name">
/// this is the name of the node to be created
/// </param>
/// <param name="value">
/// this is the value to be given to the node
/// </param>
/// <returns>
/// this returns the node that has just been added
/// </returns>
public InputNode Put(String name, String value) {
InputNode node = new InputAttribute(source, name, value);
if(name != null) {
Put(name, node);
}
return node;
}
/// <summary>
/// This is used to remove the <c>Node</c> mapped to the
/// given name. This returns a name value pair that represents
/// an attribute. If no node is mapped to the specified name
/// then this method will return a null value.
/// </summary>
/// <param name="name">
/// this is the name of the node to remove
/// </param>
/// <returns>
/// this will return the node mapped to the given name
/// </returns>
public InputNode Remove(String name) {
return super.Remove(name);
}
/// <summary>
/// This is used to acquire the <c>Node</c> mapped to the
/// given name. This returns a name value pair that represents
/// an attribute. If no node is mapped to the specified name
/// then this method will return a null value.
/// </summary>
/// <param name="name">
/// this is the name of the node to retrieve
/// </param>
/// <returns>
/// this will return the node mapped to the given name
/// </returns>
public InputNode Get(String name) {
return super.Get(name);
}
/// <summary>
/// This returns an iterator for the names of all the nodes in
/// this <c>NodeMap</c>. This allows the names to be
/// iterated within a for each loop in order to extract nodes.
/// </summary>
/// <returns>
/// this returns the names of the nodes in the map
/// </returns>
public Iterator<String> Iterator() {
return keySet().Iterator();
}
}
}
| 37.314607 | 79 | 0.59726 | [
"Apache-2.0"
] | AMCON-GmbH/simplexml | port/src/main/Xml/Stream/InputNodeMap.cs | 6,642 | C# |
using System;
using System.Runtime.CompilerServices;
namespace MarcusW.VncClient
{
/// <summary>
/// Represents a rectangle of a given <see cref="Position"/> and <see cref="Size"/>.
/// </summary>
public readonly struct Rectangle : IEquatable<Rectangle>
{
/// <summary>
/// A rectangle with the size zero at the origin of the coordinate system.
/// </summary>
public static readonly Rectangle Zero = new Rectangle(Position.Origin, Size.Zero);
/// <summary>
/// Gets the position of the upper left corner of the rectangle.
/// </summary>
public Position Position { get; }
/// <summary>
/// Gets the size of the rectangle.
/// </summary>
public Size Size { get; }
/// <summary>
/// Initializes a new instance of the <see cref="Rectangle"/> structure.
/// </summary>
/// <param name="position">The position of the upper left corner of the rectangle.</param>
/// <param name="size">The size of the rectangle.</param>
public Rectangle(Position position, Size size)
{
Position = position;
Size = size;
}
/// <summary>
/// Initializes a new instance of the <see cref="Rectangle"/> structure.
/// </summary>
/// <param name="x">The x coordinate of the upper left corner of the rectangle.</param>
/// <param name="y">The y coordinate of the upper left corner of the rectangle.</param>
/// <param name="width">The width of the rectangle.</param>
/// <param name="height">The height of the rectangle.</param>
public Rectangle(int x, int y, int width, int height)
{
Position = new Position(x, y);
Size = new Size(width, height);
}
/// <summary>
/// Checks for equality between two <see cref="Rectangle"/>s.
/// </summary>
/// <param name="left">The first rectangle.</param>
/// <param name="right">The second rectangle.</param>
/// <returns>True if the rectangles are equal, otherwise false.</returns>
public static bool operator ==(Rectangle left, Rectangle right) => left.Equals(right);
/// <summary>
/// Checks for inequality between two <see cref="Rectangle"/>s.
/// </summary>
/// <param name="left">The first rectangle.</param>
/// <param name="right">The second rectangle.</param>
/// <returns>True if the rectangles are unequal, otherwise false.</returns>
public static bool operator !=(Rectangle left, Rectangle right) => !left.Equals(right);
/// <inheritdoc />
public bool Equals(Rectangle other) => Position.Equals(other.Position) && Size.Equals(other.Size);
/// <inheritdoc />
public override bool Equals(object? obj) => obj is Rectangle other && Equals(other);
/// <inheritdoc />
public override int GetHashCode() => HashCode.Combine(Position, Size);
/// <summary>
/// Returns a new <see cref="Rectangle"/> with the specified position.
/// </summary>
/// <param name="position">The position.</param>
/// <returns>A new rectangle.</returns>
public Rectangle WithPosition(Position position) => new Rectangle(position, Size);
/// <summary>
/// Returns a new <see cref="Rectangle"/> with the specified size.
/// </summary>
/// <param name="size">The size.</param>
/// <returns>A new rectangle.</returns>
public Rectangle WithSize(Size size) => new Rectangle(Position, size);
/// <summary>
/// Returns whether this rectangle has no content (one side is zero)
/// </summary>
/// <returns>True if it has no content, otherwise false.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsEmpty() => Size.Width == 0 || Size.Height == 0;
/// <summary>
/// Returns whether this rectangle completely fits inside an area in the origin with the given size.
/// </summary>
/// <param name="areaSize">The size of the area in which the rectangle should fit in.</param>
/// <returns>True if it fits inside, otherwise false.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool FitsInside(in Size areaSize) => FitsInside(new Rectangle(Position.Origin, areaSize));
/// <summary>
/// Returns whether this rectangle completely fits inside the given area.
/// </summary>
/// <param name="area">The area in which the rectangle should fit in.</param>
/// <returns>True if it fits inside, otherwise false.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool FitsInside(in Rectangle area)
{
static bool InRange(int rectA, int rectB, int areaA, int areaB) => rectA >= areaA && rectB <= areaB;
return InRange(Position.X, Position.X + Size.Width, area.Position.X, area.Position.X + area.Size.Width)
&& InRange(Position.Y, Position.Y + Size.Height, area.Position.Y, area.Position.Y + area.Size.Height);
}
/// <summary>
/// Returns whether this rectangle overlaps the given area.
/// </summary>
/// <param name="area">The area to test for.</param>
/// <returns>True if they overlap, otherwise false.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Overlaps(in Rectangle area)
{
static bool IsValueInside(int value, int lower, int upper) => value >= lower && value <= upper;
bool overlapsX = IsValueInside(Position.X, area.Position.X, area.Position.X + area.Size.Width) || IsValueInside(area.Position.X, Position.X, Position.X + Size.Width);
bool overlapsY = IsValueInside(Position.Y, area.Position.Y, area.Position.Y + area.Size.Height) || IsValueInside(area.Position.Y, Position.Y, Position.Y + Size.Height);
return overlapsX && overlapsY;
}
/// <summary>
/// Returns a new <see cref="Rectangle"/> that is reduced enough to make it fit inside the given area.
/// </summary>
/// <param name="area">The area in which the rectangle should fit in.</param>
/// <returns>A new rectangle.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Rectangle CroppedTo(in Rectangle area)
{
static void Normalize(ref int rectA, ref int rectB, int areaA, int areaB)
{
if (rectB <= areaA)
{
rectA = rectB = areaA;
return;
}
if (rectA >= areaB)
{
rectA = rectB = areaB;
return;
}
if (rectA < areaA)
rectA = areaA;
if (rectB > areaB)
rectB = areaB;
}
int xa = Position.X;
int ya = Position.Y;
int xb = xa + Size.Width;
int yb = ya + Size.Height;
Normalize(ref xa, ref xb, area.Position.X, area.Position.X + area.Size.Width);
Normalize(ref ya, ref yb, area.Position.Y, area.Position.Y + area.Size.Height);
return new Rectangle(xa, ya, xb - xa, yb - ya);
}
/// <summary>
/// Returns the string representation of the rectangle.
/// </summary>
/// <returns>The string representation of the rectangle.</returns>
public override string ToString() => $"{Position}, {Size}";
}
}
| 42.734807 | 180 | 0.582547 | [
"MIT"
] | MarcusWichelmann/MarcusW.VncClient | src/MarcusW.VncClient/Rectangle.cs | 7,735 | 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/wincrypt.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="CERT_LOGOTYPE_REFERENCE" /> struct.</summary>
public static unsafe class CERT_LOGOTYPE_REFERENCETests
{
/// <summary>Validates that the <see cref="CERT_LOGOTYPE_REFERENCE" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<CERT_LOGOTYPE_REFERENCE>(), Is.EqualTo(sizeof(CERT_LOGOTYPE_REFERENCE)));
}
/// <summary>Validates that the <see cref="CERT_LOGOTYPE_REFERENCE" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(CERT_LOGOTYPE_REFERENCE).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="CERT_LOGOTYPE_REFERENCE" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(CERT_LOGOTYPE_REFERENCE), Is.EqualTo(16));
}
else
{
Assert.That(sizeof(CERT_LOGOTYPE_REFERENCE), Is.EqualTo(8));
}
}
}
}
| 37.636364 | 145 | 0.650966 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | tests/Interop/Windows/um/wincrypt/CERT_LOGOTYPE_REFERENCETests.cs | 1,658 | C# |
using UnityEngine;
using System.Collections;
using UnityStandardAssets.Characters.FirstPerson;
public class NetworkManager : MonoBehaviour {
[SerializeField]
bool OfflineMode = false;
public Camera standbyCamera;
// Use this for initialization
void Start () {
Connect();
}
// Update is called once per frame
void Connect () {
PhotonNetwork.offlineMode = OfflineMode;
PhotonNetwork.ConnectUsingSettings("MultiFPS 0.0.1");
}
void OnGUI() {
if(PhotonNetwork.inRoom)
GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString() + " - " + (PhotonNetwork.inRoom? PhotonNetwork.room.name : "No Room"));
}
void OnJoinedLobby() {
PhotonNetwork.JoinRandomRoom();
}
void OnPhotonRandomJoinFailed() {
PhotonNetwork.CreateRoom("Room 1");
}
void OnJoinedRoom() {
Debug.Log("Room Joined");
SpawnMyPlayer();
}
void SpawnMyPlayer() {
GameObject myPlayer = PhotonNetwork.Instantiate("FPSController", RandomSpawnVector3(), Quaternion.identity, 0);
FirstPersonController myPlayerController = myPlayer.GetComponent<FirstPersonController>();
myPlayerController.enabled = true;
myPlayerController.GetComponentInChildren<Camera>().enabled = true;
myPlayerController.GetComponentInChildren<AudioListener>().enabled = true;
standbyCamera.enabled = false;
standbyCamera.GetComponent<AudioListener>().enabled = false;
}
Vector3 RandomSpawnVector3() {
GameObject[] respawn = GameObject.FindGameObjectsWithTag("Respawn");
return respawn[Random.Range(0,respawn.Length)].transform.position;
}
}
| 29.666667 | 144 | 0.690124 | [
"MIT"
] | ohyonghao/MultiFPS | Assets/NetworkManager.cs | 1,693 | C# |
namespace LibraryItems
{
partial class PatronSelectionForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.patronSelectCbo = new System.Windows.Forms.ComboBox();
this.chooseLbl = new System.Windows.Forms.Label();
this.selectBtn = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// patronSelectCbo
//
this.patronSelectCbo.FormattingEnabled = true;
this.patronSelectCbo.Location = new System.Drawing.Point(129, 34);
this.patronSelectCbo.Name = "patronSelectCbo";
this.patronSelectCbo.Size = new System.Drawing.Size(121, 24);
this.patronSelectCbo.TabIndex = 0;
//
// chooseLbl
//
this.chooseLbl.AutoSize = true;
this.chooseLbl.Location = new System.Drawing.Point(12, 37);
this.chooseLbl.Name = "chooseLbl";
this.chooseLbl.Size = new System.Drawing.Size(97, 17);
this.chooseLbl.TabIndex = 1;
this.chooseLbl.Text = "Select Patron:";
//
// selectBtn
//
this.selectBtn.Location = new System.Drawing.Point(74, 111);
this.selectBtn.Name = "selectBtn";
this.selectBtn.Size = new System.Drawing.Size(129, 23);
this.selectBtn.TabIndex = 2;
this.selectBtn.Text = "Select";
this.selectBtn.UseVisualStyleBackColor = true;
this.selectBtn.Click += new System.EventHandler(this.SelectBtn_Click);
//
// PatronSelectionForm
//
this.AcceptButton = this.selectBtn;
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(321, 173);
this.Controls.Add(this.selectBtn);
this.Controls.Add(this.chooseLbl);
this.Controls.Add(this.patronSelectCbo);
this.Name = "PatronSelectionForm";
this.Text = "PatronSelectionForm";
this.Load += new System.EventHandler(this.PatronSelectionForm_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox patronSelectCbo;
private System.Windows.Forms.Label chooseLbl;
private System.Windows.Forms.Button selectBtn;
}
} | 39.744186 | 108 | 0.562025 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | edelenalex/c-sharp | PatronSelectionForm.Designer.cs | 3,420 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using TEABot.Bot;
using TEABot.TEAScript;
namespace TEABot.UI
{
public partial class MainForm : Form
{
/// <summary>
/// Whether to automatically connect to the IRC server after startup
/// </summary>
private bool mAutoConnect = true;
/// <summary>
/// Do not use data directory from settings, but from command line
/// </summary>
private bool mOverrideDataDirectory = false;
/// <summary>
/// Data directory from command line
/// </summary>
private string mCmdDataDirectory = String.Empty;
/// <summary>
/// Chat bot core
/// </summary>
private readonly TBChatBot mChatBot = new();
/// <summary>
/// RTF template for outgoing messages
/// </summary>
private RtfTemplate mRTFOutgoing = new();
/// <summary>
/// RTF template for incoming messages
/// </summary>
private RtfTemplate mRTFIncoming = new();
/// <summary>
/// RTF template for messages entered via the input box
/// </summary>
private RtfTemplate mRTFLocal = new();
/// <summary>
/// RTF template for info messages
/// </summary>
private RtfTemplate mRTFInfo = new();
/// <summary>
/// RTF template for warning messages
/// </summary>
private RtfTemplate mRTFWarning = new();
/// <summary>
/// RTF template for error messages
/// </summary>
private RtfTemplate mRTFError = new();
/// <summary>
/// Get the configuration data directory path
/// </summary>
/// <returns>Data directory path</returns>
private string GetDataDirectory()
{
return mOverrideDataDirectory ? mCmdDataDirectory : Properties.Settings.Default.DataDirectory;
}
/// <summary>
/// Open the form for data directory configuration
/// </summary>
private void OpenDataDirectoryConfigurationForm()
{
var ddcf = new DataDirectoryConfigForm();
var res = ddcf.ShowDialog(this);
if (res == DialogResult.OK)
{
ReloadRTFTemplates();
var dataDir = GetDataDirectory();
mChatBot.ReloadConfig(dataDir);
mChatBot.ReloadScripts(dataDir);
}
}
/// <summary>
/// Reload the logging RTF templates
/// </summary>
private void ReloadRTFTemplates()
{
LoadRtfTemplate(out mRTFOutgoing, "outgoing.rtf");
LoadRtfTemplate(out mRTFIncoming, "incoming.rtf");
LoadRtfTemplate(out mRTFLocal, "local.rtf");
LoadRtfTemplate(out mRTFInfo, "info.rtf");
LoadRtfTemplate(out mRTFWarning, "warning.rtf");
LoadRtfTemplate(out mRTFError, "error.rtf");
}
/// <summary>
/// Load a specific RTF template
/// </summary>
/// <param name="a_template">The template to load into</param>
/// <param name="a_filename">The file to load from</param>
private void LoadRtfTemplate(out RtfTemplate ao_template, string a_filename)
{
try
{
string templateText = File.ReadAllText(Path.Combine(GetDataDirectory(), a_filename));
ao_template = new RtfTemplate(templateText);
}
catch (Exception e)
{
LogMessage(mRTFError, String.Format("Failed to load RTF template from \"{0}\": {1}",
a_filename,
e.Message));
ao_template = new RtfTemplate();
}
}
/// <summary>
/// Log a message using the given RTF template and the global channel context
/// </summary>
/// <param name="a_template">The RTF template to use</param>
/// <param name="a_message">The message to log</param>
private void LogMessage(RtfTemplate a_template, string a_message)
{
LogMessage(a_template, a_message, mChatBot.Global);
}
/// <summary>
/// Log a message using the given RTF template and the given channel's own identity as the message sender
/// </summary>
/// <param name="a_template">The RTF template to use</param>
/// <param name="a_message">The message to log</param>
/// <param name="a_channel">The channel for which this message is to be logged</param>
private void LogMessage(RtfTemplate a_template, string a_message, TBChannel a_channel)
{
LogMessage(a_template, a_message, mChatBot.Global, a_channel.Configuration.Self);
}
/// <summary>
/// Log a message using the given RTF template
/// </summary>
/// <param name="a_template">The RTF template to use</param>
/// <param name="a_message">The message to log</param>
/// <param name="a_channel">The channel for which this message is to be logged</param>
/// <param name="a_sender">The sender os the message</param>
private void LogMessage(RtfTemplate a_template, string a_message, TBChannel a_channel, string a_sender)
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => LogMessage(a_template, a_message, a_channel, a_sender)));
return;
}
rtbLog.SelectionStart = rtbLog.TextLength;
try
{
rtbLog.SelectedRtf = a_template.Apply(a_message,
a_sender,
a_channel?.Configuration?.TimestampFormat ?? "HH:mm:ss")
+ Environment.NewLine;
}
catch
{
// fallback for invalid RTF format: print message as-is
rtbLog.SelectedText = a_message + Environment.NewLine;
}
rtbLog.SelectionStart = rtbLog.TextLength;
rtbLog.ScrollToCaret();
}
/// <summary>
/// Handle connection status dependend display and access
/// </summary>
/// <param name="a_connectionStatus">The bot connection status</param>
private void UpdateConnectionStatusDisplay(TBConnectionStatus a_connectionStatus)
{
if (InvokeRequired)
{
BeginInvoke(new MethodInvoker(() => { UpdateConnectionStatusDisplay(a_connectionStatus); }));
}
if (a_connectionStatus.IrcClientRunning)
{
if (a_connectionStatus.IrcClientConnected)
{
tsslIrcStatus.Image = Icons.ic_connected;
tsmiIrcReconnect.Enabled = true;
}
else
{
tsslIrcStatus.Image = Icons.ic_connecting;
tsmiIrcReconnect.Enabled = false;
}
tsmiIrcConnect.Enabled = false;
}
else
{
tsslIrcStatus.Image = Icons.ic_disconnected;
tsmiIrcConnect.Enabled = true;
tsmiIrcReconnect.Enabled = false;
}
if (a_connectionStatus.WebSocketServerRunning)
{
tsslWebSocketStatus.Image = (a_connectionStatus.WebSocketClientCount > 0)
? Icons.ic_connected
: Icons.ic_connecting;
tsslWebSocketStatus.Text = a_connectionStatus.WebSocketClientCount.ToString();
tsmiRestartWebSocket.Enabled = true;
}
else
{
tsslWebSocketStatus.Image = Icons.ic_connection_disabled;
tsslWebSocketStatus.Text = String.Empty;
tsmiRestartWebSocket.Enabled = false;
}
}
private void MChatBot_OnChatMessage(TBChannel a_channel, TBMessageDirection a_direction, string a_sender, string a_message)
{
RtfTemplate template = a_direction switch
{
TBMessageDirection.SENT => mRTFOutgoing,
TBMessageDirection.MANUAL => mRTFLocal,
_ => mRTFIncoming,
};
LogMessage(template, a_message, a_channel, a_sender);
}
private void MChatBot_OnInfo(TBChannel a_channel, string a_message)
{
if (a_channel.Configuration.InfoLog)
{
LogMessage(mRTFInfo, a_message, a_channel, String.Empty);
}
}
private void MChatBot_OnNotice(TBChannel a_channel, string a_message)
{
// Same as info but without filtering
LogMessage(mRTFInfo, a_message, a_channel, String.Empty);
}
private void MChatBot_OnWarning(TBChannel a_channel, string a_message)
{
LogMessage(mRTFWarning, a_message, a_channel, String.Empty);
}
private void MChatBot_OnError(TBChannel a_channel, string a_message)
{
LogMessage(mRTFError, a_message, a_channel, String.Empty);
}
private void MChatBot_OnConnectionStatusChanged(TBChatBot a_sender, TBConnectionStatus a_connectionStatus)
{
UpdateConnectionStatusDisplay(a_connectionStatus);
}
public MainForm()
{
InitializeComponent();
}
private void DataDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenDataDirectoryConfigurationForm();
}
private void MainForm_Shown(object sender, EventArgs e)
{
if (!mOverrideDataDirectory && !Directory.Exists(Properties.Settings.Default.DataDirectory))
{
OpenDataDirectoryConfigurationForm();
}
}
private void TsmiReload_Click(object sender, EventArgs e)
{
mChatBot.ReloadConfig(GetDataDirectory());
}
private void TsmiRecompile_Click(object sender, EventArgs e)
{
mChatBot.ReloadScripts(GetDataDirectory());
}
private void TsmiReloadRtf_Click(object sender, EventArgs e)
{
ReloadRTFTemplates();
}
private void MainForm_Load(object sender, EventArgs e)
{
// handle command line arguments
var cmdArgs = Environment.GetCommandLineArgs();
// disable autoconnect
if (cmdArgs.Any(a => a.Equals("/noConnect", StringComparison.InvariantCultureIgnoreCase)))
{
mAutoConnect = false;
}
// override data directory
if ((cmdArgs.Length > 1)
&& Directory.Exists(cmdArgs.Last()))
{
mCmdDataDirectory = cmdArgs.Last();
mOverrideDataDirectory = true;
// block opening data directory configuration form
tsmiDataDirectory.Enabled = false;
}
// set initial connection status
UpdateConnectionStatusDisplay(mChatBot.ConnectionStatus);
// attach chatbot events
mChatBot.OnChatMessage += MChatBot_OnChatMessage;
mChatBot.OnInfo += MChatBot_OnInfo;
mChatBot.OnNotice += MChatBot_OnNotice;
mChatBot.OnWarning += MChatBot_OnWarning;
mChatBot.OnError += MChatBot_OnError;
mChatBot.OnConnectionStatusChanged += MChatBot_OnConnectionStatusChanged;
// load config
var dataDir = GetDataDirectory();
if (Directory.Exists(dataDir))
{
// load and print motd
try
{
string motd = File.ReadAllText(Path.Combine(dataDir, "motd.rtf"));
rtbLog.Rtf = motd;
}
catch
{
// don't care, no motd given
}
// load config and scripts
ReloadRTFTemplates();
mChatBot.ReloadConfig(dataDir);
mChatBot.ReloadScripts(dataDir);
// autoconnect
if (mAutoConnect)
{
mChatBot.Connect();
}
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
// detach chatbot events
mChatBot.OnChatMessage -= MChatBot_OnChatMessage;
mChatBot.OnInfo -= MChatBot_OnInfo;
mChatBot.OnNotice -= MChatBot_OnNotice;
mChatBot.OnWarning -= MChatBot_OnWarning;
mChatBot.OnError -= MChatBot_OnError;
mChatBot.OnConnectionStatusChanged -= MChatBot_OnConnectionStatusChanged;
// cancel tasks and disconnect bot
mChatBot.Disconnect();
}
private void TsmiIrcConnect_Click(object sender, EventArgs e)
{
mChatBot.Connect();
}
private void TsmiIrcDisconnect_Click(object sender, EventArgs e)
{
mChatBot.Disconnect();
}
private void TsmiTBGitHub_Click(object sender, EventArgs e)
{
Process.Start(new ProcessStartInfo
{
FileName = Properties.Resources.GitHubUrl,
UseShellExecute = true
});
}
private void TsmiTBExit_Click(object sender, EventArgs e)
{
Close();
}
private void TsmiTBAbout_Click(object sender, EventArgs e)
{
new AboutForm().ShowDialog(this);
}
private void tsmiIrcReconnect_Click(object sender, EventArgs e)
{
mChatBot.ReconnectIrc();
}
private void tsmiRestartWebSocket_Click(object sender, EventArgs e)
{
mChatBot.RestartWebSocketServer();
}
}
}
| 36.225806 | 132 | 0.547709 | [
"MIT"
] | LordPrevious/TEABot | TEABot/UI/MainForm.cs | 14,601 | C# |
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using Xunit;
namespace MongoDB.Driver.Tests.Builders
{
public class SortByBuilderTests
{
[Fact]
public void TestAscending1()
{
var sortBy = SortBy.Ascending("a");
string expected = "{ \"a\" : 1 }";
Assert.Equal(expected, sortBy.ToJson());
}
[Fact]
public void TestAscending2()
{
var sortBy = SortBy.Ascending("a", "b");
string expected = "{ \"a\" : 1, \"b\" : 1 }";
Assert.Equal(expected, sortBy.ToJson());
}
[Fact]
public void TestAscendingAscending()
{
var sortBy = SortBy.Ascending("a").Ascending("b");
string expected = "{ \"a\" : 1, \"b\" : 1 }";
Assert.Equal(expected, sortBy.ToJson());
}
[Fact]
public void TestAscendingDescending()
{
var sortBy = SortBy.Ascending("a").Descending("b");
string expected = "{ \"a\" : 1, \"b\" : -1 }";
Assert.Equal(expected, sortBy.ToJson());
}
[Fact]
public void TestDescending1()
{
var sortBy = SortBy.Descending("a");
string expected = "{ \"a\" : -1 }";
Assert.Equal(expected, sortBy.ToJson());
}
[Fact]
public void TestDescending2()
{
var sortBy = SortBy.Descending("a", "b");
string expected = "{ \"a\" : -1, \"b\" : -1 }";
Assert.Equal(expected, sortBy.ToJson());
}
[Fact]
public void TestDescendingAscending()
{
var sortBy = SortBy.Descending("a").Ascending("b");
string expected = "{ \"a\" : -1, \"b\" : 1 }";
Assert.Equal(expected, sortBy.ToJson());
}
[Fact]
public void TestMetaTextGenerate()
{
var sortBy = SortBy.MetaTextScore("score");
string expected = "{ \"score\" : { \"$meta\" : \"textScore\" } }";
Assert.Equal(expected, sortBy.ToJson());
}
[Fact]
public void TestMetaTextAndOtherFields()
{
var sortBy = SortBy.MetaTextScore("searchrelevancescore").Descending("y").Ascending("z");
string expected = "{ \"searchrelevancescore\" : { \"$meta\" : \"textScore\" }, \"y\" : -1, \"z\" : 1 }";
Assert.Equal(expected, sortBy.ToJson());
}
[Fact]
public void TestMetaText()
{
if (LegacyTestConfiguration.Server.Primary.Supports(FeatureId.TextSearchQuery))
{
var collection = LegacyTestConfiguration.Database.GetCollection<BsonDocument>("test_meta_text_sort");
collection.Drop();
collection.CreateIndex(IndexKeys.Text("textfield"));
collection.Insert(new BsonDocument
{
{ "_id", 1 },
{ "textfield", "The quick brown fox jumped" },
{ "z", 1 }
});
collection.Insert(new BsonDocument
{
{ "_id", 2 },
{ "textfield", "over the lazy brown dog and brown cat" },
{ "z", 2 }
});
collection.Insert(new BsonDocument
{
{ "_id", 3 },
{ "textfield", "over the lazy brown dog and brown cat" },
{ "z", 4 }
});
collection.Insert(new BsonDocument
{
{ "_id", 4 },
{ "textfield", "over the lazy brown dog and brown cat" },
{ "z", 3 }
});
var query = Query.Text("brown");
var fields = Fields.MetaTextScore("relevance");
var sortBy = SortBy.MetaTextScore("relevance").Descending("z");
var cursor = collection.FindAs<BsonDocument>(query).SetFields(fields).SetSortOrder(sortBy);
var result = cursor.ToArray();
Assert.Equal(4, result.Length);
Assert.Equal(3, result[0]["_id"].AsInt32);
Assert.Equal(4, result[1]["_id"].AsInt32);
Assert.Equal(2, result[2]["_id"].AsInt32);
Assert.Equal(1, result[3]["_id"].AsInt32);
}
}
}
}
| 34.917241 | 117 | 0.507802 | [
"Apache-2.0"
] | 591094733/mongo-csharp-driver | tests/MongoDB.Driver.Legacy.Tests/Builders/SortByBuilderTests.cs | 5,063 | C# |
namespace Selector.Tizen
{
class Program : global::Xamarin.Forms.Platform.Tizen.FormsApplication
{
protected override void OnCreate()
{
base.OnCreate();
LoadApplication(new App());
}
static void Main(string[] args)
{
var app = new Program();
global::Xamarin.Forms.Platform.Tizen.Forms.Init(app);
app.Run(args);
}
}
}
| 23.105263 | 73 | 0.537585 | [
"Apache-2.0"
] | Samsung/xamarin-forms-samples | Templates/DataTemplateSelector/Tizen/App.cs | 441 | C# |
using BusinessLayer.Abstract;
using DataAccessLayer.Abstract;
using EntityLayer.Concrete;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLayer.Concrete
{
public class Message2Manager :IMessage2Service
{
IMessage2Dal _message2Dal;
public Message2Manager(IMessage2Dal message2Dal)
{
_message2Dal = message2Dal;
}
public List<Message2> GetInboxListByWriter(int id)
{
return _message2Dal.GetListWithMessageByWriter(id);
}
public List<Message2> GetList()
{
return _message2Dal.GetListAll();
}
public void TAdd(Message2 t)
{
throw new NotImplementedException();
}
public void TDelete(Message2 t)
{
throw new NotImplementedException();
}
public Message2 TGetById(int id)
{
return _message2Dal.GetById(id);
}
public void TUpdate(Message2 t)
{
throw new NotImplementedException();
}
}
}
| 21.641509 | 63 | 0.610288 | [
"MIT"
] | mertozler/BlogPanel | BusinessLayer/Concrete/Message2Manager.cs | 1,149 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.DotNet.Interactive.Server
{
public class StreamKernelCommandConverter : JsonConverter<StreamKernelCommand>
{
private static readonly CommandDeserializer _deserializer = new CommandDeserializer();
public override void WriteJson(JsonWriter writer, StreamKernelCommand value, JsonSerializer serializer)
{
var jObject = new JObject
{
{"id", value.Id },
{"commandType", value.CommandType },
{"command", JObject.FromObject(value.Command,serializer) }
};
serializer.Serialize(writer,jObject);
}
public override StreamKernelCommand ReadJson(JsonReader reader, Type objectType, StreamKernelCommand existingValue,
bool hasExistingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
var ret = new StreamKernelCommand
{
Id = jObject["id"].Value<int>(),
CommandType = jObject["commandType"].Value<string>()
};
if (string.IsNullOrWhiteSpace(ret.CommandType))
{
throw new JsonReaderException("Cannot deserialize with null or white space commandType");
}
if (jObject.TryGetValue("command", StringComparison.InvariantCultureIgnoreCase, out var commandValue))
{
var command = _deserializer.Deserialize(ret.CommandType, commandValue);
ret.Command = command ?? throw new JsonReaderException($"Cannot deserialize {ret.CommandType}");
}
return ret;
}
}
} | 38.2 | 123 | 0.632461 | [
"MIT"
] | daxian-dbw/try | Microsoft.DotNet.Interactive/Server/StreamKernelCommandConverter.cs | 1,912 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using RandREng.Types;
namespace RandREng.MeasureDBEntity
{
[MetadataType(typeof(Employee.MetaData))]
public partial class Employee
{
public string FirstName
{
get { return this.User.FirstName; }
set { this.User.FirstName = value; }
}
public string LastName
{
get { return this.User.LastName; ; }
set { this.User.LastName = value; }
}
public string Name
{
get { return this.User.Name; }
}
public class MetaData
{
[Display(Name = "First Name", Prompt = "Enter First Name", Description = "First Name")]
[StringLength(20)]
[Required]
public string FirstName;
[Display(Name = "Last Name", Prompt = "Enter Last Name", Description = "Last Name")]
[StringLength(20)]
[Required]
public string LastName;
[DataType(DataType.EmailAddress)]
[Display(Name = "Email Address", Prompt = "Enter Customer Email Address", Description = "Email")]
[Required]
public string Email;
[Display(Name = "Address", Prompt = "Enter Customer Address", Description = "Address Line 1")]
[StringLength(50)]
[Required]
public string Address1;
[Display(Name = "Address Additional", Prompt = "Enter Customer Address", Description = "Address Line 2")]
[StringLength(50)]
public string Address2;
[Display(Name = "City", Prompt = "Enter City", Description = "City")]
[StringLength(30)]
[Required]
public string City;
[Display(Name = "State", Prompt = "Enter State", Description = "State")]
[StringLength(2)]
[Required]
public string State;
[Display(Name = "Zip Code", Prompt = "Enter Zip Code", Description = "Zip Code")]
[PostalPlus4]
[Required]
public string Zip;
[Display(Name = "Home Number", Prompt = "Enter Home Phone Number", Description = "Customer Home Phone")]
[PhoneNumber10]
public string PhoneNumber1;
[Display(Name = "Mobile Number", Prompt = "Enter Mobile Phone Number", Description = "Customer Mobile Phone")]
[PhoneNumber10]
public string PhoneNumber2;
}
}
} | 28.294872 | 114 | 0.656094 | [
"Apache-2.0"
] | raboud/Measures | MeasuresEntity/Employee.extended.cs | 2,209 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace LumiSoft.Net
{
/// <summary>
/// This class provides usefull text methods.
/// </summary>
public class TextUtils
{
#region static method QuoteString
/// <summary>
/// Qoutes string and escapes fishy('\',"') chars.
/// </summary>
/// <param name="text">Text to quote.</param>
/// <returns></returns>
public static string QuoteString(string text)
{
// String is already quoted-string.
if(text != null && text.StartsWith("\"") && text.EndsWith("\"")){
return text;
}
StringBuilder retVal = new StringBuilder();
for(int i=0;i<text.Length;i++){
char c = text[i];
if(c == '\\'){
retVal.Append("\\\\");
}
else if(c == '\"'){
retVal.Append("\\\"");
}
else{
retVal.Append(c);
}
}
return "\"" + retVal.ToString() + "\"";
}
#endregion
#region static method UnQuoteString
/// <summary>
/// Unquotes and unescapes escaped chars specified text. For example "xxx" will become to 'xxx', "escaped quote \"", will become to escaped 'quote "'.
/// </summary>
/// <param name="text">Text to unquote.</param>
/// <returns></returns>
public static string UnQuoteString(string text)
{
int startPosInText = 0;
int endPosInText = text.Length;
//--- Trim. We can't use standard string.Trim(), it's slow. ----//
for(int i=0;i<endPosInText;i++){
char c = text[i];
if(c == ' ' || c == '\t'){
startPosInText++;
}
else{
break;
}
}
for(int i=endPosInText-1;i>0;i--){
char c = text[i];
if(c == ' ' || c == '\t'){
endPosInText--;
}
else{
break;
}
}
//--------------------------------------------------------------//
// All text trimmed
if((endPosInText - startPosInText) <= 0){
return "";
}
// Remove starting and ending quotes.
if(text[startPosInText] == '\"'){
startPosInText++;
}
if(text[endPosInText - 1] == '\"'){
endPosInText--;
}
// Just '"'
if(endPosInText == startPosInText - 1){
return "";
}
char[] chars = new char[endPosInText - startPosInText];
int posInChars = 0;
bool charIsEscaped = false;
for(int i=startPosInText;i<endPosInText;i++){
char c = text[i];
// Escaping char
if(!charIsEscaped && c == '\\'){
charIsEscaped = true;
}
// Escaped char
else if(charIsEscaped){
// TODO: replace \n,\r,\t,\v ???
chars[posInChars] = c;
posInChars++;
charIsEscaped = false;
}
// Normal char
else{
chars[posInChars] = c;
posInChars++;
charIsEscaped = false;
}
}
return new string(chars,0,posInChars);
}
#endregion
#region static method EscapeString
/// <summary>
/// Escapes specified chars in the specified string.
/// </summary>
/// <param name="text">Text to escape.</param>
/// <param name="charsToEscape">Chars to escape.</param>
public static string EscapeString(string text,char[] charsToEscape)
{
// Create worst scenario buffer, assume all chars must be escaped
char[] buffer = new char[text.Length * 2];
int nChars = 0;
foreach(char c in text){
foreach(char escapeChar in charsToEscape){
if(c == escapeChar){
buffer[nChars] = '\\';
nChars++;
break;
}
}
buffer[nChars] = c;
nChars++;
}
return new string(buffer,0,nChars);
}
#endregion
#region static method UnEscapeString
/// <summary>
/// Unescapes all escaped chars.
/// </summary>
/// <param name="text">Text to unescape.</param>
/// <returns></returns>
public static string UnEscapeString(string text)
{
// Create worst scenarion buffer, non of the chars escaped.
char[] buffer = new char[text.Length];
int nChars = 0;
bool escapedCahr = false;
foreach(char c in text){
if(!escapedCahr && c == '\\'){
escapedCahr = true;
}
else{
buffer[nChars] = c;
nChars++;
escapedCahr = false;
}
}
return new string(buffer,0,nChars);
}
#endregion
#region static method SplitQuotedString
/// <summary>
/// Splits string into string arrays. This split method won't split qouted strings, but only text outside of qouted string.
/// For example: '"text1, text2",text3' will be 2 parts: "text1, text2" and text3.
/// </summary>
/// <param name="text">Text to split.</param>
/// <param name="splitChar">Char that splits text.</param>
/// <returns></returns>
public static string[] SplitQuotedString(string text,char splitChar)
{
return SplitQuotedString(text,splitChar,false);
}
/// <summary>
/// Splits string into string arrays. This split method won't split qouted strings, but only text outside of qouted string.
/// For example: '"text1, text2",text3' will be 2 parts: "text1, text2" and text3.
/// </summary>
/// <param name="text">Text to split.</param>
/// <param name="splitChar">Char that splits text.</param>
/// <param name="unquote">If true, splitted parst will be unqouted if they are qouted.</param>
/// <returns></returns>
public static string[] SplitQuotedString(string text,char splitChar,bool unquote)
{
return SplitQuotedString(text,splitChar,unquote,int.MaxValue);
}
/// <summary>
/// Splits string into string arrays. This split method won't split qouted strings, but only text outside of qouted string.
/// For example: '"text1, text2",text3' will be 2 parts: "text1, text2" and text3.
/// </summary>
/// <param name="text">Text to split.</param>
/// <param name="splitChar">Char that splits text.</param>
/// <param name="unquote">If true, splitted parst will be unqouted if they are qouted.</param>
/// <param name="count">Maximum number of substrings to return.</param>
/// <returns>Returns splitted string.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>text</b> is null reference.</exception>
public static string[] SplitQuotedString(string text,char splitChar,bool unquote,int count)
{
if(text == null){
throw new ArgumentNullException("text");
}
List<string> splitParts = new List<string>(); // Holds splitted parts
int startPos = 0;
bool inQuotedString = false; // Holds flag if position is quoted string or not
char lastChar = '0';
for(int i=0;i<text.Length;i++){
char c = text[i];
// We have exceeded maximum allowed splitted parts.
if((splitParts.Count + 1) >= count){
break;
}
// We have quoted string start/end.
if(lastChar != '\\' && c == '\"'){
inQuotedString = !inQuotedString;
}
// We have escaped or normal char.
//else{
// We igonre split char in quoted-string.
if(!inQuotedString){
// We have split char, do split.
if(c == splitChar){
if(unquote){
splitParts.Add(UnQuoteString(text.Substring(startPos,i - startPos)));
}
else{
splitParts.Add(text.Substring(startPos,i - startPos));
}
// Store new split part start position.
startPos = i + 1;
}
}
//else{
lastChar = c;
}
// Add last split part to splitted parts list
if(unquote){
splitParts.Add(UnQuoteString(text.Substring(startPos,text.Length - startPos)));
}
else{
splitParts.Add(text.Substring(startPos,text.Length - startPos));
}
return splitParts.ToArray();
}
#endregion
#region method QuotedIndexOf
/// <summary>
/// Gets first index of specified char. The specified char in quoted string is skipped.
/// Returns -1 if specified char doesn't exist.
/// </summary>
/// <param name="text">Text in what to check.</param>
/// <param name="indexChar">Char what index to get.</param>
/// <returns></returns>
public static int QuotedIndexOf(string text,char indexChar)
{
int retVal = -1;
bool inQuotedString = false; // Holds flag if position is quoted string or not
for(int i=0;i<text.Length;i++){
char c = text[i];
if(c == '\"'){
// Start/end quoted string area
inQuotedString = !inQuotedString;
}
// Current char is what index we want and it isn't in quoted string, return it's index
if(!inQuotedString && c == indexChar){
return i;
}
}
return retVal;
}
#endregion
#region static method SplitString
/// <summary>
/// Splits string into string arrays.
/// </summary>
/// <param name="text">Text to split.</param>
/// <param name="splitChar">Char Char that splits text.</param>
/// <returns></returns>
public static string[] SplitString(string text,char splitChar)
{
ArrayList splitParts = new ArrayList(); // Holds splitted parts
int lastSplitPoint = 0;
int textLength = text.Length;
for(int i=0;i<textLength;i++){
if(text[i] == splitChar){
// Add current currentSplitBuffer value to splitted parts list
splitParts.Add(text.Substring(lastSplitPoint,i - lastSplitPoint));
lastSplitPoint = i + 1;
}
}
// Add last split part to splitted parts list
if(lastSplitPoint <= textLength){
splitParts.Add(text.Substring(lastSplitPoint));
}
string[] retVal = new string[splitParts.Count];
splitParts.CopyTo(retVal,0);
return retVal;
}
#endregion
#region static method IsToken
/// <summary>
/// Gets if specified string is valid "token" value.
/// </summary>
/// <param name="value">String value to check.</param>
/// <returns>Returns true if specified string value is valid "token" value.</returns>
/// <exception cref="ArgumentNullException">Is raised if <b>value</b> is null.</exception>
public static bool IsToken(string value)
{
if(value == null){
throw new ArgumentNullException(value);
}
/* This syntax is taken from rfc 3261, but token must be universal so ... .
token = 1*(alphanum / "-" / "." / "!" / "%" / "*" / "_" / "+" / "`" / "'" / "~" )
alphanum = ALPHA / DIGIT
ALPHA = %x41-5A / %x61-7A ; A-Z / a-z
DIGIT = %x30-39 ; 0-9
*/
char[] tokenChars = new char[]{'-','.','!','%','*','_','+','`','\'','~'};
foreach(char c in value){
// We don't have letter or digit, so we only may have token char.
if(!((c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A) || (c >= 0x30 && c <= 0x39))){
bool validTokenChar = false;
foreach(char tokenChar in tokenChars){
if(c == tokenChar){
validTokenChar = true;
break;
}
}
if(!validTokenChar){
return false;
}
}
}
return true;
}
#endregion
}
}
| 32.9625 | 158 | 0.487751 | [
"MIT"
] | Kooboo/Kooboo | Kooboo.Mail/LumiSoft.Net/TextUtils.cs | 13,185 | C# |
using NUnit.Framework;
namespace Konsole.Tests.WindowTests
{
[TestFixture]
public class BufferTests
{
public class BufferWrittenShould
{
[Test]
public void not_return_lines_not_written_to()
{
var console = new MockConsole(10, 10);
console.WriteLine("1");
console.WriteLine("2");
var lines = console.BufferWritten;
Assert.AreEqual(new[]
{
"1 ",
"2 ",
}, lines);
}
[Test]
public void return_all_lines_in_between_any_lines_written_to()
{
var console = new MockConsole(10, 10);
console.PrintAt(1, 1, "A");
console.PrintAt(3, 3, "B");
var lines = console.BufferWritten;
Assert.AreEqual(new[]
{
" ",
" A ",
" ",
" B ",
}, lines);
}
}
public class BufferShould
{
[Test]
public void return_all_lines()
{
var con = new MockConsole(10, 2);
con.WriteLine("one");
con.WriteLine("two");
Assert.AreEqual(new[] { "one ", "two " }, con.Buffer);
}
[Test]
public void not_be_trimmed()
{
var con = new MockConsole(10, 2);
Assert.AreEqual(new[] { " ", " " }, con.Buffer);
}
}
}
} | 26 | 82 | 0.386946 | [
"Apache-2.0"
] | adamhathcock/konsole | Konsole.Tests/WindowTests/BufferTests.cs | 1,718 | C# |
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace aiof.api.data
{
[ExcludeFromCodeCoverage]
public class FakeDataManager
{
private readonly AiofContext _context;
public FakeDataManager(AiofContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public void UseFakeContext()
{
_context.Users
.AddRange(GetFakeUsers());
_context.UserDependents
.AddRange(GetFakeUserDependents());
_context.UserProfiles
.AddRange(GetFakeUserProfiles());
_context.Addresses
.AddRange(GetFakeAddresses());
_context.AssetTypes
.AddRange(GetFakeAssetTypes());
_context.Assets
.AddRange(GetFakeAssets());
_context.LiabilityTypes
.AddRange(GetFakeLiabilityTypes());
_context.Liabilities
.AddRange(GetFakeLiabilities());
_context.Goals
.AddRange(GetFakeGoals());
_context.GoalsTrip
.AddRange(GetFakeGoalsTrip());
_context.GoalsHome
.AddRange(GetFakeGoalsHome());
_context.GoalsCollege
.AddRange(GetFakeGoalsCollege());
_context.Subscriptions
.AddRange(GetFakeSubscriptions());
_context.Accounts
.AddRange(GetFakeAccounts());
_context.AccountTypes
.AddRange(GetFakeAccountTypes());
_context.EducationLevels
.AddRange(GetFakeEducationLevels());
_context.MaritalStatuses
.AddRange(GetFakeMaritalStatuses());
_context.ResidentialStatuses
.AddRange(GetFakeResidentialStatuses());
_context.Genders
.AddRange(GetFakeGenders());
_context.HouseholdAdults
.AddRange(GetFakeHouseholdAdults());
_context.HouseholdChildren
.AddRange(GetFakeHouseholdChildren());
_context.UsefulDocumentations
.AddRange(GetFakeUsefulDocumentations());
_context.SaveChanges();
}
public IEnumerable<User> GetFakeUsers()
{
return new List<User>
{
new User
{
Id = 1,
PublicKey = Guid.Parse("581f3ce6-cf2a-42a5-828f-157a2bfab763"),
FirstName = "Georgi",
LastName = "Kamacharov",
Email = "gkama@test.com"
},
new User
{
Id = 2,
PublicKey = Guid.Parse("8e17276c-88ac-43bd-a9e8-5fdf5381dbd5"),
FirstName = "Jessie",
LastName = "Brown",
Email = "jessie@test.com"
},
new User
{
Id = 3,
PublicKey = Guid.Parse("7c135230-2889-4cbb-bb0e-ab4237d89367"),
FirstName = "George",
LastName = "Best",
Email = "george.best@auth.com"
}
};
}
public IEnumerable<UserDependent> GetFakeUserDependents()
{
return new List<UserDependent>
{
new UserDependent
{
Id = 1,
FirstName = "Zima",
LastName = "Kamacharov",
Age = 3,
Email = "zima.kamacharov@aiof.com",
AmountOfSupportProvided = 1500M,
UserRelationship = UserRelationship.Child.ToString(),
UserId = 1
},
new UserDependent
{
Id = 2,
FirstName = "Child",
LastName = "Childlastname",
Age = 12,
Email = null,
AmountOfSupportProvided = 12000M,
UserRelationship = UserRelationship.Son.ToString(),
UserId = 2
}
};
}
public IEnumerable<UserProfile> GetFakeUserProfiles()
{
return new List<UserProfile>
{
new UserProfile
{
Id = 1,
UserId = 1,
Gender = "Male",
Occupation = "Sr. Software Engineer",
OccupationIndustry = "IT",
MaritalStatus = MaritalStatuses.Single.ToString(),
EducationLevel = EducationLevels.Bachelors.ToString(),
ResidentialStatus = ResidentialStatuses.Rent.ToString()
}
};
}
public IEnumerable<Address> GetFakeAddresses()
{
return new List<Address>
{
new Address
{
Id = 1,
StreetLine1 = "123 Main Street",
StreetLine2 = null,
City = "Charlotte",
State = "NC",
ZipCode = "28205",
UserProfileId = 1
}
};
}
public IEnumerable<Asset> GetFakeAssets()
{
return new List<Asset>
{
new Asset
{
Id = 1,
PublicKey = Guid.Parse("1ada5134-0290-4ec6-9933-53040906b255"),
Name = "car",
TypeName = "car",
Value = 14762.12M,
UserId = 1
},
new Asset
{
Id = 2,
PublicKey = Guid.Parse("242948e5-6760-43c6-b6ff-21c40de3f9af"),
Name = "house",
TypeName = "house",
Value = 250550M,
UserId = 1
},
new Asset
{
Id = 3,
PublicKey = Guid.Parse("dbf79a48-0504-4bd0-ad00-8cbc3044e585"),
Name = "hardcoded guid",
TypeName = "investment",
Value = 999999M,
UserId = 1
},
new Asset
{
Id = 4,
PublicKey = Guid.Parse("97bedb5b-c49e-484a-8bd0-1d7cb474e217"),
Name = "asset",
TypeName = "cash",
Value = 99M,
UserId = 2
}
};
}
public IEnumerable<Liability> GetFakeLiabilities()
{
return new List<Liability>
{
new Liability
{
Id = 1,
Name = "car loan",
TypeName = "car loan",
Value = 24923.99M,
UserId = 1
}
};
}
public IEnumerable<Goal> GetFakeGoals()
{
return new List<Goal>
{
new Goal
{
Id = 1,
PublicKey = Guid.Parse("446b2d9b-6d63-4021-946c-d9b0fd99d3fe"),
Name = "buy a home by 2021",
Type = GoalType.Generic,
UserId = 1,
Amount = 3000M,
CurrentAmount = 250M,
MonthlyContribution = 200M
}
};
}
public IEnumerable<GoalTrip> GetFakeGoalsTrip()
{
return new List<GoalTrip>
{
new GoalTrip
{
Id = 2,
PublicKey = Guid.Parse("c4f6db70-2345-4a7c-866f-dfdec6a2ec34"),
Name = "trip 1 2021",
Type = GoalType.Trip,
UserId = 1,
Amount = 1550M,
CurrentAmount = 0M,
MonthlyContribution = 200M,
Destination = "Bahamas",
TripType = GoalTripType.Romance,
Duration = 7,
Travelers = 2,
Flight = 750M,
Hotel = 500M,
Car = 0M,
Food = 0M,
Activities = 250M,
Other = 50M
}
};
}
public IEnumerable<GoalHome> GetFakeGoalsHome()
{
return new List<GoalHome>
{
new GoalHome
{
Id = 3,
PublicKey = Guid.Parse("c189fa22-0c6b-41c7-879e-b2b5c6dee80f"),
Name = "Buy a home in 2022",
Type = GoalType.BuyAHome,
UserId = 1,
CurrentAmount = 25000M,
MonthlyContribution = 750M,
HomeValue = 350000M,
MortgageRate = 0.03M,
PercentDownPayment = 0.1M,
AnnualInsurance = 500M,
AnnualPropertyTax = 0.01M,
RecommendedAmount = 40000M
}
};
}
public IEnumerable<GoalCollege> GetFakeGoalsCollege()
{
return new List<GoalCollege>
{
new GoalCollege
{
Id = 5,
PublicKey = Guid.Parse("5b2d9805-16f8-4726-8d7e-6fd08a8e9c98"),
Name = "save for college",
Type = GoalType.SaveForCollege,
UserId = 1,
Amount = 94030M,
CurrentAmount = 12500M,
MonthlyContribution = 350M,
CollegeType = GoalCollegeType.PublicInState,
CostPerYear = 17500M,
StudentAge = 10,
Years = 4,
CollegeName = "Existing college"
}
};
}
public IEnumerable<AssetType> GetFakeAssetTypes()
{
return new List<AssetType>
{
new AssetType
{
Name = "car"
},
new AssetType
{
Name = "house"
},
new AssetType
{
Name = "investment"
},
new AssetType
{
Name = "stock"
},
new AssetType
{
Name = "cash"
},
new AssetType
{
Name = "other"
}
};
}
public IEnumerable<LiabilityType> GetFakeLiabilityTypes()
{
return new List<LiabilityType>
{
new LiabilityType
{
Name = "personal loan"
},
new LiabilityType
{
Name = "car loan"
},
new LiabilityType
{
Name = "student loan"
},
new LiabilityType
{
Name = "credit card"
},
new LiabilityType
{
Name = "mortgage"
},
new LiabilityType
{
Name = "house renovation"
},
new LiabilityType
{
Name = "rv"
},
new LiabilityType
{
Name = "other"
}
};
}
public IEnumerable<Subscription> GetFakeSubscriptions()
{
return new List<Subscription>
{
new Subscription
{
Id = 1,
PublicKey = Guid.Parse("89a0109a-f255-4b2d-b486-76d9efe6347b"),
Name = "Amazon Prime",
Description = "Yearly Amazon Prime subscription",
Amount = 99M,
PaymentLength = 1,
From = "Amazon",
Url = "https://amazon.com/",
UserId = 1
},
new Subscription
{
Id = 2,
PublicKey = Guid.Parse("8297bed8-c13e-4ea0-9e23-88e25ec2829d"),
Name = "Spotify",
Description = "My monthly Spotify subscription",
Amount = 10.99M,
PaymentLength = 12,
From = "Spotify",
Url = "https://spotify.com/",
UserId = 1
},
new Subscription
{
Id = 3,
PublicKey = Guid.Parse("aaa011a0-48d2-4d89-b8fc-3fc22475b564"),
Name = "Generic",
Description = "My generic subscription",
Amount = 15.99M,
PaymentLength = 12,
From = "Generic",
Url = "https://google.com/",
UserId = 1,
IsDeleted = true
},
new Subscription
{
Id = 4,
PublicKey = Guid.Parse("47bd786a-e419-4daa-b18c-7fb7023800f9"),
Name = "Spotify",
Description = "My monthly Spotify subscription",
Amount = 10.99M,
PaymentLength = 12,
From = "Generic",
Url = "https://spotify.com/",
UserId = 2
}
};
}
public IEnumerable<Account> GetFakeAccounts()
{
return new List<Account>
{
new Account
{
Id = 1,
Name = "BfA bank acount",
Description = "Bank Of Amanerica bank acount",
TypeName = "Checking/Savings",
UserId = 1
}
};
}
public IEnumerable<AccountType> GetFakeAccountTypes()
{
return new List<AccountType>
{
new AccountType
{
Name = "401(k)",
Type = AccountTypes.Retirement.ToString()
},
new AccountType
{
Name = "401(a)",
Type = AccountTypes.Retirement.ToString()
},
new AccountType
{
Name = "401(b)",
Type = AccountTypes.Retirement.ToString()
},
new AccountType
{
Name = "457",
Type = AccountTypes.Taxable.ToString()
},
new AccountType
{
Name = "IRA",
Type = AccountTypes.Retirement.ToString()
},
new AccountType
{
Name = "Roth IRA",
Type = AccountTypes.Retirement.ToString()
},
new AccountType
{
Name = "Brokerage",
Type = AccountTypes.Taxable.ToString()
},
new AccountType
{
Name = "Checking/Savings",
Type = AccountTypes.Taxable.ToString()
},
new AccountType
{
Name = "Health Savings Account",
Type = AccountTypes.Taxable.ToString()
},
new AccountType
{
Name = "529 Plan",
Type = AccountTypes.Taxable.ToString()
},
new AccountType
{
Name = "SEP IRA",
Type = AccountTypes.Retirement.ToString()
},
new AccountType
{
Name = "Simple IRA",
Type = AccountTypes.Retirement.ToString()
},
new AccountType
{
Name = "Taxable",
Type = AccountTypes.Taxable.ToString()
},
new AccountType
{
Name = "Tax-Deferred",
Type = AccountTypes.Retirement.ToString()
},
new AccountType
{
Name = "Self Employed Plan",
Type = AccountTypes.Taxable.ToString()
},
new AccountType
{
Name = "UGMA/UTMA",
Type = AccountTypes.Taxable.ToString()
}
};
}
public IEnumerable<EducationLevel> GetFakeEducationLevels()
{
return new List<EducationLevel>
{
new EducationLevel
{
Name = "Some high school or less"
},
new EducationLevel
{
Name = "High school graduate or equivalent (GED)"
},
new EducationLevel
{
Name = "Some college, no degree"
},
new EducationLevel
{
Name = "Doctorate"
}
};
}
public IEnumerable<MaritalStatus> GetFakeMaritalStatuses()
{
return new List<MaritalStatus>
{
new MaritalStatus
{
Name = "Single"
},
new MaritalStatus
{
Name = "Married"
},
new MaritalStatus
{
Name = "Living together"
},
new MaritalStatus
{
Name = "No longer married"
}
};
}
public IEnumerable<ResidentialStatus> GetFakeResidentialStatuses()
{
return new List<ResidentialStatus>
{
new ResidentialStatus
{
Name = "Living with parents / relatives"
},
new ResidentialStatus
{
Name = "Couch surfing"
},
new ResidentialStatus
{
Name = "Renting with friends"
},
new ResidentialStatus
{
Name = "Renting by myself"
},
new ResidentialStatus
{
Name = "Campus housing"
},
new ResidentialStatus
{
Name = "I own a condo"
},
new ResidentialStatus
{
Name = "I own a house"
}
};
}
public IEnumerable<Gender> GetFakeGenders()
{
return new List<Gender>
{
new Gender
{
Name = "Male"
},
new Gender
{
Name = "Female"
},
new Gender
{
Name = "Other"
}
};
}
public IEnumerable<HouseholdAdult> GetFakeHouseholdAdults()
{
return new List<HouseholdAdult>
{
new HouseholdAdult
{
Name = "1 adult",
Value = 1
},
new HouseholdAdult
{
Name = "2 adults",
Value = 2
},
new HouseholdAdult
{
Name = "3 adults",
Value = 3
},
new HouseholdAdult
{
Name = "4 adults",
Value = 4
},
new HouseholdAdult
{
Name = "5 adults",
Value = 5
},
new HouseholdAdult
{
Name = "6 adults",
Value = 6
}
};
}
public IEnumerable<HouseholdChild> GetFakeHouseholdChildren()
{
return new List<HouseholdChild>
{
new HouseholdChild
{
Name = "0 children",
Value = 0
},
new HouseholdChild
{
Name = "1 child",
Value = 1
},
new HouseholdChild
{
Name = "2 children",
Value = 2
},
new HouseholdChild
{
Name = "3 children",
Value = 3
},
new HouseholdChild
{
Name = "4 children",
Value = 4
},
new HouseholdChild
{
Name = "5 children",
Value = 5
},
new HouseholdChild
{
Name = "6 children",
Value = 6
}
};
}
public IEnumerable<UsefulDocumentation> GetFakeUsefulDocumentations()
{
return new List<UsefulDocumentation>
{
new UsefulDocumentation
{
Id = 1,
Page = "finance",
Name = "What is a financial asset?",
Url = "http://google.com",
Category = "financial asset"
},
new UsefulDocumentation
{
Id = 2,
Page = "finance",
Name = "What is a financial liability?",
Url = "http://google.com",
Category = "financial liability"
}
};
}
#region Unit Tests
public IEnumerable<object[]> GetFakeUsersData(
bool id = false,
bool email = false)
{
var fakeUsers = GetFakeUsers();
var toReturn = new List<object[]>();
if (id
& email)
{
foreach (var fakeUser in fakeUsers)
toReturn.Add(new object[]
{
fakeUser.Id,
fakeUser.Email
});
}
else if (id)
{
foreach (var fakeUserId in fakeUsers.Select(x => x.Id))
toReturn.Add(new object[]
{
fakeUserId
});
}
else if (email)
{
foreach (var fakeUserEmail in fakeUsers.Select(x => x.Email))
toReturn.Add(new object[]
{
fakeUserEmail
});
}
return toReturn;
}
public IEnumerable<object[]> GetFakeUserDependentsData(
bool id = false,
bool userId = false)
{
var fakeUserDependents = GetFakeUserDependents();
var toReturn = new List<object[]>();
if (id
&& userId)
{
foreach (var fakeUserDependent in fakeUserDependents)
toReturn.Add(new object[]
{
fakeUserDependent.Id,
fakeUserDependent.UserId
});
}
else if (id)
{
foreach (var fakeUserDependentId in fakeUserDependents.Select(x => x.Id).Distinct())
toReturn.Add(new object[]
{
fakeUserDependentId
});
}
else if (userId)
{
foreach (var fakeUserId in fakeUserDependents.Select(x => x.UserId).Distinct())
toReturn.Add(new object[]
{
fakeUserId
});
}
return toReturn;
}
public IEnumerable<object[]> GetFakeUserProfilesData(
bool userId = false,
bool email = false)
{
var fakeUserProfiles = _context.UserProfiles
.Include(x => x.User)
.AsNoTracking();
var toReturn = new List<object[]>();
if (userId
&& email)
{
foreach (var fakeUser in fakeUserProfiles.Select(x => x.User))
toReturn.Add(new object[]
{
fakeUser.Id,
fakeUser.Email,
});
}
else if (userId)
{
foreach (var fakeUserId in fakeUserProfiles.Select(x => x.UserId))
toReturn.Add(new object[]
{
fakeUserId
});
}
else if (email)
{
foreach (var fakeEmail in fakeUserProfiles.Select(x => x.User.Email))
toReturn.Add(new object[]
{
fakeEmail
});
}
return toReturn;
}
public IEnumerable<object[]> GetFakeAssetsData(
bool id = false,
bool publicKey = false,
bool name = false,
bool typeName = false,
bool value = false,
bool userId = false)
{
var fakeAssets = GetFakeAssets()
.Where(x => !x.IsDeleted)
.ToArray();
var toReturn = new List<object[]>();
if (name
&& typeName
&& value
&& userId)
{
foreach (var fakeAsset in fakeAssets)
{
toReturn.Add(new object[]
{
fakeAsset.Name,
fakeAsset.TypeName,
fakeAsset.Value,
fakeAsset.UserId
});
}
}
else if (id
&& userId)
{
foreach (var fakeAsset in fakeAssets)
{
toReturn.Add(new object[]
{
fakeAsset.Id,
fakeAsset.UserId
});
}
}
else if (typeName
&& userId)
{
foreach (var fakeAsset in fakeAssets)
{
toReturn.Add(new object[]
{
fakeAsset.TypeName,
fakeAsset.UserId
});
}
}
else if (id)
{
foreach (var fakeAssetId in fakeAssets.Select(x => x.Id))
{
toReturn.Add(new object[]
{
fakeAssetId
});
}
}
else if (publicKey)
{
foreach (var fakeAssetPublicKey in fakeAssets.Select(x => x.PublicKey))
{
toReturn.Add(new object[]
{
fakeAssetPublicKey
});
}
}
else if (typeName)
{
foreach (var fakeAssetTypeName in fakeAssets.Select(x => x.TypeName).Distinct())
{
toReturn.Add(new object[]
{
fakeAssetTypeName
});
}
}
else if (userId)
{
foreach (var fakeAssetUserId in fakeAssets.Select(x => x.UserId).Distinct())
{
toReturn.Add(new object[]
{
fakeAssetUserId
});
}
}
return toReturn;
}
public IEnumerable<object[]> GetFakeLiabilitiesData(
bool id = false,
bool userId = false,
bool typeName = false)
{
var fakeLiabilities = GetFakeLiabilities()
.ToArray();
var toReturn = new List<object[]>();
if (id
&& userId)
{
foreach (var fakeLiability in fakeLiabilities.Where(x => !x.IsDeleted))
{
toReturn.Add(new object[]
{
fakeLiability.Id,
fakeLiability.UserId
});
}
}
else if (userId)
{
foreach (var fakeLiabilityUserId in fakeLiabilities.Where(x => !x.IsDeleted).Select(x => x.UserId).Distinct())
{
toReturn.Add(new object[]
{
fakeLiabilityUserId
});
}
}
else if (typeName)
{
foreach (var fakeLiabilityTypeName in fakeLiabilities.Where(x => !x.IsDeleted).Select(x => x.TypeName).Distinct())
{
toReturn.Add(new object[]
{
fakeLiabilityTypeName
});
}
}
return toReturn;
}
public IEnumerable<object[]> GetFakeGoalsData(
bool id = false,
bool userId = false,
bool type = false)
{
var fakeGoals = GetFakeGoals()
.ToArray();
var toReturn = new List<object[]>();
if (id
&& userId)
{
foreach (var fakeGoal in fakeGoals.Where(x => !x.IsDeleted))
{
toReturn.Add(new object[]
{
fakeGoal.Id,
fakeGoal.UserId
});
}
}
else if (userId)
{
foreach (var fakeGoalUserId in fakeGoals.Where(x => !x.IsDeleted).Select(x => x.UserId).Distinct())
{
toReturn.Add(new object[]
{
fakeGoalUserId
});
}
}
else if (type)
{
foreach (var fakeGoalType in fakeGoals.Where(x => !x.IsDeleted).Select(x => x.Type).Distinct())
{
toReturn.Add(new object[]
{
fakeGoalType
});
}
}
return toReturn;
}
public IEnumerable<object[]> GetFakeSubscriptionsData(
bool userId = false,
bool id = false,
bool publicKey = false)
{
var fakeSubscriptions = GetFakeSubscriptions()
.ToArray();
var toReturn = new List<object[]>();
if (userId
&& id)
{
foreach (var fakeSubscription in fakeSubscriptions.Where(x => !x.IsDeleted))
{
toReturn.Add(new object[]
{
fakeSubscription.UserId,
fakeSubscription.Id
});
}
}
else if (userId
&& publicKey)
{
foreach (var fakeSubscription in fakeSubscriptions.Where(x => !x.IsDeleted))
{
toReturn.Add(new object[]
{
fakeSubscription.UserId,
fakeSubscription.PublicKey
});
}
}
else if (id)
{
foreach (var fakeSubscriptionId in fakeSubscriptions.Where(x => !x.IsDeleted).Select(x => x.Id))
{
toReturn.Add(new object[]
{
fakeSubscriptionId
});
}
}
return toReturn;
}
public IEnumerable<object[]> GetFakeAccountsData(
bool userId = false,
bool id = false,
bool publicKey = false)
{
var fakeAccounts = GetFakeAccounts()
.ToArray();
var toReturn = new List<object[]>();
if (userId
&& id)
{
foreach (var fakefakeAccount in fakeAccounts.Where(x => !x.IsDeleted))
{
toReturn.Add(new object[]
{
fakefakeAccount.UserId,
fakefakeAccount.Id
});
}
}
else if (userId
&& publicKey)
{
foreach (var fakeAccount in fakeAccounts.Where(x => !x.IsDeleted))
{
toReturn.Add(new object[]
{
fakeAccount.UserId,
fakeAccount.PublicKey
});
}
}
else if (id)
{
foreach (var fakeAccountId in fakeAccounts.Where(x => !x.IsDeleted).Select(x => x.Id))
{
toReturn.Add(new object[]
{
fakeAccountId
});
}
}
else if (userId)
{
foreach (var fakeAccountUserId in fakeAccounts.Where(x => !x.IsDeleted).Select(x => x.UserId))
{
toReturn.Add(new object[]
{
fakeAccountUserId
});
}
}
return toReturn;
}
public IEnumerable<object[]> GetFakeUsefulDocumentationsData(
bool page = false,
bool category = false)
{
var fakeUsefulDocumentations = GetFakeUsefulDocumentations()
.ToArray();
var toReturn = new List<object[]>();
if (page)
{
foreach (var fakeUsefulDocumentationPage in fakeUsefulDocumentations.Select(x => x.Page).Distinct())
{
toReturn.Add(new object[]
{
fakeUsefulDocumentationPage
});
}
}
else if (category)
{
foreach (var fakeUsefulDocumentationCategory in fakeUsefulDocumentations.Select(x => x.Category).Distinct())
{
toReturn.Add(new object[]
{
fakeUsefulDocumentationCategory
});
}
}
return toReturn;
}
public IEnumerable<object[]> GetFakeAmountCurrentAmountMonthlyContribution()
{
return new List<object[]>
{
new object[] { 350M, 0M, 20M },
new object[] { 1000M, 250M, 200M },
new object[] { 3750M, 500M, 500M }
};
}
public IEnumerable<object[]> GetFakeAmountCurrentAmountMonthlyContributionNegatives()
{
return new List<object[]>
{
new object[] { null, 0M, 20M },
new object[] { 1000M, 250M, null },
new object[] { null, null, 20M },
new object[] { 1000M, null, null },
};
}
#endregion
}
}
| 30.534903 | 130 | 0.373721 | [
"MIT"
] | kamacharovs/aiof-api | aiof.api.data/FakeDataManager.cs | 37,621 | C# |
using ClientCore;
using ClientCore.Statistics;
using ClientGUI;
using DTAClient.Domain.Multiplayer;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Rampastring.Tools;
using Rampastring.XNAUI;
using Rampastring.XNAUI.XNAControls;
using System;
using System.Collections.Generic;
using System.Linq;
namespace DTAClient.DXGUI.Generic
{
public class StatisticsWindow : XNAWindow
{
public StatisticsWindow(WindowManager windowManager) : base(windowManager) { }
private XNAPanel panelGameStatistics;
private XNAPanel panelTotalStatistics;
private XNAClientDropDown cmbGameModeFilter;
private XNAClientDropDown cmbGameClassFilter;
private XNAClientCheckBox chkIncludeSpectatedGames;
private XNAClientTabControl tabControl;
// Controls for game statistics
private XNAMultiColumnListBox lbGameList;
private XNAMultiColumnListBox lbGameStatistics;
private Texture2D[] sideTextures;
// *****************************
private const int TOTAL_STATS_LOCATION_X1 = 40;
private const int TOTAL_STATS_VALUE_LOCATION_X1 = 240;
private const int TOTAL_STATS_LOCATION_X2 = 380;
private const int TOTAL_STATS_VALUE_LOCATION_X2 = 580;
private const int TOTAL_STATS_Y_INCREASE = 45;
private const int TOTAL_STATS_FIRST_ITEM_Y = 20;
// Controls for total statistics
private XNALabel lblGamesStartedValue;
private XNALabel lblGamesFinishedValue;
private XNALabel lblWinsValue;
private XNALabel lblLossesValue;
private XNALabel lblWinLossRatioValue;
private XNALabel lblAverageGameLengthValue;
private XNALabel lblTotalTimePlayedValue;
private XNALabel lblAverageEnemyCountValue;
private XNALabel lblAverageAllyCountValue;
private XNALabel lblTotalKillsValue;
private XNALabel lblKillsPerGameValue;
private XNALabel lblTotalLossesValue;
private XNALabel lblLossesPerGameValue;
private XNALabel lblKillLossRatioValue;
private XNALabel lblTotalScoreValue;
private XNALabel lblAverageEconomyValue;
private XNALabel lblFavouriteSideValue;
private XNALabel lblAverageAILevelValue;
// *****************************
private StatisticsManager sm;
private List<int> listedGameIndexes = new List<int>();
private string[] sides;
private List<MultiplayerColor> mpColors;
public override void Initialize()
{
sm = StatisticsManager.Instance;
string strLblEconomy = "ECONOMY";
string strLblAvgEconomy = "Average economy:";
if (ClientConfiguration.Instance.UseBuiltStatistic)
{
strLblEconomy = "BUILT";
strLblAvgEconomy = "Avg. number of objects built:";
}
Name = "StatisticsWindow";
BackgroundTexture = AssetLoader.LoadTexture("scoreviewerbg.png");
ClientRectangle = new Rectangle(0, 0, 700, 521);
tabControl = new XNAClientTabControl(WindowManager);
tabControl.Name = "tabControl";
tabControl.ClientRectangle = new Rectangle(12, 10, 0, 0);
tabControl.SoundOnClick = AssetLoader.LoadSound("button.wav");
tabControl.FontIndex = 1;
tabControl.AddTab("Game Statistics", 133);
tabControl.AddTab("Total Statistics", 133);
tabControl.SelectedIndexChanged += TabControl_SelectedIndexChanged;
XNALabel lblFilter = new XNALabel(WindowManager);
lblFilter.Name = "lblFilter";
lblFilter.FontIndex = 1;
lblFilter.Text = "FILTER:";
lblFilter.ClientRectangle = new Rectangle(527, 12, 0, 0);
cmbGameClassFilter = new XNAClientDropDown(WindowManager);
cmbGameClassFilter.ClientRectangle = new Rectangle(585, 11, 105, 21);
cmbGameClassFilter.Name = "cmbGameClassFilter";
cmbGameClassFilter.AddItem("All games");
cmbGameClassFilter.AddItem("Online games");
cmbGameClassFilter.AddItem("Online PvP");
cmbGameClassFilter.AddItem("Online Co-Op");
cmbGameClassFilter.AddItem("Skirmish");
cmbGameClassFilter.SelectedIndex = 0;
cmbGameClassFilter.SelectedIndexChanged += CmbGameClassFilter_SelectedIndexChanged;
XNALabel lblGameMode = new XNALabel(WindowManager);
lblGameMode.Name = "lblGameMode";
lblGameMode.FontIndex = 1;
lblGameMode.Text = "GAME MODE:";
lblGameMode.ClientRectangle = new Rectangle(294, 12, 0, 0);
cmbGameModeFilter = new XNAClientDropDown(WindowManager);
cmbGameModeFilter.Name = "cmbGameModeFilter";
cmbGameModeFilter.ClientRectangle = new Rectangle(381, 11, 114, 21);
cmbGameModeFilter.SelectedIndexChanged += CmbGameModeFilter_SelectedIndexChanged;
var btnReturnToMenu = new XNAClientButton(WindowManager);
btnReturnToMenu.Name = "btnReturnToMenu";
btnReturnToMenu.ClientRectangle = new Rectangle(270, 486, 160, 23);
btnReturnToMenu.Text = "Return to Main Menu";
btnReturnToMenu.LeftClick += BtnReturnToMenu_LeftClick;
var btnClearStatistics = new XNAClientButton(WindowManager);
btnClearStatistics.Name = "btnClearStatistics";
btnClearStatistics.ClientRectangle = new Rectangle(12, 486, 160, 23);
btnClearStatistics.Text = "Clear Statistics";
btnClearStatistics.LeftClick += BtnClearStatistics_LeftClick;
btnClearStatistics.Visible = false;
chkIncludeSpectatedGames = new XNAClientCheckBox(WindowManager);
AddChild(chkIncludeSpectatedGames);
chkIncludeSpectatedGames.Name = "chkIncludeSpectatedGames";
chkIncludeSpectatedGames.Text = "Include spectated games";
chkIncludeSpectatedGames.Checked = true;
chkIncludeSpectatedGames.ClientRectangle = new Rectangle(
ClientRectangle.Width - chkIncludeSpectatedGames.ClientRectangle.Width - 12,
cmbGameModeFilter.ClientRectangle.Bottom + 3,
chkIncludeSpectatedGames.ClientRectangle.Width,
chkIncludeSpectatedGames.ClientRectangle.Height);
chkIncludeSpectatedGames.CheckedChanged += ChkIncludeSpectatedGames_CheckedChanged;
#region Match statistics
panelGameStatistics = new XNAPanel(WindowManager);
panelGameStatistics.Name = "panelGameStatistics";
panelGameStatistics.BackgroundTexture = AssetLoader.LoadTexture("scoreviewerpanelbg.png");
panelGameStatistics.ClientRectangle = new Rectangle(10, 55, 680, 425);
AddChild(panelGameStatistics);
XNALabel lblMatches = new XNALabel(WindowManager);
lblMatches.Text = "GAMES:";
lblMatches.FontIndex = 1;
lblMatches.ClientRectangle = new Rectangle(4, 2, 0, 0);
lbGameList = new XNAMultiColumnListBox(WindowManager);
lbGameList.Name = "lbGameList";
lbGameList.BackgroundTexture = AssetLoader.CreateTexture(new Color(0, 0, 0, 128), 1, 1);
lbGameList.DrawMode = PanelBackgroundImageDrawMode.STRETCHED;
lbGameList.AddColumn("DATE / TIME", 130);
lbGameList.AddColumn("MAP", 200);
lbGameList.AddColumn("GAME MODE", 130);
lbGameList.AddColumn("FPS", 50);
lbGameList.AddColumn("DURATION", 76);
lbGameList.AddColumn("COMPLETED", 90);
lbGameList.ClientRectangle = new Rectangle(2, 25, 676, 250);
lbGameList.SelectedIndexChanged += LbGameList_SelectedIndexChanged;
lbGameList.AllowKeyboardInput = true;
lbGameStatistics = new XNAMultiColumnListBox(WindowManager);
lbGameStatistics.Name = "lbGameStatistics";
lbGameStatistics.BackgroundTexture = AssetLoader.CreateTexture(new Color(0, 0, 0, 128), 1, 1);
lbGameStatistics.DrawMode = PanelBackgroundImageDrawMode.STRETCHED;
lbGameStatistics.AddColumn("NAME", 130);
lbGameStatistics.AddColumn("KILLS", 78);
lbGameStatistics.AddColumn("LOSSES", 78);
lbGameStatistics.AddColumn(strLblEconomy, 80);
lbGameStatistics.AddColumn("SCORE", 100);
lbGameStatistics.AddColumn("WON", 50);
lbGameStatistics.AddColumn("SIDE", 100);
lbGameStatistics.AddColumn("TEAM", 60);
lbGameStatistics.ClientRectangle = new Rectangle(2, 280, 676, 143);
panelGameStatistics.AddChild(lblMatches);
panelGameStatistics.AddChild(lbGameList);
panelGameStatistics.AddChild(lbGameStatistics);
#endregion
#region Total statistics
panelTotalStatistics = new XNAPanel(WindowManager);
panelTotalStatistics.Name = "panelTotalStatistics";
panelTotalStatistics.BackgroundTexture = AssetLoader.LoadTexture("scoreviewerpanelbg.png");
panelTotalStatistics.ClientRectangle = new Rectangle(10, 55, 680, 425);
AddChild(panelTotalStatistics);
panelTotalStatistics.Visible = false;
panelTotalStatistics.Enabled = false;
int locationY = TOTAL_STATS_FIRST_ITEM_Y;
AddTotalStatisticsLabel("lblGamesStarted", "Games started:", new Point(TOTAL_STATS_LOCATION_X1, locationY));
lblGamesStartedValue = new XNALabel(WindowManager);
lblGamesStartedValue.Name = "lblGamesStartedValue";
lblGamesStartedValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X1, locationY, 0, 0);
lblGamesStartedValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblGamesFinished", "Games finished:", new Point(TOTAL_STATS_LOCATION_X1, locationY));
lblGamesFinishedValue = new XNALabel(WindowManager);
lblGamesFinishedValue.Name = "lblGamesFinishedValue";
lblGamesFinishedValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X1, locationY, 0, 0);
lblGamesFinishedValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblWins", "Wins:", new Point(TOTAL_STATS_LOCATION_X1, locationY));
lblWinsValue = new XNALabel(WindowManager);
lblWinsValue.Name = "lblWinsValue";
lblWinsValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X1, locationY, 0, 0);
lblWinsValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblLosses", "Losses:", new Point(TOTAL_STATS_LOCATION_X1, locationY));
lblLossesValue = new XNALabel(WindowManager);
lblLossesValue.Name = "lblLossesValue";
lblLossesValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X1, locationY, 0, 0);
lblLossesValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblWinLossRatio", "Win / Loss ratio:", new Point(TOTAL_STATS_LOCATION_X1, locationY));
lblWinLossRatioValue = new XNALabel(WindowManager);
lblWinLossRatioValue.Name = "lblWinLossRatioValue";
lblWinLossRatioValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X1, locationY, 0, 0);
lblWinLossRatioValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblAverageGameLength", "Average game length:", new Point(TOTAL_STATS_LOCATION_X1, locationY));
lblAverageGameLengthValue = new XNALabel(WindowManager);
lblAverageGameLengthValue.Name = "lblAverageGameLengthValue";
lblAverageGameLengthValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X1, locationY, 0, 0);
lblAverageGameLengthValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblTotalTimePlayed", "Total time played:", new Point(TOTAL_STATS_LOCATION_X1, locationY));
lblTotalTimePlayedValue = new XNALabel(WindowManager);
lblTotalTimePlayedValue.Name = "lblTotalTimePlayedValue";
lblTotalTimePlayedValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X1, locationY, 0, 0);
lblTotalTimePlayedValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblAverageEnemyCount", "Average number of enemies:", new Point(TOTAL_STATS_LOCATION_X1, locationY));
lblAverageEnemyCountValue = new XNALabel(WindowManager);
lblAverageEnemyCountValue.Name = "lblAverageEnemyCountValue";
lblAverageEnemyCountValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X1, locationY, 0, 0);
lblAverageEnemyCountValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblAverageAllyCount", "Average number of allies:", new Point(TOTAL_STATS_LOCATION_X1, locationY));
lblAverageAllyCountValue = new XNALabel(WindowManager);
lblAverageAllyCountValue.Name = "lblAverageAllyCountValue";
lblAverageAllyCountValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X1, locationY, 0, 0);
lblAverageAllyCountValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
// SECOND COLUMN
locationY = TOTAL_STATS_FIRST_ITEM_Y;
AddTotalStatisticsLabel("lblTotalKills", "Total kills:", new Point(TOTAL_STATS_LOCATION_X2, locationY));
lblTotalKillsValue = new XNALabel(WindowManager);
lblTotalKillsValue.Name = "lblTotalKillsValue";
lblTotalKillsValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X2, locationY, 0, 0);
lblTotalKillsValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblKillsPerGame", "Kills / game:", new Point(TOTAL_STATS_LOCATION_X2, locationY));
lblKillsPerGameValue = new XNALabel(WindowManager);
lblKillsPerGameValue.Name = "lblKillsPerGameValue";
lblKillsPerGameValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X2, locationY, 0, 0);
lblKillsPerGameValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblTotalLosses", "Total losses:", new Point(TOTAL_STATS_LOCATION_X2, locationY));
lblTotalLossesValue = new XNALabel(WindowManager);
lblTotalLossesValue.Name = "lblTotalLossesValue";
lblTotalLossesValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X2, locationY, 0, 0);
lblTotalLossesValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblLossesPerGame", "Losses / game:", new Point(TOTAL_STATS_LOCATION_X2, locationY));
lblLossesPerGameValue = new XNALabel(WindowManager);
lblLossesPerGameValue.Name = "lblLossesPerGameValue";
lblLossesPerGameValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X2, locationY, 0, 0);
lblLossesPerGameValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblKillLossRatio", "Kill / loss ratio:", new Point(TOTAL_STATS_LOCATION_X2, locationY));
lblKillLossRatioValue = new XNALabel(WindowManager);
lblKillLossRatioValue.Name = "lblKillLossRatioValue";
lblKillLossRatioValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X2, locationY, 0, 0);
lblKillLossRatioValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblTotalScore", "Total score:", new Point(TOTAL_STATS_LOCATION_X2, locationY));
lblTotalScoreValue = new XNALabel(WindowManager);
lblTotalScoreValue.Name = "lblTotalScoreValue";
lblTotalScoreValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X2, locationY, 0, 0);
lblTotalScoreValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblAverageEconomy", strLblAvgEconomy, new Point(TOTAL_STATS_LOCATION_X2, locationY));
lblAverageEconomyValue = new XNALabel(WindowManager);
lblAverageEconomyValue.Name = "lblAverageEconomyValue";
lblAverageEconomyValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X2, locationY, 0, 0);
lblAverageEconomyValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblFavouriteSide", "Favourite side:", new Point(TOTAL_STATS_LOCATION_X2, locationY));
lblFavouriteSideValue = new XNALabel(WindowManager);
lblFavouriteSideValue.Name = "lblFavouriteSideValue";
lblFavouriteSideValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X2, locationY, 0, 0);
lblFavouriteSideValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
AddTotalStatisticsLabel("lblAverageAILevel", "Average AI level:", new Point(TOTAL_STATS_LOCATION_X2, locationY));
lblAverageAILevelValue = new XNALabel(WindowManager);
lblAverageAILevelValue.Name = "lblAverageAILevelValue";
lblAverageAILevelValue.ClientRectangle = new Rectangle(TOTAL_STATS_VALUE_LOCATION_X2, locationY, 0, 0);
lblAverageAILevelValue.RemapColor = UISettings.AltColor;
locationY += TOTAL_STATS_Y_INCREASE;
panelTotalStatistics.AddChild(lblGamesStartedValue);
panelTotalStatistics.AddChild(lblGamesFinishedValue);
panelTotalStatistics.AddChild(lblWinsValue);
panelTotalStatistics.AddChild(lblLossesValue);
panelTotalStatistics.AddChild(lblWinLossRatioValue);
panelTotalStatistics.AddChild(lblAverageGameLengthValue);
panelTotalStatistics.AddChild(lblTotalTimePlayedValue);
panelTotalStatistics.AddChild(lblAverageEnemyCountValue);
panelTotalStatistics.AddChild(lblAverageAllyCountValue);
panelTotalStatistics.AddChild(lblTotalKillsValue);
panelTotalStatistics.AddChild(lblKillsPerGameValue);
panelTotalStatistics.AddChild(lblTotalLossesValue);
panelTotalStatistics.AddChild(lblLossesPerGameValue);
panelTotalStatistics.AddChild(lblKillLossRatioValue);
panelTotalStatistics.AddChild(lblTotalScoreValue);
panelTotalStatistics.AddChild(lblAverageEconomyValue);
panelTotalStatistics.AddChild(lblFavouriteSideValue);
panelTotalStatistics.AddChild(lblAverageAILevelValue);
#endregion
AddChild(tabControl);
AddChild(lblFilter);
AddChild(cmbGameClassFilter);
AddChild(lblGameMode);
AddChild(cmbGameModeFilter);
AddChild(btnReturnToMenu);
AddChild(btnClearStatistics);
base.Initialize();
CenterOnParent();
sides = ClientConfiguration.Instance.GetSides().Split(',');
sideTextures = new Texture2D[sides.Length + 1];
for (int i = 0; i < sides.Length; i++)
sideTextures[i] = AssetLoader.LoadTexture(sides[i] + "icon.png");
sideTextures[sides.Length] = AssetLoader.LoadTexture("spectatoricon.png");
mpColors = MultiplayerColor.LoadColors();
ReadStatistics();
ListGameModes();
ListGames();
StatisticsManager.Instance.GameAdded += Instance_GameAdded;
}
private void Instance_GameAdded(object sender, EventArgs e)
{
ListGames();
}
private void ChkIncludeSpectatedGames_CheckedChanged(object sender, EventArgs e)
{
ListGames();
}
private void AddTotalStatisticsLabel(string name, string text, Point location)
{
XNALabel label = new XNALabel(WindowManager);
label.Name = name;
label.Text = text;
label.ClientRectangle = new Rectangle(location.X, location.Y, 0, 0);
panelTotalStatistics.AddChild(label);
}
private void TabControl_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl.SelectedTab == 1)
{
panelGameStatistics.Visible = false;
panelGameStatistics.Enabled = false;
panelTotalStatistics.Visible = true;
panelTotalStatistics.Enabled = true;
}
else
{
panelGameStatistics.Visible = true;
panelGameStatistics.Enabled = true;
panelTotalStatistics.Visible = false;
panelTotalStatistics.Enabled = false;
}
}
private void CmbGameClassFilter_SelectedIndexChanged(object sender, EventArgs e)
{
ListGames();
}
private void CmbGameModeFilter_SelectedIndexChanged(object sender, EventArgs e)
{
ListGames();
}
private void LbGameList_SelectedIndexChanged(object sender, EventArgs e)
{
lbGameStatistics.ClearItems();
if (lbGameList.SelectedIndex == -1)
return;
MatchStatistics ms = sm.GetMatchByIndex(listedGameIndexes[lbGameList.SelectedIndex]);
List<PlayerStatistics> players = new List<PlayerStatistics>();
for (int i = 0; i < ms.GetPlayerCount(); i++)
{
players.Add(ms.GetPlayer(i));
}
players = players.OrderBy(p => p.Score).Reverse().ToList();
Color textColor = UISettings.AltColor;
for (int i = 0; i < ms.GetPlayerCount(); i++)
{
PlayerStatistics ps = players[i];
//List<string> items = new List<string>();
List<XNAListBoxItem> items = new List<XNAListBoxItem>();
if (ps.Color > -1 && ps.Color < mpColors.Count)
textColor = mpColors[ps.Color].XnaColor;
if (ps.IsAI)
{
items.Add(new XNAListBoxItem(AILevelToString(ps.AILevel), textColor));
}
else
items.Add(new XNAListBoxItem(ps.Name, textColor));
if (ps.WasSpectator)
{
// Player was a spectator
items.Add(new XNAListBoxItem("-", textColor));
items.Add(new XNAListBoxItem("-", textColor));
items.Add(new XNAListBoxItem("-", textColor));
items.Add(new XNAListBoxItem("-", textColor));
items.Add(new XNAListBoxItem("-", textColor));
XNAListBoxItem spectatorItem = new XNAListBoxItem();
spectatorItem.Text = "Spectator";
spectatorItem.TextColor = textColor;
spectatorItem.Texture = sideTextures[sideTextures.Length - 1];
items.Add(spectatorItem);
items.Add(new XNAListBoxItem("-", textColor));
}
else
{
if (!ms.SawCompletion)
{
// The game wasn't completed - we don't know the stats
items.Add(new XNAListBoxItem("-", textColor));
items.Add(new XNAListBoxItem("-", textColor));
items.Add(new XNAListBoxItem("-", textColor));
items.Add(new XNAListBoxItem("-", textColor));
items.Add(new XNAListBoxItem("-", textColor));
}
else
{
// The game was completed and the player was actually playing
items.Add(new XNAListBoxItem(ps.Kills.ToString(), textColor));
items.Add(new XNAListBoxItem(ps.Losses.ToString(), textColor));
items.Add(new XNAListBoxItem(ps.Economy.ToString(), textColor));
items.Add(new XNAListBoxItem(ps.Score.ToString(), textColor));
items.Add(new XNAListBoxItem(
Conversions.BooleanToString(ps.Won, BooleanStringStyle.YESNO), textColor));
}
if (ps.Side == 0 || ps.Side > sides.Length)
items.Add(new XNAListBoxItem("Unknown", textColor));
else
{
XNAListBoxItem sideItem = new XNAListBoxItem();
sideItem.Text = sides[ps.Side - 1];
sideItem.TextColor = textColor;
sideItem.Texture = sideTextures[ps.Side - 1];
items.Add(sideItem);
}
items.Add(new XNAListBoxItem(TeamIndexToString(ps.Team), textColor));
}
if (!ps.IsLocalPlayer)
{
lbGameStatistics.AddItem(items);
items.ForEach(item => item.Selectable = false);
}
else
{
lbGameStatistics.AddItem(items);
lbGameStatistics.SelectedIndex = i;
}
}
}
private string TeamIndexToString(int teamIndex)
{
switch (teamIndex)
{
case 1:
return "A";
case 2:
return "B";
case 3:
return "C";
case 4:
return "D";
default:
return "-";
}
}
private string AILevelToString(int aiLevel)
{
switch (aiLevel)
{
case 2:
return "Hard AI";
case 1:
return "Medium AI";
case 0:
default:
return "Easy AI";
}
}
#region Statistics reading / game listing code
void ReadStatistics()
{
StatisticsManager sm = StatisticsManager.Instance;
sm.ReadStatistics(ProgramConstants.GamePath);
}
void ListGameModes()
{
int gameCount = sm.GetMatchCount();
List<string> gameModes = new List<string>();
cmbGameModeFilter.Items.Clear();
cmbGameModeFilter.AddItem("All");
for (int i = 0; i < gameCount; i++)
{
MatchStatistics ms = sm.GetMatchByIndex(i);
if (!gameModes.Contains(ms.GameMode))
gameModes.Add(ms.GameMode);
}
gameModes.Sort();
foreach (string gm in gameModes)
cmbGameModeFilter.AddItem(gm);
cmbGameModeFilter.SelectedIndex = 0;
}
void ListGames()
{
lbGameList.SelectedIndex = -1;
lbGameList.SetTopIndex(0);
lbGameStatistics.ClearItems();
lbGameList.ClearItems();
listedGameIndexes.Clear();
switch (cmbGameClassFilter.SelectedIndex)
{
case 0:
ListAllGames();
break;
case 1:
ListOnlineGames();
break;
case 2:
ListPvPGames();
break;
case 3:
ListCoOpGames();
break;
case 4:
ListSkirmishGames();
break;
}
listedGameIndexes.Reverse();
SetTotalStatistics();
foreach (int gameIndex in listedGameIndexes)
{
MatchStatistics ms = sm.GetMatchByIndex(gameIndex);
string dateTime = ms.DateAndTime.ToShortDateString() + " " + ms.DateAndTime.ToShortTimeString();
List<string> info = new List<string>();
info.Add(Renderer.GetSafeString(dateTime, lbGameList.FontIndex));
info.Add(ms.MapName);
info.Add(ms.GameMode);
if (ms.AverageFPS == 0)
info.Add("-");
else
info.Add(ms.AverageFPS.ToString());
info.Add(Renderer.GetSafeString(TimeSpan.FromSeconds(ms.LengthInSeconds).ToString(), lbGameList.FontIndex));
info.Add(Conversions.BooleanToString(ms.SawCompletion, BooleanStringStyle.YESNO));
lbGameList.AddItem(info, true);
}
}
private void ListAllGames()
{
int gameCount = sm.GetMatchCount();
for (int i = 0; i < gameCount; i++)
{
ListGameIndexIfPrerequisitesMet(i);
}
}
private void ListOnlineGames()
{
int gameCount = sm.GetMatchCount();
for (int i = 0; i < gameCount; i++)
{
MatchStatistics ms = sm.GetMatchByIndex(i);
int pCount = ms.GetPlayerCount();
int hpCount = 0;
for (int j = 0; j < pCount; j++)
{
PlayerStatistics ps = ms.GetPlayer(j);
if (!ps.IsAI)
{
hpCount++;
if (hpCount > 1)
{
ListGameIndexIfPrerequisitesMet(i);
break;
}
}
}
}
}
private void ListPvPGames()
{
int gameCount = sm.GetMatchCount();
for (int i = 0; i < gameCount; i++)
{
MatchStatistics ms = sm.GetMatchByIndex(i);
int pCount = ms.GetPlayerCount();
int pTeam = -1;
for (int j = 0; j < pCount; j++)
{
PlayerStatistics ps = ms.GetPlayer(j);
if (!ps.IsAI && !ps.WasSpectator)
{
// If we find a single player on a different team than another player,
// we'll count the game as a PvP game
if (pTeam > -1 && (ps.Team != pTeam || ps.Team == 0))
{
ListGameIndexIfPrerequisitesMet(i);
break;
}
pTeam = ps.Team;
}
}
}
}
private void ListCoOpGames()
{
int gameCount = sm.GetMatchCount();
for (int i = 0; i < gameCount; i++)
{
MatchStatistics ms = sm.GetMatchByIndex(i);
int pCount = ms.GetPlayerCount();
int hpCount = 0;
int pTeam = -1;
bool add = true;
for (int j = 0; j < pCount; j++)
{
PlayerStatistics ps = ms.GetPlayer(j);
if (!ps.IsAI && !ps.WasSpectator)
{
hpCount++;
if (pTeam > -1 && (ps.Team != pTeam || ps.Team == 0))
{
add = false;
break;
}
pTeam = ps.Team;
}
}
if (add && hpCount > 1)
{
ListGameIndexIfPrerequisitesMet(i);
}
}
}
private void ListSkirmishGames()
{
int gameCount = sm.GetMatchCount();
for (int i = 0; i < gameCount; i++)
{
MatchStatistics ms = sm.GetMatchByIndex(i);
int pCount = ms.GetPlayerCount();
int hpCount = 0;
bool add = true;
foreach (PlayerStatistics ps in ms.Players)
{
if (!ps.IsAI)
{
hpCount++;
if (hpCount > 1)
{
add = false;
break;
}
}
}
if (add)
{
ListGameIndexIfPrerequisitesMet(i);
}
}
}
private void ListGameIndexIfPrerequisitesMet(int gameIndex)
{
MatchStatistics ms = sm.GetMatchByIndex(gameIndex);
if (cmbGameModeFilter.SelectedIndex != 0)
{
string gameMode = cmbGameModeFilter.Items[cmbGameModeFilter.SelectedIndex].Text;
if (ms.GameMode != gameMode)
return;
}
PlayerStatistics ps = ms.Players.Find(p => p.IsLocalPlayer);
if (ps != null && !chkIncludeSpectatedGames.Checked)
{
if (ps.WasSpectator)
return;
}
listedGameIndexes.Add(gameIndex);
}
/// <summary>
/// Adjusts the labels on the "Total statistics" tab.
/// </summary>
private void SetTotalStatistics()
{
int gamesStarted = 0;
int gamesFinished = 0;
int gamesPlayed = 0;
int wins = 0;
int gameLosses = 0;
TimeSpan timePlayed = TimeSpan.Zero;
int numEnemies = 0;
int numAllies = 0;
int totalKills = 0;
int totalLosses = 0;
int totalScore = 0;
int totalEconomy = 0;
int[] sideGameCounts = new int[sides.Length];
int numEasyAIs = 0;
int numMediumAIs = 0;
int numHardAIs = 0;
foreach (int gameIndex in listedGameIndexes)
{
MatchStatistics ms = sm.GetMatchByIndex(gameIndex);
gamesStarted++;
if (ms.SawCompletion)
gamesFinished++;
timePlayed += TimeSpan.FromSeconds(ms.LengthInSeconds);
PlayerStatistics localPlayer = FindLocalPlayer(ms);
if (!localPlayer.WasSpectator)
{
totalKills += localPlayer.Kills;
totalLosses += localPlayer.Losses;
totalScore += localPlayer.Score;
totalEconomy += localPlayer.Economy;
if (localPlayer.Side > 0 && localPlayer.Side <= sides.Length)
sideGameCounts[localPlayer.Side - 1]++;
if (!ms.SawCompletion)
continue;
if (localPlayer.Won)
wins++;
else
gameLosses++;
gamesPlayed++;
for (int i = 0; i < ms.GetPlayerCount(); i++)
{
PlayerStatistics ps = ms.GetPlayer(i);
if (!ps.WasSpectator && (!ps.IsLocalPlayer || ps.IsAI))
{
if (ps.Team == 0 || localPlayer.Team != ps.Team)
numEnemies++;
else
numAllies++;
if (ps.IsAI)
{
if (ps.AILevel == 0)
numEasyAIs++;
else if (ps.AILevel == 1)
numMediumAIs++;
else
numHardAIs++;
}
}
}
}
}
lblGamesStartedValue.Text = gamesStarted.ToString();
lblGamesFinishedValue.Text = gamesFinished.ToString();
lblWinsValue.Text = wins.ToString();
lblLossesValue.Text = gameLosses.ToString();
if (gameLosses > 0)
{
lblWinLossRatioValue.Text = Math.Round(wins / (double)gameLosses, 2).ToString();
}
else
lblWinLossRatioValue.Text = "-";
if (gamesStarted > 0)
{
lblAverageGameLengthValue.Text = TimeSpan.FromSeconds((int)timePlayed.TotalSeconds / gamesStarted).ToString();
}
else
lblAverageGameLengthValue.Text = "-";
if (gamesPlayed > 0)
{
lblAverageEnemyCountValue.Text = Math.Round(numEnemies / (double)gamesPlayed, 2).ToString();
lblAverageAllyCountValue.Text = Math.Round(numAllies / (double)gamesPlayed, 2).ToString();
lblKillsPerGameValue.Text = (totalKills / gamesPlayed).ToString();
lblLossesPerGameValue.Text = (totalLosses / gamesPlayed).ToString();
lblAverageEconomyValue.Text = (totalEconomy / gamesPlayed).ToString();
}
else
{
lblAverageEnemyCountValue.Text = "-";
lblAverageAllyCountValue.Text = "-";
lblKillsPerGameValue.Text = "-";
lblLossesPerGameValue.Text = "-";
lblAverageEconomyValue.Text = "-";
}
if (totalLosses > 0)
{
lblKillLossRatioValue.Text = Math.Round(totalKills / (double)totalLosses, 2).ToString();
}
else
lblKillLossRatioValue.Text = "-";
lblTotalTimePlayedValue.Text = timePlayed.ToString();
lblTotalKillsValue.Text = totalKills.ToString();
lblTotalLossesValue.Text = totalLosses.ToString();
lblTotalScoreValue.Text = totalScore.ToString();
lblFavouriteSideValue.Text = sides[GetHighestIndex(sideGameCounts)];
if (numEasyAIs >= numMediumAIs && numEasyAIs >= numHardAIs)
lblAverageAILevelValue.Text = "Easy";
else if (numMediumAIs >= numEasyAIs && numMediumAIs >= numHardAIs)
lblAverageAILevelValue.Text = "Medium";
else
lblAverageAILevelValue.Text = "Hard";
}
private PlayerStatistics FindLocalPlayer(MatchStatistics ms)
{
int pCount = ms.GetPlayerCount();
for (int pId = 0; pId < pCount; pId++)
{
PlayerStatistics ps = ms.GetPlayer(pId);
if (!ps.IsAI && ps.IsLocalPlayer)
return ps;
}
return null;
}
private int GetHighestIndex(int[] t)
{
int highestIndex = -1;
int highest = Int32.MinValue;
for (int i = 0; i < t.Length; i++)
{
if (t[i] > highest)
{
highest = t[i];
highestIndex = i;
}
}
return highestIndex;
}
private void ClearAllStatistics()
{
StatisticsManager.Instance.ClearDatabase();
ReadStatistics();
ListGameModes();
ListGames();
}
#endregion
private void BtnReturnToMenu_LeftClick(object sender, EventArgs e)
{
// To hide the control, just set Enabled=false
// and MainMenuDarkeningPanel will deal with the rest
Enabled = false;
}
private void BtnClearStatistics_LeftClick(object sender, EventArgs e)
{
var msgBox = new XNAMessageBox(WindowManager, "Clear all statistics",
"All statistics data will be cleared from the database." +
Environment.NewLine + Environment.NewLine +
"Are you sure you want to continue?", XNAMessageBoxButtons.YesNo);
msgBox.Show();
msgBox.YesClickedAction = ClearStatisticsConfirmation_YesClicked;
}
private void ClearStatisticsConfirmation_YesClicked(XNAMessageBox messageBox)
{
ClearAllStatistics();
}
}
}
| 40.58756 | 138 | 0.556114 | [
"MIT"
] | GrantBartlett/xna-cncnet-client | DXMainClient/DXGUI/Generic/StatisticsWindow.cs | 41,372 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. 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.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.CodeAnalysis.Collections;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents an identity of an assembly as defined by CLI metadata specification.
/// </summary>
/// <remarks>
/// May represent assembly definition or assembly reference identity.
/// </remarks>
partial class AssemblyIdentity
{
/// <summary>
/// Returns the display name of the assembly identity.
/// </summary>
/// <param name="fullKey">True if the full public key should be included in the name. Otherwise public key token is used.</param>
/// <returns>The display name.</returns>
/// <remarks>
/// Characters ',', '=', '"', '\'', '\' occuring in the simple name are escaped by backslash in the display name.
/// Any character '\t' is replaced by two characters '\' and 't',
/// Any character '\n' is replaced by two characters '\' and 'n',
/// Any character '\r' is replaced by two characters '\' and 'r',
/// The assembly name in the display name is enclosed in double qoutes if it starts or ends with
/// a whitespace character (' ', '\t', '\r', '\n').
/// </remarks>
public string GetDisplayName(bool fullKey = false)
{
if (fullKey)
{
return BuildDisplayName(fullKey: true);
}
if (lazyDisplayName == null)
{
lazyDisplayName = BuildDisplayName(fullKey: false);
}
return lazyDisplayName;
}
/// <summary>
/// Returns the display name of the current instance.
/// </summary>
public override string ToString()
{
return GetDisplayName(fullKey: false);
}
private string BuildDisplayName(bool fullKey)
{
PooledStringBuilder pooledBuilder = PooledStringBuilder.GetInstance();
var sb = pooledBuilder.Builder;
EscapeName(sb, Name);
sb.Append(", Version=");
sb.Append(version.Major);
sb.Append(".");
sb.Append(version.Minor);
sb.Append(".");
sb.Append(version.Build);
sb.Append(".");
sb.Append(version.Revision);
sb.Append(", Culture=");
sb.Append(cultureName.Length != 0 ? cultureName : "neutral");
if (fullKey && HasPublicKey)
{
sb.Append(", PublicKey=");
AppendKey(sb, publicKey);
}
else
{
sb.Append(", PublicKeyToken=");
if (PublicKeyToken.Length > 0)
{
AppendKey(sb, PublicKeyToken);
}
else
{
sb.Append("null");
}
}
if (IsRetargetable)
{
sb.Append(", Retargetable=Yes");
}
switch (contentType)
{
case AssemblyContentType.Default:
break;
case AssemblyContentType.WindowsRuntime:
sb.Append(", ContentType=WindowsRuntime");
break;
default:
throw ExceptionUtilities.UnexpectedValue(contentType);
}
string result = sb.ToString();
pooledBuilder.Free();
return result;
}
private static void AppendKey(StringBuilder sb, ImmutableArray<byte> key)
{
foreach (byte b in key)
{
sb.Append(b.ToString("x2"));
}
}
private string GetDebuggerDisplay()
{
return GetDisplayName(fullKey: true);
}
public static bool TryParseDisplayName(string displayName, out AssemblyIdentity identity)
{
if (displayName == null)
{
throw new ArgumentNullException("displayName");
}
AssemblyIdentityParts parts;
return TryParseDisplayName(displayName, out identity, out parts);
}
/// <summary>
/// Parses display name filling defaults for any basic properties that are missing.
/// </summary>
/// <param name="displayName">Display name.</param>
/// <param name="identity">A full assembly identity.</param>
/// <param name="parts">
/// Parts of the assembly identity that were specified in the display name,
/// or 0 if the parsing failed.
/// </param>
/// <returns>True if display name parsed correctly.</returns>
/// <remarks>
/// The simple name has to be non-empty.
/// A partially specified version might be missing build and/or revision number. The default value for these is 65535.
/// The default culture is neutral (<see cref="CultureName"/> is <see cref="String.Empty"/>.
/// If neither public key nor token is specified the identity is considered weak.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="displayName"/> is null.</exception>
public static bool TryParseDisplayName(string displayName, out AssemblyIdentity identity, out AssemblyIdentityParts parts)
{
// see ndp\clr\src\Binder\TextualIdentityParser.cpp, ndp\clr\src\Binder\StringLexer.cpp
identity = null;
parts = 0;
if (displayName == null)
{
throw new ArgumentNullException("displayName");
}
if (displayName.IndexOf('\0') >= 0)
{
return false;
}
int position = 0;
string simpleName = TryParseNameToken(displayName, ',', ref position);
if (simpleName == null)
{
return false;
}
var parsedParts = AssemblyIdentityParts.Name;
var seen = AssemblyIdentityParts.Name;
Version version = null;
string culture = null;
bool isRetargetable = false;
var contentType = AssemblyContentType.Default;
var publicKey = default(ImmutableArray<byte>);
var publicKeyToken = default(ImmutableArray<byte>);
while (position < displayName.Length)
{
string propertyName = TryParseNameToken(displayName, '=', ref position);
if (propertyName == null)
{
return false;
}
string propertyValue = TryParseNameToken(displayName, ',', ref position);
if (propertyValue == null)
{
return false;
}
if (string.Equals(propertyName, "Version", StringComparison.OrdinalIgnoreCase))
{
if ((seen & AssemblyIdentityParts.Version) != 0)
{
return false;
}
seen |= AssemblyIdentityParts.Version;
if (propertyValue == "*")
{
continue;
}
ulong versionLong;
AssemblyIdentityParts versionParts;
if (!TryParseVersion(propertyValue, out versionLong, out versionParts))
{
return false;
}
version = ToVersion(versionLong);
parsedParts |= versionParts;
}
else if (string.Equals(propertyName, "Culture", StringComparison.OrdinalIgnoreCase) ||
string.Equals(propertyName, "Language", StringComparison.OrdinalIgnoreCase))
{
if ((seen & AssemblyIdentityParts.Culture) != 0)
{
return false;
}
seen |= AssemblyIdentityParts.Culture;
if (propertyValue == "*")
{
continue;
}
culture = string.Equals(propertyValue, "neutral", StringComparison.OrdinalIgnoreCase) ? null : propertyValue;
parsedParts |= AssemblyIdentityParts.Culture;
}
else if (string.Equals(propertyName, "PublicKey", StringComparison.OrdinalIgnoreCase))
{
if ((seen & AssemblyIdentityParts.PublicKey) != 0)
{
return false;
}
seen |= AssemblyIdentityParts.PublicKey;
if (propertyValue == "*")
{
continue;
}
ImmutableArray<byte> value = ParseKey(propertyValue);
if (value.Length == 0)
{
return false;
}
publicKey = value;
parsedParts |= AssemblyIdentityParts.PublicKey;
}
else if (string.Equals(propertyName, "PublicKeyToken", StringComparison.OrdinalIgnoreCase))
{
if ((seen & AssemblyIdentityParts.PublicKeyToken) != 0)
{
return false;
}
seen |= AssemblyIdentityParts.PublicKeyToken;
if (propertyValue == "*")
{
continue;
}
ImmutableArray<byte> value;
if (string.Equals(propertyValue, "null", StringComparison.OrdinalIgnoreCase) ||
string.Equals(propertyValue, "neutral", StringComparison.OrdinalIgnoreCase))
{
value = ImmutableArray.Create<byte>();
}
else
{
value = ParseKey(propertyValue);
if (value.Length != PublicKeyTokenSize)
{
return false;
}
}
publicKeyToken = value;
parsedParts |= AssemblyIdentityParts.PublicKeyToken;
}
else if (string.Equals(propertyName, "Retargetable", StringComparison.OrdinalIgnoreCase))
{
if ((seen & AssemblyIdentityParts.Retargetability) != 0)
{
return false;
}
seen |= AssemblyIdentityParts.Retargetability;
if (propertyValue == "*")
{
continue;
}
if (string.Equals(propertyValue, "Yes", StringComparison.OrdinalIgnoreCase))
{
isRetargetable = true;
}
else if (string.Equals(propertyValue, "No", StringComparison.OrdinalIgnoreCase))
{
isRetargetable = false;
}
else
{
return false;
}
parsedParts |= AssemblyIdentityParts.Retargetability;
}
else if (string.Equals(propertyName, "ContentType", StringComparison.OrdinalIgnoreCase))
{
if ((seen & AssemblyIdentityParts.ContentType) != 0)
{
return false;
}
seen |= AssemblyIdentityParts.ContentType;
if (propertyValue == "*")
{
continue;
}
if (string.Equals(propertyValue, "WindowsRuntime", StringComparison.OrdinalIgnoreCase))
{
contentType = AssemblyContentType.WindowsRuntime;
}
else
{
return false;
}
parsedParts |= AssemblyIdentityParts.ContentType;
}
else
{
parsedParts |= AssemblyIdentityParts.Unknown;
}
}
// incompatible values:
if (isRetargetable && contentType == AssemblyContentType.WindowsRuntime)
{
return false;
}
bool hasPublicKey = !publicKey.IsDefault;
bool hasPublicKeyToken = !publicKeyToken.IsDefault;
identity = new AssemblyIdentity(simpleName, version, culture, hasPublicKey ? publicKey : publicKeyToken, hasPublicKey, isRetargetable, contentType);
if (hasPublicKey && hasPublicKeyToken && !identity.PublicKeyToken.SequenceEqual(publicKeyToken))
{
identity = null;
return false;
}
parts = parsedParts;
return true;
}
private static string TryParseNameToken(string displayName, char terminator, ref int position)
{
Debug.Assert(displayName.IndexOf('\0') == -1);
int i = position;
// skip leading whitespace:
while (i < displayName.Length && IsWhiteSpace(displayName[i]))
{
i++;
}
if (i == displayName.Length)
{
return null;
}
char quote;
if (IsQuote(displayName[i]))
{
quote = displayName[i++];
}
else
{
quote = '\0';
}
int valueStart = i;
int valueEnd = displayName.Length;
int escapeCount = 0;
while (i < displayName.Length)
{
char c = displayName[i];
if (c == '\\')
{
escapeCount++;
i += 2;
continue;
}
if (quote == 0)
{
if (c == terminator)
{
int j = i - 1;
while (j >= valueStart && IsWhiteSpace(displayName[j]))
{
j--;
}
valueEnd = j + 1;
break;
}
if (IsQuote(c) || IsNameTokenTerminator(c))
{
return null;
}
}
else if (c == quote)
{
valueEnd = i;
i++;
// skip any whitespace following the quote
while (i < displayName.Length && IsWhiteSpace(displayName[i]))
{
i++;
}
if (i < displayName.Length && displayName[i] != terminator)
{
return null;
}
break;
}
i++;
}
Debug.Assert(i >= displayName.Length || IsNameTokenTerminator(displayName[i]));
position = (i >= displayName.Length) ? displayName.Length : i + 1;
// empty
if (valueEnd == valueStart)
{
return null;
}
if (escapeCount == 0)
{
return displayName.Substring(valueStart, valueEnd - valueStart);
}
else
{
return Unescape(displayName, valueStart, valueEnd);
}
}
private static bool IsNameTokenTerminator(char c)
{
return c == '=' || c == ',';
}
private static bool IsQuote(char c)
{
return c == '"' || c == '\'';
}
internal static Version ToVersion(ulong version)
{
return new Version(
unchecked((ushort)(version >> 48)),
unchecked((ushort)(version >> 32)),
unchecked((ushort)(version >> 16)),
unchecked((ushort)version));
}
// internal for testing
// Parses version format:
// [version-part]{[.][version-part], 3}
// Where version part is
// [*]|[0-9]*
// The number of dots in the version determines the present parts, i.e.
// "1..2" parses as "1.0.2.0" with Major, Minor and Build parts.
// "1.*" parses as "1.0.0.0" with Major and Minor parts.
internal static bool TryParseVersion(string str, out ulong result, out AssemblyIdentityParts parts)
{
Debug.Assert(str.Length > 0);
Debug.Assert(str.IndexOf('\0') < 0);
const int MaxVersionParts = 4;
const int BitsPerVersionPart = 16;
parts = 0;
result = 0;
int partOffset = BitsPerVersionPart * (MaxVersionParts - 1);
int partIndex = 0;
int partValue = 0;
bool partHasValue = false;
bool partHasWildcard = false;
int i = 0;
while (true)
{
char c = (i < str.Length) ? str[i++] : '\0';
if (c == '.' || c == 0)
{
if (partIndex == MaxVersionParts || partHasValue && partHasWildcard)
{
return false;
}
result |= ((ulong)partValue) << partOffset;
if (partHasValue || partHasWildcard)
{
parts |= (AssemblyIdentityParts)((int)AssemblyIdentityParts.VersionMajor << partIndex);
}
if (c == 0)
{
return true;
}
// next part:
partValue = 0;
partOffset -= BitsPerVersionPart;
partIndex++;
partHasWildcard = partHasValue = false;
}
else if (c >= '0' && c <= '9')
{
partHasValue = true;
partValue = partValue * 10 + c - '0';
if (partValue > ushort.MaxValue)
{
return false;
}
}
else if (c == '*')
{
partHasWildcard = true;
}
else
{
return false;
}
}
}
private static ImmutableArray<byte> ParseKey(string value)
{
byte[] result = new byte[value.Length / 2];
for (int i = 0; i < result.Length; i++)
{
int hi = HexValue(value[i * 2]);
int lo = HexValue(value[i * 2 + 1]);
if (hi < 0 || lo < 0)
{
return ImmutableArray.Create<byte>();
}
result[i] = (byte)((hi << 4) | lo);
}
return result.AsImmutable();
}
internal static int HexValue(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
if (c >= 'a' && c <= 'f')
{
return c - 'a' + 10;
}
if (c >= 'A' && c <= 'F')
{
return c - 'A' + 10;
}
return -1;
}
private static bool IsWhiteSpace(char c)
{
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
private static void EscapeName(StringBuilder result, string name)
{
bool quoted = false;
if (IsWhiteSpace(name[0]) || IsWhiteSpace(name[name.Length - 1]))
{
result.Append('"');
quoted = true;
}
for (int i = 0; i < name.Length; i++)
{
char c = name[i];
switch (c)
{
case ',':
case '=':
case '\\':
case '"':
case '\'':
result.Append('\\');
result.Append(c);
break;
case '\t':
result.Append("\\t");
break;
case '\r':
result.Append("\\r");
break;
case '\n':
result.Append("\\n");
break;
default:
result.Append(c);
break;
}
}
if (quoted)
{
result.Append('"');
}
}
private static bool CanBeEscaped(char c)
{
switch (c)
{
case ',':
case '=':
case '\\':
case '/':
case '"':
case '\'':
case 't':
case 'n':
case 'r':
case 'u':
return true;
default:
return false;
}
}
private static string Unescape(string str, int start, int end)
{
var sb = PooledStringBuilder.GetInstance();
int i = start;
while (i < end)
{
char c = str[i++];
if (c == '\\')
{
Debug.Assert(CanBeEscaped(c));
if (!Unescape(sb.Builder, str, ref i))
{
return null;
}
}
else
{
sb.Builder.Append(c);
}
}
return sb.ToStringAndFree();
}
private static bool Unescape(StringBuilder sb, string str, ref int i)
{
if (i == str.Length)
{
return false;
}
char c = str[i++];
switch (c)
{
case ',':
case '=':
case '\\':
case '/':
case '"':
case '\'':
sb.Append(c);
return true;
case 't':
sb.Append("\t");
return true;
case 'n':
sb.Append("\n");
return true;
case 'r':
sb.Append("\r");
return true;
case 'u':
int semicolon = str.IndexOf(';', i);
if (semicolon == -1)
{
return false;
}
try
{
int codepoint = Convert.ToInt32(str.Substring(i, semicolon - i), 16);
// \0 is not valid in an asembly name
if (codepoint == 0)
{
return false;
}
sb.Append(char.ConvertFromUtf32(codepoint));
}
catch
{
return false;
}
i = semicolon + 1;
return true;
default:
return false;
}
}
}
} | 31.651671 | 184 | 0.417787 | [
"ECL-2.0",
"Apache-2.0"
] | binsys/roslyn_java | Src/Compilers/Core/Source/MetadataReference/AssemblyIdentity.DisplayName.cs | 24,627 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpeedPowerUp : MonoBehaviour {
private GameObject player;
private PlayerController playerController;
// Use this for initialization
void Start () {
player = GameManager.instance.Player;
playerController = player.GetComponent<PlayerController>();
GameManager.instance.RegisterPowerUp();
}
void OnTriggerEnter (Collider other) {
if (other.gameObject == player) {
playerController.SpeedPowerUp();
Destroy(gameObject);
}
}
}
| 22.583333 | 61 | 0.760148 | [
"MIT"
] | MylesWritesCode/Unity3D | Legend of Devslopes/Assets/Scripts/SpeedPowerUp.cs | 544 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LG.Enums
{
public sealed class PIPLocationEnum
{
private readonly String name;
private readonly int value;
public static readonly PIPLocationEnum OFF = new PIPLocationEnum(1, "00");
public static readonly PIPLocationEnum PBP = new PIPLocationEnum(2, "01");
public static readonly PIPLocationEnum PBP2 = new PIPLocationEnum(3, "02");
public static readonly PIPLocationEnum TopLeft = new PIPLocationEnum(4, "03");
public static readonly PIPLocationEnum TopRight = new PIPLocationEnum(5, "04");
public static readonly PIPLocationEnum BottomLeft = new PIPLocationEnum(6, "05");
public static readonly PIPLocationEnum BottomRight = new PIPLocationEnum(7, "06");
public static readonly PIPLocationEnum PBP_3P_NA = new PIPLocationEnum(8, "07");
public static readonly PIPLocationEnum PBP_L1P_R2P_NA = new PIPLocationEnum(9, "08");
public static readonly PIPLocationEnum PBP_4P = new PIPLocationEnum(10, "09");
private PIPLocationEnum(int value, String name)
{
this.name = name;
this.value = value;
}
public override String ToString()
{
return name;
}
}
}
| 33.289474 | 88 | 0.735968 | [
"MIT"
] | knarfalingus/LG43UD79 | LG43UD79/Enums/PIPLocationEnum.cs | 1,267 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201
{
using Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="ServerForCreate" />
/// </summary>
public partial class ServerForCreateTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="ServerForCreate"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="ServerForCreate" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="ServerForCreate" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="ServerForCreate" />.</param>
/// <returns>
/// an instance of <see cref="ServerForCreate" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerForCreate ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerForCreate).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return ServerForCreate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return ServerForCreate.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return ServerForCreate.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 51.510204 | 241 | 0.587824 | [
"MIT"
] | Agazoth/azure-powershell | src/MySql/generated/api/Models/Api20171201/ServerForCreate.TypeConverter.cs | 7,426 | C# |
namespace BethanysPieShopHRM.ClientApp
{
public class Theme
{
public string ButtonClass { get; set; } = "btn-danger";
}
}
| 17.875 | 63 | 0.629371 | [
"MIT"
] | TheRealDuckboy/EntityFrameworkCore.LocalStorage | examples/Example1/BethanysPieShopHRM.ClientApp/Theme.cs | 145 | C# |
namespace MyForum.Web.API.Controllers
{
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyForum.Common;
using MyForum.Services.Data.Articles;
using MyForum.Web.ViewModels.Articles;
public class ArticlesController : ApiController
{
private readonly IArticleService articleService;
public ArticlesController(IArticleService articleService)
{
this.articleService = articleService;
}
[HttpGet]
public async Task<IEnumerable<ArticleDetailsViewModel>> All([FromQuery] int page = 1)
{
page = Math.Max(1, page);
var skip = (page - 1) * GlobalConstants.ArticlesPerPage;
var articles = await this.articleService.AllAsync(GlobalConstants.ArticlesPerPage, page, skip);
return articles;
}
[HttpGet]
[Authorize]
[Route("Mine")]
public async Task<IEnumerable<ArticleDetailsViewModel>> Mine([FromQuery] int page = 1)
{
page = Math.Max(1, page);
var skip = (page - 1) * GlobalConstants.ArticlesPerPage;
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
var articles = await this.articleService.AllByUserIdAsync(userId, GlobalConstants.ArticlesPerPage, page, skip);
return articles;
}
[HttpPost]
[Authorize]
public async Task<ActionResult<CreateEditArticleResponseModel>> Create(CreateArticleInputModel inputModel)
{
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
var articleId = await this.articleService.AddArticleAsync(inputModel, userId);
if (articleId == 0)
{
return this.BadRequest();
}
var result = new CreateEditArticleResponseModel
{
Id = articleId,
};
return result;
}
[HttpGet]
[Route("{id}")]
public async Task<ArticleDetailsViewModel> Details(int id)
{
var article = await this.articleService.DetailsAsync(id);
return article;
}
[HttpPut]
[Authorize]
[Route("{id}")]
public async Task<IActionResult> Edit(int id, EditArticleInputModel inputModel)
{
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
var result = await this.articleService.EditAsync(inputModel, userId, id);
if (result == false)
{
return this.BadRequest();
}
var returnArticleId = new CreateEditArticleResponseModel
{
Id = id,
};
return this.Ok(returnArticleId);
}
[HttpDelete]
[Authorize]
[Route("{id}")]
public async Task<IActionResult> Delete(int id)
{
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
var result = await this.articleService.DeleteAsync(id, userId);
if (result == false)
{
return this.BadRequest();
}
return this.Ok();
}
[HttpGet]
[Route("Count")]
public async Task<int> GetArticlesCount()
{
var count = await this.articleService.AllArticlesCountAsync();
return count;
}
[HttpGet]
[Authorize]
[Route("Mine/Count")]
public async Task<int> GetArticlesCountByCurrentUser()
{
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
var count = await this.articleService.AllArticlesCountByUserIdAsync(userId);
return count;
}
}
}
| 28.410072 | 123 | 0.582173 | [
"MIT"
] | BorisLechev/MyForum | Server/Web/MyForum.Web.API/Controllers/ArticlesController.cs | 3,951 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Data.Common;
using System.Security.Cryptography;
using ComLib;
using ComLib.Logging;
using ComLib.Application;
using ComLib.EmailSupport;
using ComLib.Notifications;
namespace ComLib.Samples
{
/// <summary>
/// Example for the Notifications namespace.
/// </summary>
public class Example_Notifications : App
{
/// <summary>
/// Run the application.
/// </summary>
public override BoolMessageItem Execute()
{
// Configure the notification service.
// Since emailing is disabled, the EmailServiceSettings are not configured.
// The emails are not sent as "EnableNotifications" = false above.
// Debugging is turned on so you can see the emails in the folder "Notifications.Tests".
Notifier.Init(new EmailService(new EmailServiceSettings()), new NotificationSettings());
Notifier.Settings["website.name"] = "KnowledgeDrink.com";
Notifier.Settings["website.url"] = "http://www.KnowledgeDrink.com";
Notifier.Settings["website.urls.contactus"] = "http://www.KnowledgeDrink.com/contactus.aspx";
Notifier.Settings.EnableNotifications = false;
Notifier.Settings.DebugOutputMessageToFile = true;
Notifier.Settings.DebugOutputMessageFolderPath = @"Notifications.Tests";
Logger.Info("====================================================");
Logger.Info("NOTIFICATION EMAILS ");
Logger.Info("Emails are generated to folder : " + Notifier.Settings.DebugOutputMessageFolderPath);
Notifier.WelcomeNewUser("user1@mydomain.com", "Welcome to www.knowledgedrink.com", "batman", "user1", "password");
Notifier.RemindUserPassword("user1@mydomain.com", "Welcome to www.knowledgedrink.com", "batman", "user1", "password");
Notifier.SendToFriend("batman@mydomain.com", "Check out www.knowledgedrink.com", "superman", "bruce", "Learn to fight.");
Notifier.SendToFriendPost("superman@mydomain.com", "Check out class at www.knowledgedrink.com", "batman", "clark", "Punk, learn to fly.",
"Learn to fly", "http://www.knowledgedrink.com/classes/learn-to-fly.aspx");
Notifier.Process();
return BoolMessageItem.True;
}
}
}
| 46.339623 | 149 | 0.651466 | [
"MIT"
] | joelverhagen/Knapcode.CommonLibrary.NET | src/Lib/CommonLibrary.NET/_Samples/Example_Notifications.cs | 2,458 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using NUnit.Framework;
using TestUtils;
using GitHub.Unity;
namespace UnitTests
{
[TestFixture]
public class GitLogEntryListTests
{
[Test]
public void NullListShouldEqualNullList()
{
GitLogEntry[] entries = null;
GitLogEntry[] otherEntries = null;
entries.AssertEqual(otherEntries);
}
[Test]
public void NullListShouldNotEqualEmptyList()
{
GitLogEntry[] entries = {};
GitLogEntry[] otherEntries = null;
entries.AssertNotEqual(otherEntries);
}
[Test]
public void NullListShouldNotEqualListOf1()
{
var commitTime = new DateTimeOffset(1921, 12, 23, 1, 3, 6, 23, TimeSpan.Zero);
var entries = new[]
{
new GitLogEntry("CommitID",
"AuthorName", "AuthorEmail",
"AuthorName", "AuthorEmail",
"Summary",
"Description",
commitTime, commitTime,
new List<GitStatusEntry>(),
"MergeA", "MergeB")
};
GitLogEntry[] otherEntries = null;
entries.AssertNotEqual(otherEntries);
}
[Test]
public void EmptyListShouldNotEqualListOf1()
{
var commitTime = new DateTimeOffset(1921, 12, 23, 1, 3, 6, 23, TimeSpan.Zero);
var entries = new[]
{
new GitLogEntry("CommitID",
"AuthorName", "AuthorEmail",
"AuthorName", "AuthorEmail",
"Summary",
"Description",
commitTime, commitTime,
new List<GitStatusEntry>(),
"MergeA", "MergeB")
};
GitLogEntry[] otherEntries = new GitLogEntry[0];
entries.AssertNotEqual(otherEntries);
}
[Test]
public void ListOf1ShouldEqualListOf1()
{
var commitTime = new DateTimeOffset(1921, 12, 23, 1, 3, 6, 23, TimeSpan.Zero);
var entries = new[]
{
new GitLogEntry("CommitID",
"AuthorName", "AuthorEmail",
"AuthorName", "AuthorEmail",
"Summary",
"Description",
commitTime, commitTime,
new List<GitStatusEntry>
{
new GitStatusEntry("SomePath", "SomeFullPath", "SomeProjectPath", GitFileStatus.Added, GitFileStatus.None, "SomeOriginalPath"),
},
"MergeA", "MergeB")
};
var otherEntries = new[]
{
new GitLogEntry("CommitID",
"AuthorName", "AuthorEmail",
"AuthorName", "AuthorEmail",
"Summary",
"Description",
commitTime, commitTime,
new List<GitStatusEntry>(new[]
{
new GitStatusEntry("SomePath", "SomeFullPath", "SomeProjectPath", GitFileStatus.Added, GitFileStatus.None, "SomeOriginalPath"),
}),
"MergeA", "MergeB")
};
entries.AssertEqual(otherEntries);
}
[Test]
public void ListOf2ShouldEqualListOf2()
{
var commitTime = new DateTimeOffset(1921, 12, 23, 1, 3, 6, 23, TimeSpan.Zero);
var otherCommitTime = new DateTimeOffset(1981, 12, 23, 1, 3, 6, 23, TimeSpan.Zero);
var entries = new[]
{
new GitLogEntry("CommitID",
"AuthorName", "AuthorEmail",
"AuthorName", "AuthorEmail",
"Summary", "Description",
commitTime, commitTime,
new List<GitStatusEntry>
{
new GitStatusEntry("SomePath", "SomeFullPath", "SomeProjectPath", GitFileStatus.Added, GitFileStatus.None, "SomeOriginalPath"),
},
"MergeA", "MergeB"),
new GitLogEntry("`CommitID",
"`AuthorName", "`AuthorEmail",
"`AuthorName", "`AuthorEmail",
"`Summary",
"`Description",
commitTime, commitTime,
new List<GitStatusEntry>(),
"`MergeA", "`MergeB"),
};
var otherEntries = new[]
{
new GitLogEntry("CommitID",
"AuthorName", "AuthorEmail",
"AuthorName", "AuthorEmail",
"Summary",
"Description",
commitTime, commitTime,
new List<GitStatusEntry> {
new GitStatusEntry("SomePath", "SomeFullPath", "SomeProjectPath", GitFileStatus.Added, GitFileStatus.None, "SomeOriginalPath")
},
"MergeA", "MergeB"),
new GitLogEntry("`CommitID",
"`AuthorName", "`AuthorEmail",
"`AuthorName", "`AuthorEmail",
"`Summary",
"`Description",
commitTime, commitTime,
new List<GitStatusEntry>(),
"`MergeA", "`MergeB")
};
entries.AssertEqual(otherEntries);
}
[Test]
public void ListOf2ShouldNotEqualListOf2InDifferentOrder()
{
var commitTime = new DateTimeOffset(1921, 12, 23, 1, 3, 6, 23, TimeSpan.Zero);
var otherCommitTime = new DateTimeOffset(1981, 12, 23, 1, 3, 6, 23, TimeSpan.Zero);
var entries = new[]
{
new GitLogEntry("CommitID",
"AuthorName", "AuthorEmail",
"AuthorName", "AuthorEmail",
"Summary",
"Description",
commitTime, commitTime,
new List<GitStatusEntry>(new[]
{
new GitStatusEntry("SomePath", "SomeFullPath", "SomeProjectPath", GitFileStatus.Added, GitFileStatus.None, "SomeOriginalPath"),
}),
"MergeA", "MergeB"),
new GitLogEntry("`CommitID",
"`AuthorName", "`AuthorEmail",
"`AuthorName", "`AuthorEmail",
"`Summary",
"`Description",
commitTime, commitTime,
new List<GitStatusEntry>(),
"`MergeA", "`MergeB"),
};
var otherEntries = new[]
{
new GitLogEntry("`CommitID",
"`AuthorName", "`AuthorEmail",
"`AuthorName", "`AuthorEmail",
"`Summary",
"`Description",
otherCommitTime, otherCommitTime,
new List<GitStatusEntry>(),
"`MergeA", "`MergeB"),
new GitLogEntry("CommitID",
"AuthorName", "AuthorEmail",
"AuthorName", "AuthorEmail",
"Summary",
"Description",
otherCommitTime, otherCommitTime,
new List<GitStatusEntry>(new[]
{
new GitStatusEntry("SomePath", "SomeFullPath", "SomeProjectPath", GitFileStatus.Added, GitFileStatus.None, "SomeOriginalPath"),
}),
"MergeA", "MergeB")
};
entries.AssertNotEqual(otherEntries);
}
}
}
| 35.775785 | 151 | 0.456756 | [
"MIT"
] | Anras573/Unity | src/tests/UnitTests/IO/GitLogEntryListTests.cs | 7,978 | C# |
#region License
//
// Copyright 2002-2017 Drew Noakes
// Ported from Java to C# by Yakov Danilov for Imazen LLC in 2014
//
// 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.
//
// More information about this project is available at:
//
// https://github.com/drewnoakes/metadata-extractor-dotnet
// https://drewnoakes.com/code/exif/
//
#endregion
using System.Collections.Generic;
using JetBrains.Annotations;
#if NET35
using DirectoryList = System.Collections.Generic.IList<MetadataExtractor.Directory>;
#else
using DirectoryList = System.Collections.Generic.IReadOnlyList<MetadataExtractor.Directory>;
#endif
namespace MetadataExtractor.Formats.Jpeg
{
/// <summary>Defines an object that extracts metadata from in JPEG segments.</summary>
public interface IJpegSegmentMetadataReader
{
/// <summary>Gets the set of JPEG segment types that this reader is interested in.</summary>
[NotNull]
ICollection<JpegSegmentType> SegmentTypes { get; }
/// <summary>Extracts metadata from all instances of a particular JPEG segment type.</summary>
/// <param name="segments">
/// A sequence of JPEG segments from which the metadata should be extracted. These are in the order encountered in the original file.
/// </param>
[NotNull]
DirectoryList ReadJpegSegments([NotNull] IEnumerable<JpegSegment> segments);
}
}
| 37.843137 | 141 | 0.721762 | [
"Apache-2.0"
] | AkosLukacs/metadata-extractor-dotnet | MetadataExtractor/Formats/Jpeg/IJpegSegmentMetadataReader.cs | 1,930 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using HuaweiCloud.SDK.Core;
namespace HuaweiCloud.SDK.Cbr.V1.Model
{
/// <summary>
///
/// </summary>
public class OpErrorInfo
{
/// <summary>
/// 请参见[错误码](ErrorCode.xml)。
/// </summary>
[JsonProperty("code", NullValueHandling = NullValueHandling.Ignore)]
public string Code { get; set; }
/// <summary>
/// 错误信息
/// </summary>
[JsonProperty("message", NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; set; }
/// <summary>
/// Get the string
/// </summary>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OpErrorInfo {\n");
sb.Append(" code: ").Append(Code).Append("\n");
sb.Append(" message: ").Append(Message).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public override bool Equals(object input)
{
return this.Equals(input as OpErrorInfo);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public bool Equals(OpErrorInfo input)
{
if (input == null)
return false;
return
(
this.Code == input.Code ||
(this.Code != null &&
this.Code.Equals(input.Code))
) &&
(
this.Message == input.Message ||
(this.Message != null &&
this.Message.Equals(input.Message))
);
}
/// <summary>
/// Get hash code
/// </summary>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Code != null)
hashCode = hashCode * 59 + this.Code.GetHashCode();
if (this.Message != null)
hashCode = hashCode * 59 + this.Message.GetHashCode();
return hashCode;
}
}
}
}
| 27.577778 | 79 | 0.480661 | [
"Apache-2.0"
] | cnblogs/huaweicloud-sdk-net-v3 | Services/Cbr/V1/Model/OpErrorInfo.cs | 2,504 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using DSharp.Compiler.ScriptModel.Symbols;
namespace DSharp.Compiler.Extensions
{
public static class TypeSymbolExtensions
{
private static readonly StringComparer stringComparer = StringComparer.InvariantCultureIgnoreCase;
internal static ICollection<InterfaceSymbol> GetInterfaces(this TypeSymbol symbol)
{
if (symbol is ClassSymbol classSymbol)
{
return classSymbol.Interfaces ?? Array.Empty<InterfaceSymbol>();
}
if (symbol is InterfaceSymbol interfaceSymbol)
{
var interfaces = new List<InterfaceSymbol> { interfaceSymbol };
if (interfaceSymbol.Interfaces != null)
{
interfaces.AddRange(interfaceSymbol.Interfaces);
}
return interfaces;
}
return null;
}
internal static bool ImplementsListType(this TypeSymbol symbol)
{
var interfaces = symbol.GetInterfaces();
if (interfaces == null)
{
return false;
}
return interfaces.Any(i => IsSpecifiedType(i, "System.Collections", "IList", "IList`1"));
}
internal static bool IsDictionary(this TypeSymbol symbol)
=> IsSpecifiedType(symbol, "System.Collections.Generic", "Dictionary`2");
internal static bool IsList(this TypeSymbol symbol)
=> IsSpecifiedType(symbol, "System.Collections", "List", "List`1");
internal static bool IsArgumentsType(this TypeSymbol symbol)
{
return symbol.FullName == "System.Arguments";
}
internal static bool IsNativeObject(this TypeSymbol typeSymbol)
{
return stringComparer.Equals(typeSymbol.FullGeneratedName, nameof(Object));
}
internal static bool IsReservedType(this TypeSymbol typeSymbol)
{
return typeSymbol.IsList() || typeSymbol.IsDictionary();
}
private static bool IsSpecifiedType(TypeSymbol typeSymbol, string ns, params string[] typeAliases)
{
return typeSymbol.FullName.StartsWith(ns)
&& typeAliases.Any(alias => typeSymbol.FullName.EndsWith(alias));
}
}
}
| 32.081081 | 106 | 0.611626 | [
"Apache-2.0"
] | donluispanis/dsharp | src/DSharp.Compiler/Extensions/TypeSymbolExtensions.cs | 2,376 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
using FairyGUI.Utils;
namespace FairyGUI
{
/// <summary>
/// Component
/// </summary>
public class GComponent : GObject
{
/// <summary>
/// Root container.
/// </summary>
public Container rootContainer { get; private set; }
/// <summary>
/// Content container. If the component is not clipped, then container==rootContainer.
/// </summary>
public Container container { get; protected set; }
/// <summary>
/// ScrollPane of the component. If the component is not scrollable, the value is null.
/// </summary>
public ScrollPane scrollPane { get; private set; }
internal List<GObject> _children;
internal List<Controller> _controllers;
internal List<Transition> _transitions;
internal bool _buildingDisplayList;
protected Margin _margin;
protected bool _trackBounds;
protected bool _boundsChanged;
protected ChildrenRenderOrder _childrenRenderOrder;
protected int _apexIndex;
internal Vector2 _alignOffset;
Vector2 _clipSoftness;
int _sortingChildCount;
EventCallback0 _buildDelegate;
Controller _applyingController;
EventListener _onDrop;
public GComponent()
{
_children = new List<GObject>();
_controllers = new List<Controller>();
_transitions = new List<Transition>();
_margin = new Margin();
_buildDelegate = BuildNativeDisplayList;
}
override protected void CreateDisplayObject()
{
rootContainer = new Container("GComponent");
rootContainer.gOwner = this;
rootContainer.onUpdate = OnUpdate;
container = rootContainer;
displayObject = rootContainer;
}
override public void Dispose()
{
int cnt = _transitions.Count;
for (int i = 0; i < cnt; ++i)
{
Transition trans = _transitions[i];
trans.Dispose();
}
cnt = _controllers.Count;
for (int i = 0; i < cnt; ++i)
{
Controller c = _controllers[i];
c.Dispose();
}
if (scrollPane != null)
scrollPane.Dispose();
base.Dispose(); //Dispose native tree first, avoid DisplayObject.RemoveFromParent call
cnt = _children.Count;
for (int i = cnt - 1; i >= 0; --i)
{
GObject obj = _children[i];
obj.InternalSetParent(null); //Avoid GObject.RemoveParent call
obj.Dispose();
}
}
/// <summary>
/// Dispatched when an object was dragged and dropped to this component.
/// </summary>
public EventListener onDrop
{
get { return _onDrop ?? (_onDrop = new EventListener(this, "onDrop")); }
}
/// <summary>
/// Draw call optimization switch.
/// </summary>
public bool fairyBatching
{
get { return rootContainer.fairyBatching; }
set { rootContainer.fairyBatching = value; }
}
public void InvalidateBatchingState(bool childChanged)
{
if (childChanged)
container.InvalidateBatchingState(childChanged);
else
rootContainer.InvalidateBatchingState();
}
/// <summary>
/// If true, mouse/touch events cannot pass through the empty area of the component. Default is true.
/// </summary>
public bool opaque
{
get { return rootContainer.opaque; }
set { rootContainer.opaque = value; }
}
public Margin margin
{
get { return _margin; }
set
{
_margin = value;
if (rootContainer.clipRect != null && scrollPane == null) //如果scrollPane不为空,则HandleSizeChanged里面的处理会促使ScrollPane处理
container.SetXY(_margin.left + _alignOffset.x, _margin.top + _alignOffset.y);
HandleSizeChanged();
}
}
public ChildrenRenderOrder childrenRenderOrder
{
get { return _childrenRenderOrder; }
set
{
if (_childrenRenderOrder != value)
{
_childrenRenderOrder = value;
BuildNativeDisplayList();
}
}
}
public int apexIndex
{
get { return _apexIndex; }
set
{
if (_apexIndex != value)
{
_apexIndex = value;
if (_childrenRenderOrder == ChildrenRenderOrder.Arch)
BuildNativeDisplayList();
}
}
}
/// <summary>
/// Add a child to the component. It will be at the frontmost position.
/// </summary>
/// <param name="child">A child object</param>
/// <returns>GObject</returns>
public GObject AddChild(GObject child)
{
AddChildAt(child, _children.Count);
return child;
}
/// <summary>
/// Adds a child to the component at a certain index.
/// </summary>
/// <param name="child">A child object</param>
/// <param name="index">Index</param>
/// <returns>GObject</returns>
virtual public GObject AddChildAt(GObject child, int index)
{
int numChildren = _children.Count;
if (index >= 0 && index <= numChildren)
{
if (child.parent == this)
{
SetChildIndex(child, index);
}
else
{
child.RemoveFromParent();
child.InternalSetParent(this);
int cnt = _children.Count;
if (child.sortingOrder != 0)
{
_sortingChildCount++;
index = GetInsertPosForSortingChild(child);
}
else if (_sortingChildCount > 0)
{
if (index > (cnt - _sortingChildCount))
index = cnt - _sortingChildCount;
}
if (index == cnt)
_children.Add(child);
else
_children.Insert(index, child);
ChildStateChanged(child);
SetBoundsChangedFlag();
if (child.group != null)
child.group.SetBoundsChangedFlag(true);
}
return child;
}
else
{
throw new Exception("Invalid child index: " + index + ">" + numChildren);
}
}
int GetInsertPosForSortingChild(GObject target)
{
int cnt = _children.Count;
int i;
for (i = 0; i < cnt; i++)
{
GObject child = _children[i];
if (child == target)
continue;
if (target.sortingOrder < child.sortingOrder)
break;
}
return i;
}
/// <summary>
/// Removes a child from the component. If the object is not a child, nothing happens.
/// </summary>
/// <param name="child">A child object</param>
/// <returns>GObject</returns>
public GObject RemoveChild(GObject child)
{
return RemoveChild(child, false);
}
/// <summary>
/// Removes a child from the component. If the object is not a child, nothing happens.
/// </summary>
/// <param name="child">A child object</param>
/// <param name="dispose">If true, the child will be disposed right away.</param>
/// <returns>GObject</returns>
public GObject RemoveChild(GObject child, bool dispose)
{
int childIndex = _children.IndexOf(child);
if (childIndex != -1)
{
RemoveChildAt(childIndex, dispose);
}
return child;
}
/// <summary>
/// Removes a child at a certain index. Children above the child will move down.
/// </summary>
/// <param name="index">Index</param>
/// <returns>GObject</returns>
public GObject RemoveChildAt(int index)
{
return RemoveChildAt(index, false);
}
/// <summary>
/// Removes a child at a certain index. Children above the child will move down.
/// </summary>
/// <param name="index">Index</param>
/// <param name="dispose">If true, the child will be disposed right away.</param>
/// <returns>GObject</returns>
virtual public GObject RemoveChildAt(int index, bool dispose)
{
if (index >= 0 && index < numChildren)
{
GObject child = _children[index];
child.InternalSetParent(null);
if (child.sortingOrder != 0)
_sortingChildCount--;
_children.RemoveAt(index);
child.group = null;
if (child.inContainer)
{
container.RemoveChild(child.displayObject);
if (_childrenRenderOrder == ChildrenRenderOrder.Arch)
{
UpdateContext.OnBegin -= _buildDelegate;
UpdateContext.OnBegin += _buildDelegate;
}
}
if (dispose)
child.Dispose();
SetBoundsChangedFlag();
return child;
}
else
throw new Exception("Invalid child index: " + index + ">" + numChildren);
}
/// <summary>
/// Remove all children.
/// </summary>
public void RemoveChildren()
{
RemoveChildren(0, -1, false);
}
/// <summary>
/// Removes a range of children from the container (endIndex included).
/// </summary>
/// <param name="beginIndex">Begin index.</param>
/// <param name="endIndex">End index.(Included).</param>
/// <param name="dispose">If true, the child will be disposed right away.</param>
public void RemoveChildren(int beginIndex, int endIndex, bool dispose)
{
if (endIndex < 0 || endIndex >= numChildren)
endIndex = numChildren - 1;
for (int i = beginIndex; i <= endIndex; ++i)
RemoveChildAt(beginIndex, dispose);
}
/// <summary>
/// Returns a child object at a certain index. If index out of bounds, exception raised.
/// </summary>
/// <param name="index">Index</param>
/// <returns>A child object.</returns>
public GObject GetChildAt(int index)
{
if (index >= 0 && index < numChildren)
return _children[index];
else
throw new Exception("Invalid child index: " + index + ">" + numChildren);
}
/// <summary>
/// Returns a child object with a certain name.
/// </summary>
/// <param name="name">Name</param>
/// <returns>A child object. Null if not found.</returns>
public GObject GetChild(string name)
{
int cnt = _children.Count;
for (int i = 0; i < cnt; ++i)
{
if (_children[i].name == name)
return _children[i];
}
return null;
}
/// <summary>
/// Returns a visible child object with a certain name.
/// </summary>
/// <param name="name">Name</param>
/// <returns>A child object. Null if not found.</returns>
public GObject GetVisibleChild(string name)
{
int cnt = _children.Count;
for (int i = 0; i < cnt; ++i)
{
GObject child = _children[i];
if (child.internalVisible && child.internalVisible2 && child.name == name)
return child;
}
return null;
}
/// <summary>
/// Returns a child object belong to a group with a certain name.
/// </summary>
/// <param name="group">A group object</param>
/// <param name="name">Name</param>
/// <returns>A child object. Null if not found.</returns>
public GObject GetChildInGroup(GGroup group, string name)
{
int cnt = _children.Count;
for (int i = 0; i < cnt; ++i)
{
GObject child = _children[i];
if (child.group == group && child.name == name)
return child;
}
return null;
}
internal GObject GetChildById(string id)
{
int cnt = _children.Count;
for (int i = 0; i < cnt; ++i)
{
if (_children[i].id == id)
return _children[i];
}
return null;
}
/// <summary>
/// Returns a copy of all children with an array.
/// </summary>
/// <returns>An array contains all children</returns>
public GObject[] GetChildren()
{
return _children.ToArray();
}
public List<GObject> GetChildrenList()
{
return _children;
}
/// <summary>
/// Returns the index of a child within the container, or "-1" if it is not found.
/// </summary>
/// <param name="child">A child object</param>
/// <returns>Index of the child. -1 If not found.</returns>
public int GetChildIndex(GObject child)
{
return _children.IndexOf(child);
}
/// <summary>
/// Moves a child to a certain index. Children at and after the replaced position move up.
/// </summary>
/// <param name="child">A Child</param>
/// <param name="index">Index</param>
public void SetChildIndex(GObject child, int index)
{
int oldIndex = _children.IndexOf(child);
if (oldIndex == -1)
throw new ArgumentException("Not a child of this container");
if (child.sortingOrder != 0) //no effect
return;
if (_sortingChildCount > 0)
{
int cnt = _children.Count;
if (index > (cnt - _sortingChildCount - 1))
index = cnt - _sortingChildCount - 1;
}
_SetChildIndex(child, oldIndex, index);
}
/// <summary>
/// Moves a child to a certain position which is in front of the child previously at given index.
/// 与SetChildIndex不同的是,如果child原来在index的前面,那么child插入的位置是index-1,即保证排在原来占据index的对象的前面。
/// </summary>
/// <param name="child"></param>
/// <param name="index"></param>
public int SetChildIndexBefore(GObject child, int index)
{
int oldIndex = _children.IndexOf(child);
if (oldIndex == -1)
throw new ArgumentException("Not a child of this container");
if (child.sortingOrder != 0) //no effect
return oldIndex;
int cnt = _children.Count;
if (_sortingChildCount > 0)
{
if (index > (cnt - _sortingChildCount - 1))
index = cnt - _sortingChildCount - 1;
}
if (oldIndex < index)
return _SetChildIndex(child, oldIndex, index - 1);
else
return _SetChildIndex(child, oldIndex, index);
}
int _SetChildIndex(GObject child, int oldIndex, int index)
{
int cnt = _children.Count;
if (index > cnt)
index = cnt;
if (oldIndex == index)
return oldIndex;
_children.RemoveAt(oldIndex);
if (index >= cnt)
_children.Add(child);
else
_children.Insert(index, child);
if (child.inContainer)
{
int displayIndex = 0;
if (_childrenRenderOrder == ChildrenRenderOrder.Ascent)
{
for (int i = 0; i < index; i++)
{
GObject g = _children[i];
if (g.inContainer)
displayIndex++;
}
container.SetChildIndex(child.displayObject, displayIndex);
}
else if (_childrenRenderOrder == ChildrenRenderOrder.Descent)
{
for (int i = cnt - 1; i > index; i--)
{
GObject g = _children[i];
if (g.inContainer)
displayIndex++;
}
container.SetChildIndex(child.displayObject, displayIndex);
}
else
{
UpdateContext.OnBegin -= _buildDelegate;
UpdateContext.OnBegin += _buildDelegate;
}
SetBoundsChangedFlag();
}
return index;
}
/// <summary>
/// Swaps the indexes of two children.
/// </summary>
/// <param name="child1">A child object</param>
/// <param name="child2">A child object</param>
public void SwapChildren(GObject child1, GObject child2)
{
int index1 = _children.IndexOf(child1);
int index2 = _children.IndexOf(child2);
if (index1 == -1 || index2 == -1)
throw new Exception("Not a child of this container");
SwapChildrenAt(index1, index2);
}
/// <summary>
/// Swaps the indexes of two children.
/// </summary>
/// <param name="index1">index of first child</param>
/// <param name="index2">index of second child</param>
public void SwapChildrenAt(int index1, int index2)
{
GObject child1 = _children[index1];
GObject child2 = _children[index2];
SetChildIndex(child1, index2);
SetChildIndex(child2, index1);
}
/// <summary>
/// The number of children of this component.
/// </summary>
public int numChildren
{
get { return _children.Count; }
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool IsAncestorOf(GObject obj)
{
if (obj == null)
return false;
GComponent p = obj.parent;
while (p != null)
{
if (p == this)
return true;
p = p.parent;
}
return false;
}
/// <summary>
/// Adds a controller to the container.
/// </summary>
/// <param name="controller">Controller object</param>
public void AddController(Controller controller)
{
_controllers.Add(controller);
controller.parent = this;
ApplyController(controller);
}
/// <summary>
/// Returns a controller object at a certain index.
/// </summary>
/// <param name="index">Index</param>
/// <returns>Controller object.</returns>
public Controller GetControllerAt(int index)
{
return _controllers[index];
}
/// <summary>
/// Returns a controller object with a certain name.
/// </summary>
/// <param name="name">Name</param>
/// <returns>Controller object. Null if not found.</returns>
public Controller GetController(string name)
{
int cnt = _controllers.Count;
for (int i = 0; i < cnt; ++i)
{
Controller c = _controllers[i];
if (c.name == name)
return c;
}
return null;
}
/// <summary>
/// Removes a controller from the container.
/// </summary>
/// <param name="c">Controller object.</param>
public void RemoveController(Controller c)
{
int index = _controllers.IndexOf(c);
if (index == -1)
throw new Exception("controller not exists: " + c.name);
c.parent = null;
_controllers.RemoveAt(index);
int cnt = _children.Count;
for (int i = 0; i < cnt; ++i)
{
GObject child = _children[i];
child.HandleControllerChanged(c);
}
}
/// <summary>
/// Returns controller list.
/// </summary>
/// <returns>Controller list</returns>
public List<Controller> Controllers
{
get { return _controllers; }
}
/// <summary>
/// Returns a transition object at a certain index.
/// </summary>
/// <param name="index">Index</param>
/// <returns>transition object.</returns>
public Transition GetTransitionAt(int index)
{
return _transitions[index];
}
/// <summary>
/// Returns a transition object at a certain name.
/// </summary>
/// <param name="name">Name</param>
/// <returns>Transition Object</returns>
public Transition GetTransition(string name)
{
int cnt = _transitions.Count;
for (int i = 0; i < cnt; ++i)
{
Transition trans = _transitions[i];
if (trans.name == name)
return trans;
}
return null;
}
internal void ChildStateChanged(GObject child)
{
if (_buildingDisplayList)
return;
int cnt = _children.Count;
if (child is GGroup)
{
for (int i = 0; i < cnt; ++i)
{
GObject g = _children[i];
if (g.group == child)
ChildStateChanged(g);
}
return;
}
if (child.displayObject == null)
return;
if (child.internalVisible)
{
if (child.displayObject.parent == null)
{
if (_childrenRenderOrder == ChildrenRenderOrder.Ascent)
{
int index = 0;
for (int i = 0; i < cnt; i++)
{
GObject g = _children[i];
if (g == child)
break;
if (g.displayObject != null && g.displayObject.parent != null)
index++;
}
container.AddChildAt(child.displayObject, index);
}
else if (_childrenRenderOrder == ChildrenRenderOrder.Descent)
{
int index = 0;
for (int i = cnt - 1; i >= 0; i--)
{
GObject g = _children[i];
if (g == child)
break;
if (g.displayObject != null && g.displayObject.parent != null)
index++;
}
container.AddChildAt(child.displayObject, index);
}
else
{
container.AddChild(child.displayObject);
UpdateContext.OnBegin -= _buildDelegate;
UpdateContext.OnBegin += _buildDelegate;
}
}
}
else
{
if (child.displayObject.parent != null)
{
container.RemoveChild(child.displayObject);
if (_childrenRenderOrder == ChildrenRenderOrder.Arch)
{
UpdateContext.OnBegin -= _buildDelegate;
UpdateContext.OnBegin += _buildDelegate;
}
}
}
}
void BuildNativeDisplayList()
{
if (displayObject == null || displayObject.isDisposed)
return;
int cnt = _children.Count;
if (cnt == 0)
return;
switch (_childrenRenderOrder)
{
case ChildrenRenderOrder.Ascent:
{
for (int i = 0; i < cnt; i++)
{
GObject child = _children[i];
if (child.displayObject != null && child.internalVisible)
container.AddChild(child.displayObject);
}
}
break;
case ChildrenRenderOrder.Descent:
{
for (int i = cnt - 1; i >= 0; i--)
{
GObject child = _children[i];
if (child.displayObject != null && child.internalVisible)
container.AddChild(child.displayObject);
}
}
break;
case ChildrenRenderOrder.Arch:
{
for (int i = 0; i < _apexIndex; i++)
{
GObject child = _children[i];
if (child.displayObject != null && child.internalVisible)
container.AddChild(child.displayObject);
}
for (int i = cnt - 1; i >= _apexIndex; i--)
{
GObject child = _children[i];
if (child.displayObject != null && child.internalVisible)
container.AddChild(child.displayObject);
}
}
break;
}
}
internal void ApplyController(Controller c)
{
_applyingController = c;
int cnt = _children.Count;
for (int i = 0; i < cnt; ++i)
{
GObject child = _children[i];
child.HandleControllerChanged(c);
}
_applyingController = null;
c.RunActions();
}
void ApplyAllControllers()
{
int cnt = _controllers.Count;
for (int i = 0; i < cnt; ++i)
{
Controller controller = _controllers[i];
ApplyController(controller);
}
}
internal void AdjustRadioGroupDepth(GObject obj, Controller c)
{
int cnt = _children.Count;
int i;
GObject child;
int myIndex = -1, maxIndex = -1;
for (i = 0; i < cnt; i++)
{
child = _children[i];
if (child == obj)
{
myIndex = i;
}
else if ((child is GButton)
&& ((GButton)child).relatedController == c)
{
if (i > maxIndex)
maxIndex = i;
}
}
if (myIndex < maxIndex)
{
if (_applyingController != null)
_children[maxIndex].HandleControllerChanged(_applyingController);
this.SwapChildrenAt(myIndex, maxIndex);
}
}
/// <summary>
/// If clipping softness is set, clipped containers will have soft border effect.
/// </summary>
public Vector2 clipSoftness
{
get { return _clipSoftness; }
set
{
_clipSoftness = value;
if (scrollPane != null)
scrollPane.UpdateClipSoft();
else if (_clipSoftness.x > 0 || _clipSoftness.y > 0)
rootContainer.clipSoftness = new Vector4(value.x, value.y, value.x, value.y);
else
rootContainer.clipSoftness = null;
}
}
/// <summary>
/// The mask of the component.
/// </summary>
public DisplayObject mask
{
get { return container.mask; }
set { container.mask = value; }
}
/// <summary>
///
/// </summary>
public bool reversedMask
{
get { return container.reversedMask; }
set { container.reversedMask = value; }
}
/// <summary>
///
/// </summary>
public string baseUserData
{
get
{
ByteBuffer buffer = packageItem.rawData;
buffer.Seek(0, 4);
return buffer.ReadS();
}
}
/// <summary>
/// Test if a child is in view.
/// </summary>
/// <param name="child">A child object</param>
/// <returns>True if in view</returns>
public bool IsChildInView(GObject child)
{
if (scrollPane != null)
{
return scrollPane.IsChildInView(child);
}
else if (rootContainer.clipRect != null)
{
return child.x + child.width >= 0 && child.x <= this.width
&& child.y + child.height >= 0 && child.y <= this.height;
}
else
return true;
}
virtual public int GetFirstChildInView()
{
int cnt = _children.Count;
for (int i = 0; i < cnt; ++i)
{
GObject child = _children[i];
if (IsChildInView(child))
return i;
}
return -1;
}
protected void SetupScroll(ByteBuffer buffer)
{
if (rootContainer == container)
{
container = new Container();
rootContainer.AddChild(container);
}
scrollPane = new ScrollPane(this);
scrollPane.Setup(buffer);
}
protected void SetupOverflow(OverflowType overflow)
{
if (overflow == OverflowType.Hidden)
{
if (rootContainer == container)
{
container = new Container();
rootContainer.AddChild(container);
}
UpdateClipRect();
container.SetXY(_margin.left, _margin.top);
}
else if (_margin.left != 0 || _margin.top != 0)
{
if (rootContainer == container)
{
container = new Container();
rootContainer.AddChild(container);
}
container.SetXY(_margin.left, _margin.top);
}
}
void UpdateClipRect()
{
if (scrollPane == null)
{
float w = this.width - (_margin.left + _margin.right);
float h = this.height - (_margin.top + _margin.bottom);
rootContainer.clipRect = new Rect(_margin.left, _margin.top, w, h);
}
else
rootContainer.clipRect = new Rect(0, 0, this.width, this.height);
}
override protected void HandleSizeChanged()
{
base.HandleSizeChanged();
if (scrollPane != null)
scrollPane.OnOwnerSizeChanged();
if (rootContainer.clipRect != null)
UpdateClipRect();
}
override protected void HandleGrayedChanged()
{
Controller cc = GetController("grayed");
if (cc != null)
cc.selectedIndex = this.grayed ? 1 : 0;
else
base.HandleGrayedChanged();
}
override public void HandleControllerChanged(Controller c)
{
base.HandleControllerChanged(c);
if (scrollPane != null)
scrollPane.HandleControllerChanged(c);
}
/// <summary>
/// Notify the component the bounds should recaculate.
/// </summary>
public void SetBoundsChangedFlag()
{
if (scrollPane == null && !_trackBounds)
return;
_boundsChanged = true;
}
/// <summary>
/// Make sure the bounds of the component is correct.
/// Bounds of the component is not updated on every changed. For example, you add a new child to the list, children in the list will be rearranged in next frame.
/// If you want to access the correct child position immediatelly, call this function first.
/// </summary>
public void EnsureBoundsCorrect()
{
if (_boundsChanged)
UpdateBounds();
}
virtual protected void UpdateBounds()
{
float ax, ay, aw, ah;
if (_children.Count > 0)
{
ax = int.MaxValue;
ay = int.MaxValue;
float ar = int.MinValue, ab = int.MinValue;
float tmp;
int cnt = _children.Count;
for (int i = 0; i < cnt; ++i)
{
GObject child = _children[i];
tmp = child.x;
if (tmp < ax)
ax = tmp;
tmp = child.y;
if (tmp < ay)
ay = tmp;
tmp = child.x + child.actualWidth;
if (tmp > ar)
ar = tmp;
tmp = child.y + child.actualHeight;
if (tmp > ab)
ab = tmp;
}
aw = ar - ax;
ah = ab - ay;
}
else
{
ax = 0;
ay = 0;
aw = 0;
ah = 0;
}
SetBounds(ax, ay, aw, ah);
}
protected void SetBounds(float ax, float ay, float aw, float ah)
{
_boundsChanged = false;
if (scrollPane != null)
scrollPane.SetContentSize(Mathf.RoundToInt(ax + aw), Mathf.RoundToInt(ay + ah));
}
/// <summary>
/// Viwe port width of the container.
/// </summary>
public float viewWidth
{
get
{
if (scrollPane != null)
return scrollPane.viewWidth;
else
return this.width - _margin.left - _margin.right;
}
set
{
if (scrollPane != null)
scrollPane.viewWidth = value;
else
this.width = value + _margin.left + _margin.right;
}
}
/// <summary>
/// View port height of the container.
/// </summary>
public float viewHeight
{
get
{
if (scrollPane != null)
return scrollPane.viewHeight;
else
return this.height - _margin.top - _margin.bottom;
}
set
{
if (scrollPane != null)
scrollPane.viewHeight = value;
else
this.height = value + _margin.top + _margin.bottom;
}
}
virtual protected internal void GetSnappingPosition(ref float xValue, ref float yValue)
{
int cnt = _children.Count;
if (cnt == 0)
return;
EnsureBoundsCorrect();
GObject obj = null;
int i = 0;
if (yValue != 0)
{
for (; i < cnt; i++)
{
obj = _children[i];
if (yValue < obj.y)
{
if (i == 0)
{
yValue = 0;
break;
}
else
{
GObject prev = _children[i - 1];
if (yValue < prev.y + prev.height / 2) //top half part
yValue = prev.y;
else //bottom half part
yValue = obj.y;
break;
}
}
}
if (i == cnt)
yValue = obj.y;
}
if (xValue != 0)
{
if (i > 0)
i--;
for (; i < cnt; i++)
{
obj = _children[i];
if (xValue < obj.x)
{
if (i == 0)
{
xValue = 0;
break;
}
else
{
GObject prev = _children[i - 1];
if (xValue < prev.x + prev.width / 2) // top half part
xValue = prev.x;
else//bottom half part
xValue = obj.x;
break;
}
}
}
if (i == cnt)
xValue = obj.x;
}
}
internal void ChildSortingOrderChanged(GObject child, int oldValue, int newValue)
{
if (newValue == 0)
{
_sortingChildCount--;
SetChildIndex(child, _children.Count);
}
else
{
if (oldValue == 0)
_sortingChildCount++;
int oldIndex = _children.IndexOf(child);
int index = GetInsertPosForSortingChild(child);
if (oldIndex < index)
_SetChildIndex(child, oldIndex, index - 1);
else
_SetChildIndex(child, oldIndex, index);
}
}
/// <summary>
/// 每帧调用的一个回调。如果你要override,请记住以下两点:
/// 1、记得调用base.onUpdate;
/// 2、不要在方法里进行任何会更改显示列表的操作,例如AddChild、RemoveChild、visible等。
/// </summary>
virtual protected void OnUpdate()
{
if (_boundsChanged)
UpdateBounds();
}
override public void ConstructFromResource()
{
ConstructFromResource(null, 0);
}
internal void ConstructFromResource(List<GObject> objectPool, int poolIndex)
{
this.gameObjectName = packageItem.name;
if (!packageItem.translated)
{
packageItem.translated = true;
TranslationHelper.TranslateComponent(packageItem);
}
ByteBuffer buffer = packageItem.rawData;
buffer.Seek(0, 0);
underConstruct = true;
sourceWidth = buffer.ReadInt();
sourceHeight = buffer.ReadInt();
initWidth = sourceWidth;
initHeight = sourceHeight;
SetSize(sourceWidth, sourceHeight);
if (buffer.ReadBool())
{
minWidth = buffer.ReadInt();
maxWidth = buffer.ReadInt();
minHeight = buffer.ReadInt();
maxHeight = buffer.ReadInt();
}
if (buffer.ReadBool())
{
float f1 = buffer.ReadFloat();
float f2 = buffer.ReadFloat();
SetPivot(f1, f2, buffer.ReadBool());
}
if (buffer.ReadBool())
{
_margin.top = buffer.ReadInt();
_margin.bottom = buffer.ReadInt();
_margin.left = buffer.ReadInt();
_margin.right = buffer.ReadInt();
}
OverflowType overflow = (OverflowType)buffer.ReadByte();
if (overflow == OverflowType.Scroll)
{
int savedPos = buffer.position;
buffer.Seek(0, 7);
SetupScroll(buffer);
buffer.position = savedPos;
}
else
SetupOverflow(overflow);
if (buffer.ReadBool())
{
int i1 = buffer.ReadInt();
int i2 = buffer.ReadInt();
this.clipSoftness = new Vector2(i1, i2);
}
_buildingDisplayList = true;
buffer.Seek(0, 1);
int controllerCount = buffer.ReadShort();
for (int i = 0; i < controllerCount; i++)
{
int nextPos = buffer.ReadShort();
nextPos += buffer.position;
Controller controller = new Controller();
_controllers.Add(controller);
controller.parent = this;
controller.Setup(buffer);
buffer.position = nextPos;
}
buffer.Seek(0, 2);
GObject child;
int childCount = buffer.ReadShort();
for (int i = 0; i < childCount; i++)
{
int dataLen = buffer.ReadShort();
int curPos = buffer.position;
if (objectPool != null)
child = objectPool[poolIndex + i];
else
{
buffer.Seek(curPos, 0);
ObjectType type = (ObjectType)buffer.ReadByte();
string src = buffer.ReadS();
string pkgId = buffer.ReadS();
PackageItem pi = null;
if (src != null)
{
UIPackage pkg;
if (pkgId != null)
pkg = UIPackage.GetById(pkgId);
else
pkg = packageItem.owner;
pi = pkg != null ? pkg.GetItem(src) : null;
}
if (pi != null)
{
child = UIObjectFactory.NewObject(pi);
child.packageItem = pi;
child.ConstructFromResource();
}
else
child = UIObjectFactory.NewObject(type);
}
child.underConstruct = true;
child.Setup_BeforeAdd(buffer, curPos);
child.InternalSetParent(this);
_children.Add(child);
buffer.position = curPos + dataLen;
}
buffer.Seek(0, 3);
this.relations.Setup(buffer, true);
buffer.Seek(0, 2);
buffer.Skip(2);
for (int i = 0; i < childCount; i++)
{
int nextPos = buffer.ReadShort();
nextPos += buffer.position;
buffer.Seek(buffer.position, 3);
_children[i].relations.Setup(buffer, false);
buffer.position = nextPos;
}
buffer.Seek(0, 2);
buffer.Skip(2);
for (int i = 0; i < childCount; i++)
{
int nextPos = buffer.ReadShort();
nextPos += buffer.position;
child = _children[i];
child.Setup_AfterAdd(buffer, buffer.position);
child.underConstruct = false;
if (child.displayObject != null)
ToolSet.SetParent(child.displayObject.cachedTransform, this.displayObject.cachedTransform);
buffer.position = nextPos;
}
buffer.Seek(0, 4);
buffer.Skip(2); //customData
this.opaque = buffer.ReadBool();
int maskId = buffer.ReadShort();
if (maskId != -1)
{
this.mask = GetChildAt(maskId).displayObject;
if (buffer.ReadBool())
this.reversedMask = true;
}
string hitTestId = buffer.ReadS();
if (hitTestId != null)
{
PackageItem pi = packageItem.owner.GetItem(hitTestId);
if (pi != null && pi.pixelHitTestData != null)
{
int i1 = buffer.ReadInt();
int i2 = buffer.ReadInt();
this.rootContainer.hitArea = new PixelHitTest(pi.pixelHitTestData, i1, i2, sourceWidth, sourceHeight);
}
}
buffer.Seek(0, 5);
int transitionCount = buffer.ReadShort();
for (int i = 0; i < transitionCount; i++)
{
int nextPos = buffer.ReadShort();
nextPos += buffer.position;
Transition trans = new Transition(this);
trans.Setup(buffer);
_transitions.Add(trans);
buffer.position = nextPos;
}
if (_transitions.Count > 0)
{
this.onAddedToStage.Add(__addedToStage);
this.onRemovedFromStage.Add(__removedFromStage);
}
ApplyAllControllers();
_buildingDisplayList = false;
underConstruct = false;
BuildNativeDisplayList();
SetBoundsChangedFlag();
if (packageItem.objectType != ObjectType.Component)
ConstructExtension(buffer);
ConstructFromXML(null);
}
virtual protected void ConstructExtension(ByteBuffer buffer)
{
}
/// <summary>
/// Method for extensions to override
/// </summary>
/// <param name="xml"></param>
virtual public void ConstructFromXML(XML xml)
{
}
public override void Setup_AfterAdd(ByteBuffer buffer, int beginPos)
{
base.Setup_AfterAdd(buffer, beginPos);
buffer.Seek(beginPos, 4);
int pageController = buffer.ReadShort();
if (pageController != -1 && scrollPane != null && scrollPane.pageMode)
scrollPane.pageController = parent.GetControllerAt(pageController);
int cnt = buffer.ReadShort();
for (int i = 0; i < cnt; i++)
{
Controller cc = GetController(buffer.ReadS());
string pageId = buffer.ReadS();
if (cc != null)
cc.selectedPageId = pageId;
}
}
void __addedToStage()
{
int cnt = _transitions.Count;
for (int i = 0; i < cnt; ++i)
_transitions[i].OnOwnerAddedToStage();
}
void __removedFromStage()
{
int cnt = _transitions.Count;
for (int i = 0; i < cnt; ++i)
_transitions[i].OnOwnerRemovedFromStage();
}
}
}
| 23.134993 | 163 | 0.619901 | [
"MIT"
] | L-Fone/TowerDefense | Unity/Packages/ThirdParty/FairyGUI/Scripts/UI/GComponent.cs | 35,532 | C# |
// <auto-generated/>
#pragma warning disable 1591
#pragma warning disable 0414
#pragma warning disable 0649
#pragma warning disable 0169
namespace graphlibvisu
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
#nullable restore
#line 1 "/Users/marcelochsendorf/Downloads/MathematischeAlgorithmenSS2022/src/graphlibvisu/_Imports.razor"
using System.Net.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "/Users/marcelochsendorf/Downloads/MathematischeAlgorithmenSS2022/src/graphlibvisu/_Imports.razor"
using Microsoft.AspNetCore.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "/Users/marcelochsendorf/Downloads/MathematischeAlgorithmenSS2022/src/graphlibvisu/_Imports.razor"
using Microsoft.AspNetCore.Components.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "/Users/marcelochsendorf/Downloads/MathematischeAlgorithmenSS2022/src/graphlibvisu/_Imports.razor"
using Microsoft.AspNetCore.Components.Forms;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "/Users/marcelochsendorf/Downloads/MathematischeAlgorithmenSS2022/src/graphlibvisu/_Imports.razor"
using Microsoft.AspNetCore.Components.Routing;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "/Users/marcelochsendorf/Downloads/MathematischeAlgorithmenSS2022/src/graphlibvisu/_Imports.razor"
using Microsoft.AspNetCore.Components.Web;
#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "/Users/marcelochsendorf/Downloads/MathematischeAlgorithmenSS2022/src/graphlibvisu/_Imports.razor"
using Microsoft.JSInterop;
#line default
#line hidden
#nullable disable
#nullable restore
#line 8 "/Users/marcelochsendorf/Downloads/MathematischeAlgorithmenSS2022/src/graphlibvisu/_Imports.razor"
using graphlibvisu;
#line default
#line hidden
#nullable disable
#nullable restore
#line 9 "/Users/marcelochsendorf/Downloads/MathematischeAlgorithmenSS2022/src/graphlibvisu/_Imports.razor"
using graphlibvisu.Shared;
#line default
#line hidden
#nullable disable
public partial class _Imports : System.Object
{
#pragma warning disable 1998
protected void Execute()
{
}
#pragma warning restore 1998
}
}
#pragma warning restore 1591
| 27.522727 | 106 | 0.810074 | [
"MIT"
] | RBEGamer/MathematischeAlgorithmenSS2022 | src/graphlibvisu/obj/Debug/net6.0/RazorDeclaration/_Imports.razor.g.cs | 2,422 | C# |
// <auto-generated />
using Endpoint;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Endpoint.Migrations
{
[DbContext(typeof(CSVContext))]
partial class CSVContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "5.0.14");
modelBuilder.Entity("Endpoint.CSVRecord", b =>
{
b.Property<int>("CSVRecordId")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("AccountNumber")
.HasColumnType("INTEGER");
b.Property<double>("Amount")
.HasColumnType("REAL");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<string>("Reference")
.HasColumnType("TEXT");
b.Property<int>("SortCode")
.HasColumnType("INTEGER");
b.HasKey("CSVRecordId");
b.ToTable("CSVRecords");
});
#pragma warning restore 612, 618
}
}
}
| 30 | 69 | 0.528369 | [
"Apache-2.0"
] | aere69/APTTest | Story3/Endpoint/Migrations/CSVContextModelSnapshot.cs | 1,412 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using StackExchange.Redis;
namespace HotChocolate.Subscriptions.Redis
{
public class RedisEventStream
: IEventStream
{
private readonly IEventDescription _eventDescription;
private readonly ChannelMessageQueue _channel;
private readonly IPayloadSerializer _serializer;
private RedisEventStreamEnumerator _enumerator;
private bool _isCompleted;
public RedisEventStream(
IEventDescription eventDescription,
ChannelMessageQueue channel,
IPayloadSerializer serializer)
{
_eventDescription = eventDescription;
_channel = channel;
_serializer = serializer;
}
public IAsyncEnumerator<IEventMessage> GetAsyncEnumerator(
CancellationToken cancellationToken = default)
{
if (_isCompleted || (_enumerator is { IsCompleted: true }))
{
throw new InvalidOperationException(
"The stream has been completed and cannot be replayed.");
}
if (_enumerator is null)
{
_enumerator = new RedisEventStreamEnumerator(
_eventDescription,
_channel,
_serializer,
cancellationToken);
}
return _enumerator;
}
public async ValueTask CompleteAsync(
CancellationToken cancellationToken = default)
{
if (!_isCompleted)
{
await _channel.UnsubscribeAsync().ConfigureAwait(false);
_isCompleted = true;
}
}
private class RedisEventStreamEnumerator
: IAsyncEnumerator<IEventMessage>
{
private readonly IEventDescription _eventDescription;
private readonly ChannelMessageQueue _channel;
private readonly IPayloadSerializer _serializer;
private readonly CancellationToken _cancellationToken;
private bool _isCompleted;
public RedisEventStreamEnumerator(
IEventDescription eventDescription,
ChannelMessageQueue channel,
IPayloadSerializer serializer,
CancellationToken cancellationToken)
{
_eventDescription = eventDescription;
_channel = channel;
_serializer = serializer;
_cancellationToken = cancellationToken;
}
public IEventMessage Current { get; private set; }
internal bool IsCompleted => _isCompleted;
public async ValueTask<bool> MoveNextAsync()
{
if (_isCompleted || _channel.Completion.IsCompleted)
{
Current = null;
return false;
}
try
{
ChannelMessage message =
await _channel.ReadAsync(_cancellationToken).ConfigureAwait(false);
object payload = _serializer.Deserialize(message.Message);
Current = new EventMessage(message.Channel, payload);
return true;
}
catch
{
Current = null;
return false;
}
}
public async ValueTask DisposeAsync()
{
await _channel.UnsubscribeAsync().ConfigureAwait(false);
_isCompleted = true;
}
}
}
}
| 32.521739 | 91 | 0.55508 | [
"MIT"
] | Coldplayer1995/GraphQLTest | src/Core/Subscriptions.Redis/RedisEventStream.cs | 3,740 | C# |
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using MySqlConnector.Protocol;
using MySqlConnector.Protocol.Serialization;
namespace MySqlConnector.Core;
internal sealed class BatchedCommandPayloadCreator : ICommandPayloadCreator
{
public static ICommandPayloadCreator Instance { get; } = new BatchedCommandPayloadCreator();
public bool WriteQueryCommand(ref CommandListPosition commandListPosition, IDictionary<string, CachedProcedure?> cachedProcedures, ByteBufferWriter writer)
{
writer.Write((byte) CommandKind.Multi);
bool? firstResult = default;
bool wroteCommand;
ReadOnlySpan<byte> padding = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
do
{
// save room for command length
var position = writer.Position;
writer.Write(padding);
wroteCommand = SingleCommandPayloadCreator.Instance.WriteQueryCommand(ref commandListPosition, cachedProcedures, writer);
firstResult ??= wroteCommand;
// write command length
var commandLength = writer.Position - position - padding.Length;
var span = writer.ArraySegment.AsSpan().Slice(position);
span[0] = 0xFE;
BinaryPrimitives.WriteUInt64LittleEndian(span.Slice(1), (ulong) commandLength);
} while (wroteCommand);
// remove the padding that was saved for the final command (which wasn't written)
writer.TrimEnd(padding.Length);
return firstResult.Value;
}
}
| 34.65 | 156 | 0.76912 | [
"MIT"
] | qinqoushui/MySqlConnector | src/MySqlConnector/Core/BatchedCommandPayloadCreator.cs | 1,386 | 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.
namespace Iot.Device.Ft4222
{
/// <summary>
/// System clock rate
/// </summary>
internal enum FtClockRate
{
/// <summary>
/// 60 MHz
/// </summary>
Clock60MHz = 0,
/// <summary>
/// 24 MHz
/// </summary>
Clock24MHz,
/// <summary>
/// 48 MHz
/// </summary>
Clock48MHz,
/// <summary>
/// 80 MHz
/// </summary>
Clock80MHz,
}
}
| 22.733333 | 71 | 0.51173 | [
"MIT"
] | TobBrandt/iot | src/devices/Ft4222/FtClockRate.cs | 684 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ME2IniCompiler")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ME2IniCompiler")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a4ee3725-cbbc-4ad7-9eb1-fa3f0ce52c8c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.72973 | 84 | 0.748567 | [
"MIT"
] | ME3Tweaks/ME2CoalescedCompiler | ME2IniCompiler/Properties/AssemblyInfo.cs | 1,399 | C# |
using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CInteractionsManager : IGameSystem
{
[Ordinal(1)] [RED("activeInteraction")] public CHandle<CInteractionComponent> ActiveInteraction { get; set;}
public CInteractionsManager(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CInteractionsManager(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 32.48 | 132 | 0.741379 | [
"MIT"
] | DerinHalil/CP77Tools | CP77.CR2W/Types/W3/RTTIConvert/CInteractionsManager.cs | 788 | C# |
/* Copyright 2016-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver.Core.Connections;
using MongoDB.Driver.Core.Events;
using MongoDB.Driver.Core.Misc;
using MongoDB.Driver.Core.WireProtocol;
namespace MongoDB.Driver.Core.Servers
{
internal sealed class ServerMonitor : IServerMonitor
{
private readonly ServerDescription _baseDescription;
private volatile IConnection _connection;
private readonly IConnectionFactory _connectionFactory;
private CancellationTokenSource _heartbeatCancellationTokenSource; // used to cancel an ongoing heartbeat
private ServerDescription _currentDescription;
private readonly EndPoint _endPoint;
private BuildInfoResult _handshakeBuildInfoResult;
private HeartbeatDelay _heartbeatDelay;
private readonly object _lock = new object();
private readonly CancellationTokenSource _monitorCancellationTokenSource; // used to cancel the entire monitor
private readonly IRoundTripTimeMonitor _roundTripTimeMonitor;
private readonly ServerId _serverId;
private readonly InterlockedInt32 _state;
private readonly ServerMonitorSettings _serverMonitorSettings;
private readonly Action<ServerHeartbeatStartedEvent> _heartbeatStartedEventHandler;
private readonly Action<ServerHeartbeatSucceededEvent> _heartbeatSucceededEventHandler;
private readonly Action<ServerHeartbeatFailedEvent> _heartbeatFailedEventHandler;
private readonly Action<SdamInformationEvent> _sdamInformationEventHandler;
public event EventHandler<ServerDescriptionChangedEventArgs> DescriptionChanged;
public ServerMonitor(ServerId serverId, EndPoint endPoint, IConnectionFactory connectionFactory, ServerMonitorSettings serverMonitorSettings, IEventSubscriber eventSubscriber)
: this(
serverId,
endPoint,
connectionFactory,
serverMonitorSettings,
eventSubscriber,
roundTripTimeMonitor: new RoundTripTimeMonitor(
connectionFactory,
serverId,
endPoint,
Ensure.IsNotNull(serverMonitorSettings, nameof(serverMonitorSettings)).HeartbeatInterval))
{
}
public ServerMonitor(ServerId serverId, EndPoint endPoint, IConnectionFactory connectionFactory, ServerMonitorSettings serverMonitorSettings, IEventSubscriber eventSubscriber, IRoundTripTimeMonitor roundTripTimeMonitor)
{
_monitorCancellationTokenSource = new CancellationTokenSource();
_serverId = Ensure.IsNotNull(serverId, nameof(serverId));
_endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint));
_connectionFactory = Ensure.IsNotNull(connectionFactory, nameof(connectionFactory));
Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));
_serverMonitorSettings = Ensure.IsNotNull(serverMonitorSettings, nameof(serverMonitorSettings));
_baseDescription = _currentDescription = new ServerDescription(_serverId, endPoint, reasonChanged: "InitialDescription", heartbeatInterval: serverMonitorSettings.HeartbeatInterval);
_roundTripTimeMonitor = Ensure.IsNotNull(roundTripTimeMonitor, nameof(roundTripTimeMonitor));
_state = new InterlockedInt32(State.Initial);
eventSubscriber.TryGetEventHandler(out _heartbeatStartedEventHandler);
eventSubscriber.TryGetEventHandler(out _heartbeatSucceededEventHandler);
eventSubscriber.TryGetEventHandler(out _heartbeatFailedEventHandler);
eventSubscriber.TryGetEventHandler(out _sdamInformationEventHandler);
_heartbeatCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_monitorCancellationTokenSource.Token);
}
public ServerDescription Description => Interlocked.CompareExchange(ref _currentDescription, null, null);
public object Lock => _lock;
// public methods
public void CancelCurrentCheck()
{
IConnection toDispose = null;
lock (_lock)
{
if (!_heartbeatCancellationTokenSource.IsCancellationRequested)
{
_heartbeatCancellationTokenSource.Cancel();
_heartbeatCancellationTokenSource.Dispose();
_heartbeatCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_monitorCancellationTokenSource.Token);
// the previous isMaster cancelation token is still cancelled
toDispose = _connection;
_connection = null;
}
}
toDispose?.Dispose();
}
public void Dispose()
{
if (_state.TryChange(State.Disposed))
{
_monitorCancellationTokenSource.Cancel();
_monitorCancellationTokenSource.Dispose();
if (_connection != null)
{
_connection.Dispose();
}
_roundTripTimeMonitor.Dispose();
}
}
public void Initialize()
{
if (_state.TryChange(State.Initial, State.Open))
{
// the call to Task.Factory.StartNew is not normally recommended or necessary
// we are using it temporarily to work around a race condition in some of our tests
// the issue is that we set up some mocked async methods to return results immediately synchronously
// which results in the MonitorServerAsync method making more progress synchronously than the test expected
// by using Task.Factory.StartNew we introduce a short delay before the MonitorServerAsync Task starts executing
// the delay is whatever time it takes for the new Task to be activated and scheduled
// and the delay is usually long enough for the test to get past the race condition (though not guaranteed)
_ = Task.Factory.StartNew(() => _ = MonitorServerAsync().ConfigureAwait(false)).ConfigureAwait(false);
_ = _roundTripTimeMonitor.RunAsync().ConfigureAwait(false);
}
}
public void RequestHeartbeat()
{
ThrowIfNotOpen();
// CSHARP-3302: Accessing _heartbeatDelay inside _lock can lead to deadlock when processing concurrent heartbeats from old and new primaries.
// Accessing _heartbeatDelay outside of _lock avoids the deadlock and will at worst reference the previous delay
_heartbeatDelay?.RequestHeartbeat();
}
// private methods
private CommandWireProtocol<BsonDocument> InitializeIsMasterProtocol(IConnection connection)
{
BsonDocument isMasterCommand;
var commandResponseHandling = CommandResponseHandling.Return;
if (connection.Description.IsMasterResult.TopologyVersion != null)
{
connection.SetReadTimeout(_serverMonitorSettings.ConnectTimeout + _serverMonitorSettings.HeartbeatInterval);
commandResponseHandling = CommandResponseHandling.ExhaustAllowed;
var veryLargeHeartbeatInterval = TimeSpan.FromDays(1); // the server doesn't support Infinite value, so we set just a big enough value
var maxAwaitTime = _serverMonitorSettings.HeartbeatInterval == Timeout.InfiniteTimeSpan ? veryLargeHeartbeatInterval : _serverMonitorSettings.HeartbeatInterval;
isMasterCommand = IsMasterHelper.CreateCommand(connection.Description.IsMasterResult.TopologyVersion, maxAwaitTime);
}
else
{
isMasterCommand = IsMasterHelper.CreateCommand();
}
return IsMasterHelper.CreateProtocol(isMasterCommand, commandResponseHandling);
}
private async Task<IConnection> InitializeConnectionAsync(CancellationToken cancellationToken) // called setUpConnection in spec
{
var connection = _connectionFactory.CreateConnection(_serverId, _endPoint);
var stopwatch = Stopwatch.StartNew();
try
{
// if we are cancelling, it's because the server has
// been shut down and we really don't need to wait.
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
}
catch
{
// dispose it here because the _connection is not initialized yet
try { connection.Dispose(); } catch { }
throw;
}
stopwatch.Stop();
_roundTripTimeMonitor.AddSample(stopwatch.Elapsed);
return connection;
}
private async Task MonitorServerAsync()
{
var metronome = new Metronome(_serverMonitorSettings.HeartbeatInterval);
var monitorCancellationToken = _monitorCancellationTokenSource.Token;
while (!monitorCancellationToken.IsCancellationRequested)
{
try
{
CancellationToken cachedHeartbeatCancellationToken;
lock (_lock)
{
cachedHeartbeatCancellationToken = _heartbeatCancellationTokenSource.Token; // we want to cache the current cancellation token in case the source changes
}
try
{
await HeartbeatAsync(cachedHeartbeatCancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cachedHeartbeatCancellationToken.IsCancellationRequested)
{
// ignore OperationCanceledException when heartbeat cancellation is requested
}
catch (Exception unexpectedException)
{
// if we catch an exception here it's because of a bug in the driver (but we need to defend ourselves against that)
var handler = _sdamInformationEventHandler;
if (handler != null)
{
try
{
handler.Invoke(new SdamInformationEvent(() =>
string.Format(
"Unexpected exception in ServerMonitor.MonitorServerAsync: {0}",
unexpectedException.ToString())));
}
catch
{
// ignore any exceptions thrown by the handler (note: event handlers aren't supposed to throw exceptions)
}
}
// since an unexpected exception was thrown set the server description to Unknown (with the unexpected exception)
try
{
// keep this code as simple as possible to keep the surface area with any remaining possible bugs as small as possible
var newDescription = _baseDescription.WithHeartbeatException(unexpectedException); // not With in case the bug is in With
SetDescription(newDescription); // not SetDescriptionIfChanged in case the bug is in SetDescriptionIfChanged
}
catch
{
// if even the simple code in the try throws just give up (at least we've raised the unexpected exception via an SdamInformationEvent)
}
}
HeartbeatDelay newHeartbeatDelay;
lock (_lock)
{
newHeartbeatDelay = new HeartbeatDelay(metronome.GetNextTickDelay(), _serverMonitorSettings.MinHeartbeatInterval);
if (_heartbeatDelay != null)
{
_heartbeatDelay.Dispose();
}
_heartbeatDelay = newHeartbeatDelay;
}
await newHeartbeatDelay.Task.ConfigureAwait(false); // corresponds to wait method in spec
}
catch
{
// ignore these exceptions
}
}
}
private async Task HeartbeatAsync(CancellationToken cancellationToken)
{
CommandWireProtocol<BsonDocument> isMasterProtocol = null;
bool processAnother = true;
while (processAnother && !cancellationToken.IsCancellationRequested)
{
IsMasterResult heartbeatIsMasterResult = null;
Exception heartbeatException = null;
var previousDescription = _currentDescription;
try
{
IConnection connection;
lock (_lock)
{
connection = _connection;
}
if (connection == null)
{
var initializedConnection = await InitializeConnectionAsync(cancellationToken).ConfigureAwait(false);
lock (_lock)
{
if (_state.Value == State.Disposed)
{
try { initializedConnection.Dispose(); } catch { }
throw new OperationCanceledException("The ServerMonitor has been disposed.");
}
_connection = initializedConnection;
_handshakeBuildInfoResult = _connection.Description.BuildInfoResult;
heartbeatIsMasterResult = _connection.Description.IsMasterResult;
}
}
else
{
isMasterProtocol = isMasterProtocol ?? InitializeIsMasterProtocol(connection);
heartbeatIsMasterResult = await GetIsMasterResultAsync(connection, isMasterProtocol, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
IConnection toDispose = null;
lock (_lock)
{
isMasterProtocol = null;
heartbeatException = ex;
_roundTripTimeMonitor.Reset();
toDispose = _connection;
_connection = null;
}
toDispose?.Dispose();
}
lock (_lock)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
}
ServerDescription newDescription;
if (heartbeatIsMasterResult != null)
{
if (_handshakeBuildInfoResult == null)
{
// we can be here only if there is a bug in the driver
throw new ArgumentNullException("BuildInfo has been lost.");
}
var averageRoundTripTime = _roundTripTimeMonitor.Average;
var averageRoundTripTimeRounded = TimeSpan.FromMilliseconds(Math.Round(averageRoundTripTime.TotalMilliseconds));
newDescription = _baseDescription.With(
averageRoundTripTime: averageRoundTripTimeRounded,
canonicalEndPoint: heartbeatIsMasterResult.Me,
electionId: heartbeatIsMasterResult.ElectionId,
lastWriteTimestamp: heartbeatIsMasterResult.LastWriteTimestamp,
logicalSessionTimeout: heartbeatIsMasterResult.LogicalSessionTimeout,
maxBatchCount: heartbeatIsMasterResult.MaxBatchCount,
maxDocumentSize: heartbeatIsMasterResult.MaxDocumentSize,
maxMessageSize: heartbeatIsMasterResult.MaxMessageSize,
replicaSetConfig: heartbeatIsMasterResult.GetReplicaSetConfig(),
state: ServerState.Connected,
tags: heartbeatIsMasterResult.Tags,
topologyVersion: heartbeatIsMasterResult.TopologyVersion,
type: heartbeatIsMasterResult.ServerType,
version: _handshakeBuildInfoResult.ServerVersion,
wireVersionRange: new Range<int>(heartbeatIsMasterResult.MinWireVersion, heartbeatIsMasterResult.MaxWireVersion));
}
else
{
newDescription = _baseDescription.With(lastUpdateTimestamp: DateTime.UtcNow);
}
if (heartbeatException != null)
{
var topologyVersion = default(Optional<TopologyVersion>);
if (heartbeatException is MongoCommandException heartbeatCommandException)
{
topologyVersion = TopologyVersion.FromMongoCommandException(heartbeatCommandException);
}
newDescription = newDescription.With(heartbeatException: heartbeatException, topologyVersion: topologyVersion);
}
newDescription = newDescription.With(reasonChanged: "Heartbeat", lastHeartbeatTimestamp: DateTime.UtcNow);
lock (_lock)
{
cancellationToken.ThrowIfCancellationRequested();
SetDescription(newDescription);
}
processAnother =
// serverSupportsStreaming
(newDescription.Type != ServerType.Unknown && heartbeatIsMasterResult != null && heartbeatIsMasterResult.TopologyVersion != null) ||
// connectionIsStreaming
(isMasterProtocol != null && isMasterProtocol.MoreToCome) ||
// transitionedWithNetworkError
(IsNetworkError(heartbeatException) && previousDescription.Type != ServerType.Unknown);
}
bool IsNetworkError(Exception ex)
{
return ex is MongoConnectionException mongoConnectionException && mongoConnectionException.IsNetworkException;
}
}
private async Task<IsMasterResult> GetIsMasterResultAsync(
IConnection connection,
CommandWireProtocol<BsonDocument> isMasterProtocol,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (_heartbeatStartedEventHandler != null)
{
_heartbeatStartedEventHandler(new ServerHeartbeatStartedEvent(connection.ConnectionId, connection.Description.IsMasterResult.TopologyVersion != null));
}
try
{
var stopwatch = Stopwatch.StartNew();
var isMasterResult = await IsMasterHelper.GetResultAsync(connection, isMasterProtocol, cancellationToken).ConfigureAwait(false);
stopwatch.Stop();
if (_heartbeatSucceededEventHandler != null)
{
_heartbeatSucceededEventHandler(new ServerHeartbeatSucceededEvent(connection.ConnectionId, stopwatch.Elapsed, connection.Description.IsMasterResult.TopologyVersion != null));
}
return isMasterResult;
}
catch (Exception ex)
{
if (_heartbeatFailedEventHandler != null)
{
_heartbeatFailedEventHandler(new ServerHeartbeatFailedEvent(connection.ConnectionId, ex, connection.Description.IsMasterResult.TopologyVersion != null));
}
throw;
}
}
private void OnDescriptionChanged(ServerDescription oldDescription, ServerDescription newDescription)
{
var handler = DescriptionChanged;
if (handler != null)
{
var args = new ServerDescriptionChangedEventArgs(oldDescription, newDescription);
try { handler(this, args); }
catch { } // ignore exceptions
}
}
private void SetDescription(ServerDescription newDescription)
{
var oldDescription = Interlocked.CompareExchange(ref _currentDescription, null, null);
SetDescription(oldDescription, newDescription);
}
private void SetDescription(ServerDescription oldDescription, ServerDescription newDescription)
{
Interlocked.Exchange(ref _currentDescription, newDescription);
OnDescriptionChanged(oldDescription, newDescription);
}
private void ThrowIfDisposed()
{
if (_state.Value == State.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
private void ThrowIfNotOpen()
{
if (_state.Value != State.Open)
{
ThrowIfDisposed();
throw new InvalidOperationException("Server monitor must be initialized.");
}
}
// nested types
private static class State
{
public const int Initial = 0;
public const int Open = 1;
public const int Disposed = 2;
}
}
}
| 46.787755 | 227 | 0.5933 | [
"Apache-2.0"
] | jeremy-waguet/mongo-csharp-driver | src/MongoDB.Driver.Core/Core/Servers/ServerMonitor.cs | 22,928 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
//
// ███╗ ██╗ ██████╗ ████████╗██╗ ██████╗███████╗
// ████╗ ██║██╔═══██╗╚══██╔══╝██║██╔════╝██╔════╝
// ██╔██╗ ██║██║ ██║ ██║ ██║██║ █████╗
// ██║╚██╗██║██║ ██║ ██║ ██║██║ ██╔══╝
// ██║ ╚████║╚██████╔╝ ██║ ██║╚██████╗███████╗
// ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝
// ------------------------------------------------
//
// This file is automatically generated.
// Please do not edit these files manually.
//
// ------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text.Json;
using System.Text.Json.Serialization;
#nullable restore
namespace Elastic.Clients.Elasticsearch.License
{
public partial class License
{
[JsonInclude]
[JsonPropertyName("expiry_date_in_millis")]
public Elastic.Clients.Elasticsearch.EpochMillis ExpiryDateInMillis { get; set; }
[JsonInclude]
[JsonPropertyName("issue_date_in_millis")]
public Elastic.Clients.Elasticsearch.EpochMillis IssueDateInMillis { get; set; }
[JsonInclude]
[JsonPropertyName("issued_to")]
public string IssuedTo { get; set; }
[JsonInclude]
[JsonPropertyName("issuer")]
public string Issuer { get; set; }
[JsonInclude]
[JsonPropertyName("max_nodes")]
public long? MaxNodes { get; set; }
[JsonInclude]
[JsonPropertyName("max_resource_units")]
public long? MaxResourceUnits { get; set; }
[JsonInclude]
[JsonPropertyName("signature")]
public string Signature { get; set; }
[JsonInclude]
[JsonPropertyName("start_date_in_millis")]
public Elastic.Clients.Elasticsearch.EpochMillis? StartDateInMillis { get; set; }
[JsonInclude]
[JsonPropertyName("type")]
public Elastic.Clients.Elasticsearch.License.LicenseType Type { get; set; }
[JsonInclude]
[JsonPropertyName("uid")]
public string Uid { get; set; }
}
public sealed partial class LicenseDescriptor : SerializableDescriptorBase<LicenseDescriptor>
{
internal LicenseDescriptor(Action<LicenseDescriptor> configure) => configure.Invoke(this);
public LicenseDescriptor() : base()
{
}
private Elastic.Clients.Elasticsearch.EpochMillis ExpiryDateInMillisValue { get; set; }
private Elastic.Clients.Elasticsearch.EpochMillis IssueDateInMillisValue { get; set; }
private string IssuedToValue { get; set; }
private string IssuerValue { get; set; }
private long? MaxNodesValue { get; set; }
private long? MaxResourceUnitsValue { get; set; }
private string SignatureValue { get; set; }
private Elastic.Clients.Elasticsearch.EpochMillis? StartDateInMillisValue { get; set; }
private Elastic.Clients.Elasticsearch.License.LicenseType TypeValue { get; set; }
private string UidValue { get; set; }
public LicenseDescriptor ExpiryDateInMillis(Elastic.Clients.Elasticsearch.EpochMillis expiryDateInMillis)
{
ExpiryDateInMillisValue = expiryDateInMillis;
return Self;
}
public LicenseDescriptor IssueDateInMillis(Elastic.Clients.Elasticsearch.EpochMillis issueDateInMillis)
{
IssueDateInMillisValue = issueDateInMillis;
return Self;
}
public LicenseDescriptor IssuedTo(string issuedTo)
{
IssuedToValue = issuedTo;
return Self;
}
public LicenseDescriptor Issuer(string issuer)
{
IssuerValue = issuer;
return Self;
}
public LicenseDescriptor MaxNodes(long? maxNodes)
{
MaxNodesValue = maxNodes;
return Self;
}
public LicenseDescriptor MaxResourceUnits(long? maxResourceUnits)
{
MaxResourceUnitsValue = maxResourceUnits;
return Self;
}
public LicenseDescriptor Signature(string signature)
{
SignatureValue = signature;
return Self;
}
public LicenseDescriptor StartDateInMillis(Elastic.Clients.Elasticsearch.EpochMillis? startDateInMillis)
{
StartDateInMillisValue = startDateInMillis;
return Self;
}
public LicenseDescriptor Type(Elastic.Clients.Elasticsearch.License.LicenseType type)
{
TypeValue = type;
return Self;
}
public LicenseDescriptor Uid(string uid)
{
UidValue = uid;
return Self;
}
protected override void Serialize(Utf8JsonWriter writer, JsonSerializerOptions options, IElasticsearchClientSettings settings)
{
writer.WriteStartObject();
writer.WritePropertyName("expiry_date_in_millis");
JsonSerializer.Serialize(writer, ExpiryDateInMillisValue, options);
writer.WritePropertyName("issue_date_in_millis");
JsonSerializer.Serialize(writer, IssueDateInMillisValue, options);
writer.WritePropertyName("issued_to");
writer.WriteStringValue(IssuedToValue);
writer.WritePropertyName("issuer");
writer.WriteStringValue(IssuerValue);
if (MaxNodesValue.HasValue)
{
writer.WritePropertyName("max_nodes");
writer.WriteNumberValue(MaxNodesValue.Value);
}
if (MaxResourceUnitsValue.HasValue)
{
writer.WritePropertyName("max_resource_units");
writer.WriteNumberValue(MaxResourceUnitsValue.Value);
}
writer.WritePropertyName("signature");
writer.WriteStringValue(SignatureValue);
if (StartDateInMillisValue is not null)
{
writer.WritePropertyName("start_date_in_millis");
JsonSerializer.Serialize(writer, StartDateInMillisValue, options);
}
writer.WritePropertyName("type");
JsonSerializer.Serialize(writer, TypeValue, options);
writer.WritePropertyName("uid");
writer.WriteStringValue(UidValue);
writer.WriteEndObject();
}
}
} | 28.651282 | 128 | 0.702166 | [
"Apache-2.0"
] | SimonCropp/elasticsearch-net | src/Elastic.Clients.Elasticsearch/_Generated/Types/License/License.g.cs | 6,033 | 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 Microsoft.ML.Runtime.Data;
using Microsoft.ML.Trainers.FastTree;
using Microsoft.ML.Runtime.Internal.Calibration;
using Microsoft.ML.Runtime.Internal.Internallearn;
using Microsoft.ML.Runtime.Learners;
using Microsoft.ML.Runtime.RunTests;
using Microsoft.ML.Runtime.TextAnalytics;
using System.Collections.Generic;
using Xunit;
namespace Microsoft.ML.Tests.Scenarios.Api
{
public partial class ApiScenariosTests
{
/// <summary>
/// Introspective training: Models that produce outputs and are otherwise black boxes are of limited use;
/// it is also necessary often to understand at least to some degree what was learnt. To outline critical
/// scenarios that have come up multiple times:
/// *) When I train a linear model, I should be able to inspect coefficients.
/// *) The tree ensemble learners, I should be able to inspect the trees.
/// *) The LDA transform, I should be able to inspect the topics.
/// I view it as essential from a usability perspective that this be discoverable to someone without
/// having to read documentation. For example, if I have var lda = new LdaTransform().Fit(data)(I don't insist on that
/// exact signature, just giving the idea), then if I were to type lda.
/// In Visual Studio, one of the auto-complete targets should be something like GetTopics.
/// </summary>
[Fact]
public void New_IntrospectiveTraining()
{
var ml = new MLContext(seed: 1, conc: 1);
var data = ml.Data.CreateTextReader(TestDatasets.Sentiment.GetLoaderColumns(), hasHeader: true)
.Read(GetDataPath(TestDatasets.Sentiment.trainFilename));
var pipeline = ml.Transforms.Text.FeaturizeText("SentimentText", "Features")
.AppendCacheCheckpoint(ml)
.Append(ml.BinaryClassification.Trainers.StochasticDualCoordinateAscent("Label", "Features", advancedSettings: s => s.NumThreads = 1));
// Train.
var model = pipeline.Fit(data);
// Get feature weights.
VBuffer<float> weights = default;
model.LastTransformer.Model.GetFeatureWeights(ref weights);
}
}
}
| 45.648148 | 151 | 0.682353 | [
"MIT"
] | Zruty0/machinelearning | test/Microsoft.ML.Tests/Scenarios/Api/Estimators/IntrospectiveTraining.cs | 2,467 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\dxgiddi.h(862,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct DXGIDDI_MULTIPLANE_OVERLAY_ALLOCATION_INFO
{
public uint PresentAllocation;
public uint SubResourceIndex;
}
}
| 26.571429 | 84 | 0.712366 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/DXGIDDI_MULTIPLANE_OVERLAY_ALLOCATION_INFO.cs | 374 | C# |
using System;
using SharpFunction.Universal;
using static SharpFunction.Universal.EnumHelper;
namespace SharpFunction.Commands.Minecraft
{
/// <summary>
/// Represents /execute command. Equal to Minecraft's <code>/execute {tons of params}</code>
/// </summary>
public sealed class Execute : ICommand
{
/// <summary>
/// Compiled command string
/// </summary>
/// <value></value>
public string Compiled { get; private set; }
/// <summary>
/// Compiles the /execute command.
/// </summary>
/// <param name="params">Parameters for '/execute' command</param>
public void Compile(ExecuteParameters @params)
{
Compiled = @params.String;
}
}
/// <summary>
/// Represents collection of conditions for /execute command with most of it being metadata
/// </summary>
public struct ExecuteParameters
{
internal string String { get; }
#nullable enable
/// <summary>
/// Execute command has a very complex syntax tree<br />
/// <b>Execute parameters</b>
/// <para>
/// <para>
/// 1. <see cref="ExecuteCondition.Align" /><br />
/// Updates the command's execution position, aligning to its current block position.<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should have swizzle of coordinates.<br />
/// Example: "xzy" or "yz"
/// </para>
/// <para>
/// 2. <see cref="ExecuteCondition.Anchored" /><br />
/// Sets the execution anchor to the eyes or feet. Defaults to feet.<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="AnchorCondition" /><br />
/// </para>
/// <para>
/// 3. <see cref="ExecuteCondition.As" /><br />
/// Sets the command's executor to target entity, without
/// changing execution position, rotation, dimension, or anchor<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="EntitySelector" />
/// </para>
/// <para>
/// 4. <see cref="ExecuteCondition.At" /><br />
/// Sets the execution position, rotation, and dimension to
/// match those of an entity; does not change executor.<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="EntitySelector" />
/// </para>
/// <para>
/// 5. <see cref="ExecuteCondition.Facing" /><br />
/// Sets the execution rotation to face a given point, as
/// viewed from its anchor (either the eyes or the feet)<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="FacingCondition" /><br />
/// First option (<see cref="FacingCondition.Position" />): <br />
/// <paramref name="extraParameters" />[1] should be <see cref="Vector3" />)<br />
/// Second option (<see cref="FacingCondition.Entity" />): <br />
/// <paramref name="extraParameters" />[1] should be <see cref="EntitySelector" /> entity<br />
/// <paramref name="extraParameters" />[2] should be <see cref="AnchorCondition" /> anchor <br />
/// </para>
/// <para>
/// 6. <see cref="ExecuteCondition.In" /><br />
/// Sets the execution dimension and position<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be dimension
/// string ("overworld"|"the_nether"|"the_end"|"custom dimension")<br />
/// </para>
/// <para>
/// 7. <see cref="ExecuteCondition.Positioned" /><br />
/// Sets the execution position, without changing execution
/// rotation or dimension;<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="Vector3" />
/// </para>
/// <para>
/// 8. <see cref="ExecuteCondition.PositionedAs" /><br />
/// Works like <see cref="ExecuteCondition.Positioned" /> but anchors at
/// entity<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="EntitySelector" />
/// </para>
/// <para>
/// 9. <see cref="ExecuteCondition.Rotated" /><br />
/// Sets the execution rotation<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be yaw float<br />
/// <paramref name="extraParameters" />[1] should be pitch float<br />
/// </para>
/// <para>
/// 10. <see cref="ExecuteCondition.RotatedAs" /><br />
/// Sets the execution rotation to entity's rotation<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="EntitySelector" /> entity<br />
/// </para>
/// </para>
/// <b>Execute Conditions (if/unless)</b>
/// <para>
/// <para>
/// 1. <see cref="ExecuteSubcondition.Block" /><br />
/// Compares the block at a given position to
/// a given block ID or block tag.<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="Vector3" /><br />
/// <paramref name="extraParameters" />[1] should be string block predicate tag in format of
/// namespaced_id[predicate_states]{nbt_tags}<br />
/// </para>
/// <para>
/// 2. <see cref="ExecuteSubcondition.Blocks" /><br />
/// Compares the blocks in two equally sized volumes<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="Vector3" /> array, where [0] is beginning of
/// volume,
/// [1] is end of volume and [2] is destination of volume<br />
/// <paramref name="extraParameters" />[1] should be <see cref="ScanningMode" /><br />
/// </para>
/// <para>
/// 3. <see cref="ExecuteSubcondition.NBTData" /><br />
/// Checks whether the targeted block, entity or
/// storage has any data tag for a given path<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="NBTDataType" />
/// and depending on it should be <paramref name="extraParameters" />[1]<br />
/// <paramref name="extraParameters" />[2] should always be nbt data string to check for.<br />
/// 3.1. <see cref="NBTDataType.Block" /><br />
/// <paramref name="extraParameters" />[1] should be <see cref="Vector3" /> block pos to check<br />
/// 3.2. <see cref="NBTDataType.Entity" /><br />
/// <paramref name="extraParameters" />[1] should be <see cref="EntitySelector" /> entity to check<br />
/// 3.3. <see cref="NBTDataType.Storage" /><br />
/// <paramref name="extraParameters" />[1] should be string namespaced id to check<br />
/// </para>
/// <para>
/// 4. <see cref="ExecuteSubcondition.Entity" /><br />
/// Checks whether one or more entities exist.<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="EntitySelector" /> entity to check for.<br />
/// </para>
/// <para>
/// 5. <see cref="ExecuteSubcondition.Predicate" /><br />
/// Checks whether the predicate evaluates to a positive result.<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be namespaced id for predicate to seek.<br />
/// </para>
/// <para>
/// 6. <see cref="ExecuteSubcondition.Scoreboard" /><br />
/// Check whether a score has the specific relation to
/// another score, or whether it is in a given range.<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="ScoreComparation" />
/// and other params will be dependant on it's value.<br />
/// 6.1. <see cref="ScoreComparation.Comparation" /><br />
/// Other params should go this way:<br />
/// <see cref="EntitySelector" /> holder of the objective to be compared.<br />
/// <see cref="string" /> name of the objective to be compared the value.<br />
/// <see cref="Comparator" /> comparator to compare the value.<br />
/// <see cref="EntitySelector" /> holder of the objective to compare.<br />
/// <see cref="string" /> name of the objective to compare the value.<br />
/// 6.2. <see cref="ScoreComparation.Match" /><br />
/// Other params should go this way:<br />
/// <see cref="EntitySelector" /> holder of the objective to be matched.<br />
/// <see cref="string" /> name of the objective to be matched the value.<br />
/// </para>
/// </para>
/// <para>
/// <b>Execute Store (result|success)</b>
/// <para>
/// 1. <see cref="ExecuteStore.Block" /><br />
/// Saves the final command's return value as
/// tag data within a block entity. Store as a
/// byte, short, int, long, float, or double.<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="Vector3" /> of block<br />
/// <paramref name="extraParameters" />[1] should be <see cref="NBTPath" /> to store data<br />
/// <paramref name="extraParameters" />[2] should be <see cref="Type" /> of data to be stored<br />
/// <paramref name="extraParameters" />[3] should be <see cref="double" /> scale for value to be rounded if it
/// is decimal<br />
/// </para>
/// <para>
/// 2. <see cref="ExecuteStore.Bossbar" /><br />
/// Saves the final command's return value in either
/// a bossbar's current value or its maximum value<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="string" /> namespaced id of bossbar to store
/// data<br />
/// <paramref name="extraParameters" />[1] should be <see cref="BossbarOverwrite" /> of value to overwrite
/// (current or max)<br />
/// </para>
/// <para>
/// 3. <see cref="ExecuteStore.Entity" /><br />
/// Save the final command's return value in one of an entity's data
/// tags. Store as a byte, short, int, long, float, or double.
/// Like the /data command, /execute store entity cannot modify player's NBT.<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="EntitySelector" /> of entity<br />
/// <paramref name="extraParameters" />[1] should be <see cref="NBTPath" /> to store data<br />
/// <paramref name="extraParameters" />[2] should be <see cref="Type" /> of data to be stored<br />
/// <paramref name="extraParameters" />[3] should be <see cref="double" /> scale for value to be rounded if it
/// is decimal<br />
/// </para>
/// <para>
/// 4. <see cref="ExecuteStore.Score" /><br />
/// Overrides the score held by targets on the given
/// objective with the final command's return value.<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="EntitySelector" /> of score holder<br />
/// <paramref name="extraParameters" />[1] should be <see cref="string" /> namespaced id of scoreboard<br />
/// </para>
/// <para>
/// 5. <see cref="ExecuteStore.Storage" /><br />
/// Uses the path within storage target to store the return value in.
/// Store as a byte, short, int, long, float, or double.
/// If the storage does not yet exist, it gets created.<br />
/// <i>Syntax:</i><br />
/// <paramref name="extraParameters" />[0] should be <see cref="string" /> namespaced id of storage to store
/// data<br />
/// <paramref name="extraParameters" />[1] should be <see cref="NBTPath" /> to store data<br />
/// <paramref name="extraParameters" />[2] should be <see cref="Type" /> of data to be stored<br />
/// <paramref name="extraParameters" />[3] should be <see cref="double" /> scale for value to be rounded if it
/// is decimal<br />
/// </para>
/// </para>
/// </summary>
/// <remarks>
/// Most information taken from <a href="https://minecraft.fandom.com/wiki/Commands/execute">Minecraft Wiki page</a>.
/// <br />
/// </remarks>
/// <param name="cmd">Compiled command to be ran</param>
/// <param name="cond">Extra execute params</param>
/// <param name="oper">Execute operator (if|unless)</param>
/// <param name="subcond">Condition to execute the command. See <paramref name="oper" /></param>
/// <param name="store">Specific data that should be stored after command execution</param>
/// <param name="cont">What the command should store</param>
/// <param name="extraParameters">See summary on method</param>
public ExecuteParameters(
ICommand cmd,
ExecuteCondition? cond = null,
ExecuteOperator? oper = null,
ExecuteSubcondition? subcond = null,
ExecuteStore? store = null,
ExecuteStoreContainer? cont = null,
params object[]? extraParameters
)
{
String = "/execute";
// Create base stuff to build templates from later
string tmp = cmd.Compiled.StartsWith("/") ? cmd.Compiled.Remove(0, 1) : cmd.Compiled;
string tmpRun = $"run {tmp}";
tmp = !cond.Equals(null) ? cond.GetStringValue() : "";
string tmpCond = $"{tmp}";
tmp = !oper.Equals(null) ? oper.GetStringValue() : "";
string tmpOper = $"{tmp}";
tmp = !subcond.Equals(null) ? subcond.GetStringValue() : "";
tmpOper += $" {tmp}";
tmp = !cont.Equals(null) ? cont.GetStringValue() : "";
string tmpStore = !cont.Equals(null) ? $"store {tmp}" : "";
tmp = !store.Equals(null) ? store.GetStringValue() : "";
tmpStore += !store.Equals(null) ? $" {tmp}" : "";
// Switch through all the enumerators and increase current extraParameters node
var i = 0;
if (extraParameters != null)
try
{
if (cond != null)
switch (cond)
{
case ExecuteCondition.Align:
var swizzle = (string) extraParameters[i];
tmpCond += $" {swizzle}";
i++;
break;
case ExecuteCondition.Anchored:
var tmpc = (AnchorCondition) extraParameters[i];
tmpCond += $" {tmpc.GetStringValue()}";
i++;
break;
case ExecuteCondition.As:
var tmpt = (EntitySelector) extraParameters[i];
tmpCond += $" {tmpt.String()}";
i++;
break;
case ExecuteCondition.At:
goto case ExecuteCondition.As;
case ExecuteCondition.Facing:
var tmpfc = (FacingCondition) extraParameters[i];
i++;
switch (tmpfc)
{
case FacingCondition.Position:
tmpCond += $" {((Vector3) extraParameters[i]).String()}";
i++;
break;
case FacingCondition.Entity:
tmpCond +=
$" entity {((EntitySelector) extraParameters[i]).String()} {((AnchorCondition) extraParameters[i + 1]).GetStringValue()}";
i = i + 2;
break;
}
break;
case ExecuteCondition.In:
var tmpdn = (string) extraParameters[i];
tmpCond += $" {tmpdn}";
i++;
break;
case ExecuteCondition.Positioned:
var tmppv = (Vector3) extraParameters[i];
tmpCond += $" {tmppv.String()}";
i++;
break;
case ExecuteCondition.PositionedAs:
var tmpes = (EntitySelector) extraParameters[i];
tmpCond += $" {tmpes.String()}";
i++;
break;
case ExecuteCondition.Rotated:
var tmpy = (float) extraParameters[i];
i++;
var tmpp = (float) extraParameters[i];
tmpCond +=
$" {VectorHelper.DecimalToMCString(tmpy)} {VectorHelper.DecimalToMCString(tmpp)}";
i++;
break;
case ExecuteCondition.RotatedAs:
var tmpes2 = (EntitySelector) extraParameters[i];
tmpCond += $" {tmpes2.String()}";
i++;
break;
case ExecuteCondition.None:
tmpCond += "";
i++;
break;
}
if (oper != null && subcond != null)
switch (subcond)
{
case ExecuteSubcondition.Block:
var tmpv = (Vector3) extraParameters[i];
i++;
var tmpbn = (string) extraParameters[i];
i++;
tmpOper += $" {tmpv.String()} {tmpbn}";
break;
case ExecuteSubcondition.Blocks:
var tmpvs = (Vector3[]) extraParameters[i];
i++;
var scanMode = (ScanningMode) extraParameters[i];
i++;
tmpOper +=
$" {tmpvs[0].String()} {tmpvs[1].String()} {tmpvs[2].String()} {scanMode.GetStringValue()}";
break;
case ExecuteSubcondition.NBTData:
var tmpe = (NBTDataType) extraParameters[i];
i++;
string stmp22;
switch (tmpe)
{
case NBTDataType.Block:
var tmp2 = (Vector3) extraParameters[i];
i++;
stmp22 = $" block {tmp2.String()}";
break;
case NBTDataType.Entity:
var tmp22 = (EntitySelector) extraParameters[i];
i++;
stmp22 = $" entity {tmp22.String()}";
break;
case NBTDataType.Storage:
var tmp222 = (string) extraParameters[i];
i++;
stmp22 = $" storage {tmp222}";
break;
default:
stmp22 = "";
break;
}
tmpOper += $" {stmp22} {(string) extraParameters[i]}";
i++;
break;
case ExecuteSubcondition.Entity:
var atmp = (EntitySelector) extraParameters[i];
i++;
tmpOper += $" {atmp.String()}";
break;
case ExecuteSubcondition.Predicate:
var ptmp = (string) extraParameters[i];
i++;
tmpOper += $" {ptmp}";
break;
case ExecuteSubcondition.Scoreboard:
string fstmp;
var yatmp = (ScoreComparation) extraParameters[i];
i++;
switch (yatmp)
{
case ScoreComparation.Comparation:
var ettmp = (EntitySelector) extraParameters[i];
i++;
var objtmp = (string) extraParameters[i];
i++;
var ctmp = (Comparator) extraParameters[i];
i++;
var srchtmp = (EntitySelector) extraParameters[i];
i++;
var srctmp = (string) extraParameters[i];
i++;
fstmp =
$" {ettmp.String()} {objtmp} {ctmp.GetStringValue()} {srchtmp} {srctmp}";
break;
case ScoreComparation.Match:
var ex1 = (EntitySelector) extraParameters[i];
i++;
var ex2 = (string) extraParameters[i];
i++;
var comptmp = (string) extraParameters[i];
i++;
fstmp = $"{ex1.String()} {ex2} matches {comptmp}";
break;
default:
fstmp = "";
break;
}
tmpOper += $" {fstmp}";
break;
case ExecuteSubcondition.None:
tmpOper += "";
break;
default:
goto case ExecuteSubcondition.None;
}
if (store != null && cont != null)
{
string fstr = string.Empty;
switch (store)
{
case ExecuteStore.Block:
var tmpp = (Vector3) extraParameters[i];
i++;
var tmpnp = (NBTPath) extraParameters[i];
i++;
var tmpt = (Type) extraParameters[i];
i++;
var tmps = (double) extraParameters[i];
i++;
fstr = $" {tmpp.String()} {tmpnp.JSON} {tmpt} {VectorHelper.DecimalToMCString(tmps)}";
break;
case ExecuteStore.Bossbar:
var tmpid = (string) extraParameters[i];
i++;
var tmpbo = (BossbarOverwrite) extraParameters[i];
i++;
fstr = $" {tmpid} {tmpbo.GetStringValue()}";
break;
case ExecuteStore.Entity:
var tmps2 = (EntitySelector) extraParameters[i];
i++;
var tmpnp2 = (NBTPath) extraParameters[i];
i++;
var tmpt2 = (Type) extraParameters[i];
i++;
var tmpsc = (double) extraParameters[i];
i++;
fstr =
$" {tmps2.String()} {tmpnp2.JSON} {tmpt2} {VectorHelper.DecimalToMCString(tmpsc)}";
break;
case ExecuteStore.Score:
var tmps22 = (EntitySelector) extraParameters[i];
i++;
var tmpobj = (string) extraParameters[i];
i++;
fstr = $" {tmps22.String()} {tmpobj}";
break;
case ExecuteStore.Storage:
var tmptr = (string) extraParameters[i];
i++;
var tmpnp22 = (NBTPath) extraParameters[i];
i++;
var tmpt222 = (Type) extraParameters[i];
i++;
var tmpscr = (double) extraParameters[i];
i++;
fstr = $" {tmptr} {tmpnp22.JSON} {tmpt222} {VectorHelper.DecimalToMCString(tmpscr)}";
break;
case ExecuteStore.None:
fstr = "";
break;
default:
goto case ExecuteStore.None;
}
}
String += $" {tmpCond} {tmpOper} {tmpRun} {tmpStore}".Replace(" ", " ");
}
// if wrong cast exception appears it means that provided object is invalid.
catch (InvalidCastException ice)
{
throw new ArgumentException(
$"Wrong argument at {nameof(extraParameters)}. More information: {ice.Message}");
}
// handle any other exception so the code won't break
catch (Exception e)
{
throw new ArgumentException(
$"A fatal error occurred (probably) because of parameter {nameof(extraParameters)}. More information: {e.Message}");
}
}
#nullable disable
}
/// <summary>
/// Represents enumerated condition for execute command
/// </summary>
public enum ExecuteCondition
{
/// <summary>
/// align as swizzle of coordinates
/// </summary>
[EnumValue("align")] Align,
/// <summary>
/// anchor to entity/pos
/// </summary>
[EnumValue("anchored")] Anchored,
/// <summary>
/// execute as entity
/// </summary>
[EnumValue("as")] As,
/// <summary>
/// execute at entity/pos
/// </summary>
[EnumValue("at")] At,
/// <summary>
/// execute facing entity/pos
/// </summary>
[EnumValue("facing")] Facing,
/// <summary>
/// execute in
/// </summary>
[EnumValue("in")] In,
/// <summary>
/// execute positioned at pos
/// </summary>
[EnumValue("positoned")] Positioned,
/// <summary>
/// execute positioned as entity
/// </summary>
[EnumValue("positoned as")] PositionedAs,
/// <summary>
/// execute rotated with certain yaw and pitch
/// </summary>
[EnumValue("rotated")] Rotated,
/// <summary>
/// execute rotated as entity
/// </summary>
[EnumValue("rotated as")] RotatedAs,
/// <summary>
/// </summary>
[EnumValue("")] None
}
/// <summary>
/// Represents type of facing
/// </summary>
public enum FacingCondition
{
[EnumValue("")] Position,
[EnumValue("entity")] Entity
}
/// <summary>
/// Represents type of anchor
/// </summary>
public enum AnchorCondition
{
[EnumValue("eyes")] Eyes,
[EnumValue("feet")] Feet
}
/// <summary>
/// Represents scanning mode for execute command
/// </summary>
public enum ScanningMode
{
[EnumValue("all")] All,
[EnumValue("masked")] NoAir
}
/// <summary>
/// Represents operator for /execute command
/// </summary>
public enum ExecuteOperator
{
[EnumValue("if")] If,
[EnumValue("unless")] Unless,
[EnumValue("")] None
}
/// <summary>
/// Represents subcondition for execute command to be executed with
/// </summary>
public enum ExecuteSubcondition
{
[EnumValue("block")] Block,
[EnumValue("blocks")] Blocks,
[EnumValue("data")] NBTData,
[EnumValue("entity")] Entity,
[EnumValue("predicate")] Predicate,
[EnumValue("score")] Scoreboard,
[EnumValue("")] None
}
/// <summary>
/// Represents /execute store subcommand
/// </summary>
public enum ExecuteStore
{
[EnumValue("block")] Block,
[EnumValue("bossbar")] Bossbar,
[EnumValue("entity")] Entity,
[EnumValue("score")] Score,
[EnumValue("storage")] Storage,
[EnumValue("")] None
}
/// <summary>
/// Represents data stored in /execute store command
/// </summary>
public enum ExecuteStoreContainer
{
[EnumValue("result")] Result,
[EnumValue("success")] Success,
[EnumValue("")] None
}
/// <summary>
/// Represents type of data in execute command
/// </summary>
public enum NBTDataType
{
[EnumValue("block")] Block,
[EnumValue("entity")] Entity,
[EnumValue("storage")] Storage
}
/// <summary>
/// Represents comparator oper to compare values
/// </summary>
public enum Comparator
{
[EnumValue("<")] Less,
[EnumValue("<=")] LessOrEqual,
[EnumValue("==")] Equal,
[EnumValue("=>")] MoreOrEqual,
[EnumValue(">")] More
}
/// <summary>
/// Represents type of comparing scoreboards
/// </summary>
public enum ScoreComparation
{
[EnumValue("")] Comparation,
[EnumValue("matches")] Match
}
/// <summary>
/// Specifies which value of boss bar to overwrite
/// </summary>
public enum BossbarOverwrite
{
[EnumValue("max")] MaxValue,
[EnumValue("value")] CurrentValue
}
} | 49.123404 | 166 | 0.416118 | [
"MIT"
] | Maxuss/SharpFunction | SharpFunction/Commands/Minecraft/Execute.cs | 34,634 | C# |
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace NgrokApi
{
// <summary>
// SSH Host Certificates along with the corresponding private key allows an SSH
// server to assert its authenticity to connecting SSH clients who trust the
// SSH Certificate Authority that was used to sign the certificate.
// </summary>
public class SshHostCertificates
{
private IApiHttpClient apiClient;
internal SshHostCertificates(IApiHttpClient apiClient)
{
this.apiClient = apiClient;
}
// <summary>
// Create a new SSH Host Certificate
// </summary>
//
// https://ngrok.com/docs/api#api-ssh-host-certificates-create
public async Task<SshHostCertificate> Create(SshHostCertificateCreate arg)
{
Dictionary<string, string> query = null;
SshHostCertificateCreate body = null;
body = arg;
return await apiClient.Do<SshHostCertificate>(
path: $"/ssh_host_certificates",
method: new HttpMethod("post"),
body: body,
query: query
);
}
// <summary>
// Delete an SSH Host Certificate
// </summary>
//
// https://ngrok.com/docs/api#api-ssh-host-certificates-delete
public async Task Delete(string id)
{
var arg = new Item() { Id = id };
Dictionary<string, string> query = null;
Item body = null;
query = new Dictionary<string, string>()
{
};
await apiClient.DoNoReturnBody<Empty>(
path: $"/ssh_host_certificates/{arg.Id}",
method: new HttpMethod("delete"),
body: body,
query: query
);
}
// <summary>
// Get detailed information about an SSH Host Certficate
// </summary>
//
// https://ngrok.com/docs/api#api-ssh-host-certificates-get
public async Task<SshHostCertificate> Get(string id)
{
var arg = new Item() { Id = id };
Dictionary<string, string> query = null;
Item body = null;
query = new Dictionary<string, string>()
{
};
return await apiClient.Do<SshHostCertificate>(
path: $"/ssh_host_certificates/{arg.Id}",
method: new HttpMethod("get"),
body: body,
query: query
);
}
private async Task<SshHostCertificateList> ListPage(Paging arg)
{
Dictionary<string, string> query = null;
Paging body = null;
query = new Dictionary<string, string>()
{
["before_id"] = arg.BeforeId,
["limit"] = arg.Limit,
};
return await apiClient.Do<SshHostCertificateList>(
path: $"/ssh_host_certificates",
method: new HttpMethod("get"),
body: body,
query: query
);
}
// <summary>
// List all SSH Host Certificates issued on this account
// </summary>
//
// https://ngrok.com/docs/api#api-ssh-host-certificates-list
public IAsyncEnumerable<SshHostCertificate> List(string limit = null, string beforeId = null)
{
return new Iterator<SshHostCertificate>(beforeId, async lastId =>
{
var result = await this.ListPage(new Paging()
{
BeforeId = lastId,
Limit = limit,
});
return result.SshHostCertificates;
});
}
// <summary>
// Update an SSH Host Certificate
// </summary>
//
// https://ngrok.com/docs/api#api-ssh-host-certificates-update
public async Task<SshHostCertificate> Update(SshHostCertificateUpdate arg)
{
Dictionary<string, string> query = null;
SshHostCertificateUpdate body = null;
body = arg;
return await apiClient.Do<SshHostCertificate>(
path: $"/ssh_host_certificates/{arg.Id}",
method: new HttpMethod("patch"),
body: body,
query: query
);
}
}
}
| 31 | 101 | 0.517897 | [
"MIT"
] | ffMathy/ngrok-api-dotnet | NgrokApi/Services/SshHostCertificates.cs | 4,526 | C# |
using System.Drawing;
using GregsStack.InputSimulatorStandard;
using Sidekick.Domain.Platforms;
namespace Sidekick.Platform.Windows.Mouse
{
public class MouseProvider : IMouseProvider
{
private static InputSimulator simulator = null;
public static InputSimulator Simulator
{
get
{
if (simulator == null)
{
simulator = new InputSimulator();
}
return simulator;
}
}
public MouseProvider()
{
}
public void Initialize()
{
// Do nothing
}
public Point GetPosition()
{
return Simulator.Mouse.Position;
}
}
}
| 20.702703 | 55 | 0.509138 | [
"MIT"
] | JadedCricket/Sidekick | src/Sidekick.Platform.Windows/Mouse/MouseProvider.cs | 766 | C# |
// Copyright (c) 2018 Ark S.r.l. All rights reserved.
// Licensed under the MIT License. See LICENSE file for license information.
using System;
namespace Ark.Tools.AspNetCore.NestedStartup
{
internal class BranchedServiceProvider : IServiceProvider
{
private IServiceProvider _parentService;
private IServiceProvider _service;
public BranchedServiceProvider(IServiceProvider parentService, IServiceProvider service)
{
_parentService = parentService;
_service = service;
}
public object GetService(Type serviceType)
{
return _service.GetService(serviceType) ?? _parentService.GetService(serviceType);
}
}
}
| 30.166667 | 96 | 0.689227 | [
"MIT"
] | ARKlab/Ark.Tools | Ark.Tools.AspNetCore.NestedStartup/BranchedServiceProvider.cs | 726 | C# |
// <auto-generated />
using AnimalShelter.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace CAnimalShelterAPI.Migrations
{
[DbContext(typeof(AnimalShelterContext))]
[Migration("20200131234619_Initial")]
partial class Initial
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.2.6-servicing-10079")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("AnimalShelter.Models.Animal", b =>
{
b.Property<int>("AnimalId")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.Property<string>("Species");
b.HasKey("AnimalId");
b.ToTable("Animals");
b.HasData(
new
{
AnimalId = 1,
Name = "Ancient One",
Species = "Cat"
},
new
{
AnimalId = 2,
Name = "Rexie",
Species = "Cat"
},
new
{
AnimalId = 3,
Name = "Matilda",
Species = "Dog"
},
new
{
AnimalId = 4,
Name = "Pip",
Species = "Dog"
},
new
{
AnimalId = 5,
Name = "Bartholomew",
Species = "Cat"
});
});
#pragma warning restore 612, 618
}
}
}
| 32 | 75 | 0.391518 | [
"MIT"
] | AnthonyGolovin/C-AnimalShelterAPI | Migrations/20200131234619_Initial.Designer.cs | 2,242 | C# |
//-----------------------------------------------------------------------
// <copyright file="LowPassFilter.cs" company="Google LLC">
//
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// This low pass filter allows a single value to be smoothed.
/// </summary>
public class LowPassFilter
{
private float _outputSmoothed;
private float _weight;
private float _inputData;
private bool _isInitialized;
/// <summary>
/// Creates an instance of the filter with a weight and initial value.
/// </summary>
/// <param name="weight">Weight of the filter.</param>
/// <param name="initialValue">Initial value of the filter.</param>
public LowPassFilter(float weight, float initialValue)
{
_weight = weight;
_inputData = initialValue;
_outputSmoothed = initialValue;
_isInitialized = false;
}
/// <summary>
/// Sets the weight.
/// </summary>
/// <param name="weight">Updates the weight.</param>
public void SetWeight(float weight)
{
_weight = weight;
}
/// <summary>
/// Gives access to the raw input data.
/// </summary>
/// <returns>Returns the raw input data.</returns>
public float GetRawInput()
{
return _inputData;
}
/// <summary>
/// Checks whether the filter is initialized.
/// </summary>
/// <returns>Returns the initialization state.</returns>
public bool GetIsInitialized()
{
return _isInitialized;
}
/// <summary>
/// Smoothes the input value with a pre-set weight.
/// </summary>
/// <param name="val">Input value.</param>
/// <returns>Returns the filtered value.</returns>
public float UpdateFilterValue(float val)
{
// Checks for not a value or infinity.
if (System.Single.IsNaN(val) || System.Single.IsInfinity(val))
{
return _outputSmoothed;
}
if (_isInitialized)
{
_outputSmoothed = (_weight * val) + ((1f - _weight) * _outputSmoothed);
}
else
{
_outputSmoothed = val;
_isInitialized = true;
}
_inputData = val;
return _outputSmoothed;
}
/// <summary>
/// Smoothes the input value while also using a new weight.
/// </summary>
/// <param name="val">Input value.</param>
/// <param name="weight">The weight of the filter operation.</param>
/// <returns>Returns the filtered value.</returns>
public float UpdateFilterValue(float val, float weight)
{
SetWeight(weight);
return UpdateFilterValue(val);
}
}
| 29.473684 | 83 | 0.602679 | [
"Apache-2.0"
] | AgrMayank/ARCore-Raw-Depth-API | Assets/ARRealismDemos/Common/Scripts/SmoothingFilter/LowPassFilter.cs | 3,360 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.Azure.IIoT.App {
using Microsoft.Azure.IIoT.App.Services;
using Microsoft.Azure.IIoT.App.Runtime;
using Microsoft.Azure.IIoT.AspNetCore.Auth.Clients;
using Microsoft.Azure.IIoT.AspNetCore.Auth;
using Microsoft.Azure.IIoT.Auth.Clients;
using Microsoft.Azure.IIoT.Http.Auth;
using Microsoft.Azure.IIoT.Http.Default;
using Microsoft.Azure.IIoT.Http.SignalR;
using Microsoft.Azure.IIoT.OpcUa.Api.Publisher.Clients;
using Microsoft.Azure.IIoT.OpcUa.Api.Registry.Clients;
using Microsoft.Azure.IIoT.OpcUa.Api.Twin.Clients;
using Microsoft.Azure.IIoT.OpcUa.Api.Vault.Clients;
using Microsoft.Azure.IIoT.OpcUa.Api.Registry;
using Microsoft.Azure.IIoT.OpcUa.Api.Publisher;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Autofac.Extensions.DependencyInjection;
using Autofac;
using System;
using System.Threading.Tasks;
using System.Security.Claims;
/// <summary>
/// Webapp startup
/// </summary>
public class Startup {
/// <summary>
/// Configuration - Initialized in constructor
/// </summary>
public Config Config { get; }
/// <summary>
/// Created through builder
/// </summary>
/// <param name="configuration"></param>
public Startup(IConfiguration configuration) {
if (configuration == null) {
throw new ArgumentNullException(nameof(configuration));
}
configuration = new ConfigurationBuilder()
.AddConfiguration(configuration)
.AddEnvironmentVariables()
.AddEnvironmentVariables(EnvironmentVariableTarget.User)
.AddFromDotEnvFile()
.AddFromKeyVault()
.Build();
Config = new Config(configuration);
}
/// <summary>
/// Configure application
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
/// <param name="appLifetime"></param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
IHostApplicationLifetime appLifetime) {
var applicationContainer = app.ApplicationServices.GetAutofacRoot();
app.UseForwardedHeaders();
var isDevelopment = env.IsDevelopment();
isDevelopment = true; // TODO Remove when all issues fixed
if (isDevelopment) {
app.UseDeveloperExceptionPage();
}
else {
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseRewriter(
new RewriteOptions().Add(context => {
if (context.HttpContext.Request.Path == "/AzureAD/Account/SignedOut") {
context.HttpContext.Response.Redirect("/");
}
})
);
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
// If you want to dispose of resources that have been resolved in the
// application container, register for the "ApplicationStopped" event.
appLifetime.ApplicationStopped.Register(applicationContainer.Dispose);
}
/// <summary>
/// This is where you register dependencies, add services to the
/// container. This method is called by the runtime, before the
/// Configure method below.
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public void ConfigureServices(IServiceCollection services) {
if (string.Equals(
Environment.GetEnvironmentVariable("ASPNETCORE_FORWARDEDHEADERS_ENABLED"),
"true", StringComparison.OrdinalIgnoreCase)) {
services.Configure<ForwardedHeadersOptions>(options => {
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto;
// Only loopback proxies are allowed by default.
// Clear that restriction because forwarders are enabled by explicit
// configuration.
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
}
// Protect anything using keyvault and storage persisted keys
services.AddAzureDataProtection(Config.Configuration);
services.Configure<CookiePolicyOptions>(options => {
// This lambda determines whether user consent for non-essential cookies
// is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Strict;
});
services.AddAntiforgery(options => {
options.Cookie.SameSite = SameSiteMode.None;
});
services.AddHttpContextAccessor();
services
.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => {
options.Instance = Config.InstanceUrl;
options.Domain = Config.Domain;
options.TenantId = Config.TenantId;
options.ClientId = Config.AppId;
options.ClientSecret = Config.AppSecret;
options.CallbackPath = "/signin-oidc";
});
//
// Without overriding the response type (which by default is id_token),
// the OnAuthorizationCodeReceived event is not called but instead
// OnTokenValidated event is called. Here we request both so that
// OnTokenValidated is called first which ensures that context.Principal
// has a non-null value when OnAuthorizationCodeReceived is called
//
services
.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options => {
options.SaveTokens = true;
options.ResponseType = "id_token code";
options.Resource = Config.AppId;
options.Scope.Add("offline_access");
options.Events.OnAuthenticationFailed = OnAuthenticationFailedAsync;
options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceivedAsync;
});
services.AddControllersWithViews(options => {
if (!string.IsNullOrEmpty(Config.AppId)) {
options.Filters.Add(new AuthorizeFilter(
new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build()));
}
});
services.AddRazorPages();
services.AddServerSideBlazor();
}
/// <summary>
/// Configure dependency injection using autofac.
/// </summary>
/// <param name="builder"></param>
public void ConfigureContainer(ContainerBuilder builder) {
// Register configuration interfaces and logger
builder.RegisterInstance(Config)
.AsImplementedInterfaces().SingleInstance();
// Register logger
builder.AddDiagnostics(Config);
// Register http client module (needed for api)...
builder.RegisterModule<HttpClientModule>();
builder.RegisterType<SignalRClient>()
.AsImplementedInterfaces().AsSelf().SingleInstance();
// Use bearer authentication
builder.RegisterType<HttpBearerAuthentication>()
.AsImplementedInterfaces().SingleInstance();
// Use behalf of token provider to get tokens from user
builder.RegisterType<BehalfOfTokenProvider>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<DistributedTokenCache>()
.AsImplementedInterfaces().SingleInstance();
// Register twin, vault, and registry services clients
builder.RegisterType<TwinServiceClient>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<RegistryServiceClient>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<VaultServiceClient>()
.AsImplementedInterfaces().SingleInstance();
builder.RegisterType<PublisherServiceClient>()
.AsImplementedInterfaces().SingleInstance();
// ... with client event callbacks
builder.RegisterType<RegistryServiceEvents>()
.AsImplementedInterfaces().AsSelf().SingleInstance();
builder.RegisterType<PublisherServiceEvents>()
.AsImplementedInterfaces().AsSelf().SingleInstance();
builder.RegisterType<Registry>()
.AsImplementedInterfaces().AsSelf().SingleInstance();
builder.RegisterType<Browser>()
.AsImplementedInterfaces().AsSelf().SingleInstance();
builder.RegisterType<Publisher>()
.AsImplementedInterfaces().AsSelf().SingleInstance();
}
/// <summary>
/// Redeems the authorization code by calling AcquireTokenByAuthorizationCodeAsync
/// in order to ensure
/// that the cache has a token for the signed-in user, which will then enable
/// the controllers
/// to call AcquireTokenSilentAsync successfully.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedContext context) {
// Acquire a Token for the API and cache it.
var credential = new ClientCredential(context.Options.ClientId,
context.Options.ClientSecret);
// TODO : Refactor!!!
var provider = context.HttpContext.RequestServices.GetRequiredService<ITokenCacheProvider>();
var tokenCache = provider.GetCache($"OID:{context.Principal.GetObjectId()}");
var authContext = new AuthenticationContext(context.Options.Authority, tokenCache);
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
context.TokenEndpointRequest.Code,
new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute),
credential, context.Options.Resource);
// Notify the OIDC middleware that we already took care of code redemption.
context.HandleCodeRedemption(authResult.AccessToken, context.ProtocolMessage.IdToken);
}
/// <summary>
/// Handle failures
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private Task OnAuthenticationFailedAsync(AuthenticationFailedContext context) {
context.Response.Redirect("/Error");
context.HandleResponse(); // Suppress the exception
return Task.CompletedTask;
}
}
}
| 43.200692 | 105 | 0.603925 | [
"MIT"
] | jaz230/Industrial-IoT | samples/src/Microsoft.Azure.IIoT.App/src/Startup.cs | 12,485 | C# |
using JetBrains.ReSharper.UnitTestFramework.Execution.TestRunner;
namespace Machine.Specifications.Runner.ReSharper.Runner
{
public interface IAgentManagerHost
{
ITestRunnerAgentManager AgentManager { get; }
}
}
| 23.4 | 66 | 0.769231 | [
"MIT"
] | machine/machine.specifications.runner.resharper | src/Machine.Specifications.Runner.ReSharper/Runner/IAgentManagerHost.cs | 236 | C# |
using System;
using System.Runtime.InteropServices;
namespace ASodium
{
public static partial class SodiumSecretAeadChaCha20Poly1305Library
{
#if IOS
const string DllName = "__Internal";
#else
const string DllName = "libsodium";
#endif
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_chacha20poly1305_keybytes();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_chacha20poly1305_npubbytes();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_chacha20poly1305_nsecbytes();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_chacha20poly1305_abytes();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern long crypto_aead_chacha20poly1305_messagebytes_max();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_chacha20poly1305_encrypt(Byte[] CipherText,long CipherTextLength,Byte[] Message,long MessageLength,Byte[] AdditionalData,long AdditionalDataLength,Byte[] NonceSecurity,Byte[] NoncePublic,Byte[] Key);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_chacha20poly1305_decrypt(Byte[] Message,long MessageLength,Byte[] NonceSecurity,Byte[] CipherText,long CipherTextLength,Byte[] AdditionalData,long AdditionalDataLength,Byte[] NoncePublic,Byte[] Key);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_chacha20poly1305_encrypt_detached(Byte[] CipherText, Byte[] MAC, long MACLength, Byte[] Message, long MessageLength, Byte[] AdditionalData, long AdditionalDataLength, Byte[] NonceSecurity, Byte[] NoncePublic, Byte[] Key);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern int crypto_aead_chacha20poly1305_decrypt_detached(Byte[] Message, Byte[] NonceSecurity, Byte[] CipherText, long CipherTextLength,Byte[] MAC, Byte[] AdditionalData, long AdditionalDataLength, Byte[] NoncePublic, Byte[] Key);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
internal static extern void crypto_aead_chacha20poly1305_keygen(Byte[] Key);
}
}
| 57.511111 | 269 | 0.746909 | [
"MIT"
] | Chewhern/ASodium | Deprecated Source/0.5.1/SodiumSecretAeadChaCha20Poly1305Library.cs | 2,590 | C# |
/*
Copyright 2017 Coin Foundry (coinfoundry.org)
Authors: Oliver Weichhold (oliver@weichhold.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Autofac;
using AutoMapper;
using MiningCore.Blockchain.Bitcoin.Configuration;
using MiningCore.Blockchain.Bitcoin.DaemonResponses;
using MiningCore.Configuration;
using MiningCore.DaemonInterface;
using MiningCore.Extensions;
using MiningCore.Notifications;
using MiningCore.Payments;
using MiningCore.Persistence;
using MiningCore.Persistence.Model;
using MiningCore.Persistence.Repositories;
using MiningCore.Time;
using MiningCore.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Block = MiningCore.Persistence.Model.Block;
using Contract = MiningCore.Contracts.Contract;
namespace MiningCore.Blockchain.Bitcoin
{
[CoinMetadata(
CoinType.BTC, CoinType.BCH, CoinType.NMC, CoinType.PPC,
CoinType.LTC, CoinType.DOGE, CoinType.DGB, CoinType.VIA,
CoinType.GRS, CoinType.MONA, CoinType.VTC, CoinType.BTG,
CoinType.GLT, CoinType.STAK, CoinType.MOON, CoinType.XVG,
CoinType.PAK, CoinType.CANN, CoinType.MUE)]
public class BitcoinPayoutHandler : PayoutHandlerBase,
IPayoutHandler
{
public BitcoinPayoutHandler(
IComponentContext ctx,
IConnectionFactory cf,
IMapper mapper,
IShareRepository shareRepo,
IBlockRepository blockRepo,
IBalanceRepository balanceRepo,
IPaymentRepository paymentRepo,
IMasterClock clock,
NotificationService notificationService) :
base(cf, mapper, shareRepo, blockRepo, balanceRepo, paymentRepo, clock, notificationService)
{
Contract.RequiresNonNull(ctx, nameof(ctx));
Contract.RequiresNonNull(balanceRepo, nameof(balanceRepo));
Contract.RequiresNonNull(paymentRepo, nameof(paymentRepo));
this.ctx = ctx;
}
protected readonly IComponentContext ctx;
protected DaemonClient daemon;
protected BitcoinCoinProperties coinProperties;
protected BitcoinDaemonEndpointConfigExtra extraPoolConfig;
protected BitcoinPoolPaymentProcessingConfigExtra extraPoolPaymentProcessingConfig;
protected override string LogCategory => "Bitcoin Payout Handler";
#region IPayoutHandler
public virtual Task ConfigureAsync(ClusterConfig clusterConfig, PoolConfig poolConfig)
{
Contract.RequiresNonNull(poolConfig, nameof(poolConfig));
this.poolConfig = poolConfig;
this.clusterConfig = clusterConfig;
extraPoolConfig = poolConfig.Extra.SafeExtensionDataAs<BitcoinDaemonEndpointConfigExtra>();
extraPoolPaymentProcessingConfig = poolConfig.PaymentProcessing.Extra.SafeExtensionDataAs<BitcoinPoolPaymentProcessingConfigExtra>();
coinProperties = BitcoinProperties.GetCoinProperties(poolConfig.Coin.Type, poolConfig.Coin.Algorithm);
logger = LogUtil.GetPoolScopedLogger(typeof(BitcoinPayoutHandler), poolConfig);
var jsonSerializerSettings = ctx.Resolve<JsonSerializerSettings>();
daemon = new DaemonClient(jsonSerializerSettings);
daemon.Configure(poolConfig.Daemons);
return Task.FromResult(true);
}
public virtual async Task<Block[]> ClassifyBlocksAsync(Block[] blocks)
{
Contract.RequiresNonNull(poolConfig, nameof(poolConfig));
Contract.RequiresNonNull(blocks, nameof(blocks));
var pageSize = 100;
var pageCount = (int) Math.Ceiling(blocks.Length / (double) pageSize);
var result = new List<Block>();
for(var i = 0; i < pageCount; i++)
{
// get a page full of blocks
var page = blocks
.Skip(i * pageSize)
.Take(pageSize)
.ToArray();
// build command batch (block.TransactionConfirmationData is the hash of the blocks coinbase transaction)
var batch = page.Select(block => new DaemonCmd(BitcoinCommands.GetTransaction,
new[] { block.TransactionConfirmationData })).ToArray();
// execute batch
var results = await daemon.ExecuteBatchAnyAsync(batch);
for(var j = 0; j < results.Length; j++)
{
var cmdResult = results[j];
var transactionInfo = cmdResult.Response?.ToObject<Transaction>();
var block = page[j];
// check error
if (cmdResult.Error != null)
{
// Code -5 interpreted as "orphaned"
if (cmdResult.Error.Code == -5)
{
block.Status = BlockStatus.Orphaned;
result.Add(block);
}
else
{
logger.Warn(() => $"[{LogCategory}] Daemon reports error '{cmdResult.Error.Message}' (Code {cmdResult.Error.Code}) for transaction {page[j].TransactionConfirmationData}");
}
}
// missing transaction details are interpreted as "orphaned"
else if (transactionInfo?.Details == null || transactionInfo.Details.Length == 0)
{
block.Status = BlockStatus.Orphaned;
result.Add(block);
}
else
{
switch(transactionInfo.Details[0].Category)
{
case "immature":
// update progress
var minConfirmations = extraPoolConfig?.MinimumConfirmations ?? BitcoinConstants.CoinbaseMinConfimations;
block.ConfirmationProgress = Math.Min(1.0d, (double) transactionInfo.Confirmations / minConfirmations);
result.Add(block);
break;
case "generate":
// matured and spendable coinbase transaction
block.Status = BlockStatus.Confirmed;
block.ConfirmationProgress = 1;
result.Add(block);
logger.Info(() => $"[{LogCategory}] Unlocked block {block.BlockHeight} worth {FormatAmount(block.Reward)}");
break;
default:
logger.Info(() => $"[{LogCategory}] Block {block.BlockHeight} classified as orphaned. Category: {transactionInfo.Details[0].Category}");
block.Status = BlockStatus.Orphaned;
block.Reward = 0;
result.Add(block);
break;
}
}
}
}
return result.ToArray();
}
public virtual Task CalculateBlockEffortAsync(Block block, double accumulatedBlockShareDiff)
{
block.Effort = accumulatedBlockShareDiff / block.NetworkDifficulty;
return Task.FromResult(true);
}
public virtual Task<decimal> UpdateBlockRewardBalancesAsync(IDbConnection con, IDbTransaction tx, Block block, PoolConfig pool)
{
var blockRewardRemaining = block.Reward;
// Distribute funds to configured reward recipients
foreach(var recipient in poolConfig.RewardRecipients.Where(x => x.Percentage > 0))
{
var amount = block.Reward * (recipient.Percentage / 100.0m);
var address = recipient.Address;
blockRewardRemaining -= amount;
// skip transfers from pool wallet to pool wallet
if (address != poolConfig.Address)
{
logger.Info(() => $"Adding {FormatAmount(amount)} to balance of {address}");
balanceRepo.AddAmount(con, tx, poolConfig.Id, poolConfig.Coin.Type, address, amount, $"Reward for block {block.BlockHeight}");
}
}
return Task.FromResult(blockRewardRemaining);
}
public virtual async Task PayoutAsync(Balance[] balances)
{
Contract.RequiresNonNull(balances, nameof(balances));
// build args
var amounts = balances
.Where(x => x.Amount > 0)
.ToDictionary(x => x.Address, x => Math.Round(x.Amount, 8));
if (amounts.Count == 0)
return;
logger.Info(() => $"[{LogCategory}] Paying out {FormatAmount(balances.Sum(x => x.Amount))} to {balances.Length} addresses");
object[] args;
if (extraPoolPaymentProcessingConfig?.MinersPayTxFees == true)
{
var comment = (poolConfig.PoolName ?? clusterConfig.ClusterName ?? "MiningCore").Trim() + " Payment";
var subtractFeesFrom = amounts.Keys.ToArray();
args = new object[]
{
string.Empty, // default account
amounts, // addresses and associated amounts
1, // only spend funds covered by this many confirmations
comment, // tx comment
subtractFeesFrom // distribute transaction fee equally over all recipients
};
}
else
{
args = new object[]
{
string.Empty, // default account
amounts, // addresses and associated amounts
};
}
var didUnlockWallet = false;
// send command
tryTransfer:
var result = await daemon.ExecuteCmdSingleAsync<string>(BitcoinCommands.SendMany, args, new JsonSerializerSettings());
if (result.Error == null)
{
if (didUnlockWallet)
{
// lock wallet
logger.Info(() => $"[{LogCategory}] Locking wallet");
await daemon.ExecuteCmdSingleAsync<JToken>(BitcoinCommands.WalletLock);
}
// check result
var txId = result.Response;
if (string.IsNullOrEmpty(txId))
logger.Error(() => $"[{LogCategory}] {BitcoinCommands.SendMany} did not return a transaction id!");
else
logger.Info(() => $"[{LogCategory}] Payout transaction id: {txId}");
PersistPayments(balances, txId);
NotifyPayoutSuccess(poolConfig.Id, balances, new[] { txId }, null);
}
else
{
if (result.Error.Code == (int) BitcoinRPCErrorCode.RPC_WALLET_UNLOCK_NEEDED && !didUnlockWallet)
{
if (!string.IsNullOrEmpty(extraPoolPaymentProcessingConfig?.WalletPassword))
{
logger.Info(() => $"[{LogCategory}] Unlocking wallet");
var unlockResult = await daemon.ExecuteCmdSingleAsync<JToken>(BitcoinCommands.WalletPassphrase, new []
{
(object) extraPoolPaymentProcessingConfig.WalletPassword,
(object) 5 // unlock for N seconds
});
if (unlockResult.Error == null)
{
didUnlockWallet = true;
goto tryTransfer;
}
else
logger.Error(() => $"[{LogCategory}] {BitcoinCommands.WalletPassphrase} returned error: {result.Error.Message} code {result.Error.Code}");
}
else
logger.Error(() => $"[{LogCategory}] Wallet is locked but walletPassword was not configured. Unable to send funds.");
}
else
{
logger.Error(() => $"[{LogCategory}] {BitcoinCommands.SendMany} returned error: {result.Error.Message} code {result.Error.Code}");
NotifyPayoutFailure(poolConfig.Id, balances, $"{BitcoinCommands.SendMany} returned error: {result.Error.Message} code {result.Error.Code}", null);
}
}
}
#endregion // IPayoutHandler
}
}
| 43.123494 | 200 | 0.553887 | [
"MIT"
] | vkynchev/miningcore | src/MiningCore/Blockchain/Bitcoin/BitcoinPayoutHandler.cs | 14,319 | C# |
// SortReceiveEvent.cs
// Script#/Libraries/jQuery/UI
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace jQueryApi.UI.Interactions {
[ScriptImport]
[ScriptIgnoreNamespace]
[ScriptName("Object")]
public sealed class SortReceiveEvent {
[ScriptField]
public jQueryObject Helper {
get {
return null;
}
set {
}
}
[ScriptField]
public jQueryObject Item {
get {
return null;
}
set {
}
}
[ScriptField]
public object Offset {
get {
return null;
}
set {
}
}
[ScriptField]
public object OriginalPosition {
get {
return null;
}
set {
}
}
[ScriptField]
public object Position {
get {
return null;
}
set {
}
}
[ScriptField]
public jQueryObject Sender {
get {
return null;
}
set {
}
}
}
}
| 18.830986 | 90 | 0.424832 | [
"Apache-2.0"
] | AmanArnold/dsharp | src/Libraries/jQuery/jQuery.UI/Interactions/Sortable/SortReceiveEvent.cs | 1,337 | C# |
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;
#if UNITY_2018
using UnityEngine.Experimental.UIElements;
#else
using UnityEngine.UIElements;
#endif
namespace EsnyaFactory
{
[System.Serializable]
public class LayerGenerator : EditorWindow
{
public abstract class Generator : PersistentObject
{
public abstract string GetName();
public abstract VisualElement CreateGUI();
public abstract IEnumerable<Object> Generate(AnimatorController animatorController, AnimatorStateMachine stateMachine);
}
const string titleText = "Layer Generator";
[MenuItem("EsnyaTools/" + titleText)]
static void ShowWindow()
{
GetWindow<LayerGenerator>().Show();
}
public string savePath = "Assets";
public Generator[] generators;
public Generator generator;
public AnimatorController animatorController;
public int layerIndex;
private VisualElement GetRoot()
{
#if UNITY_2018
return this.GetRootVisualContainer();
#else
return rootVisualElement;
#endif
}
void OnValidate()
{
var isValid = animatorController != null
&& savePath.StartsWith("Assets")
&& layerIndex < animatorController.layers.Length;
GetRoot().Q<Button>("generateButton").SetEnabled(isValid);
}
void OnAnimatorControllerChanged(AnimatorController newValue)
{
var container = GetRoot().Q<VisualElement>("Input:layer");
container.Clear();
if (newValue != null)
{
if (layerIndex >= newValue.layers.Length) layerIndex = 0;
var popupField = new PopupField<string>(
newValue.layers.Select(l => l.name).ToList(),
layerIndex
);
container.Add(popupField);
popupField.OnValueChanged(e2 => layerIndex = popupField.index);
}
else
{
container.Add(new Label("Select Animator Controller"));
}
}
void OnGeneratorChanged(Generator newValue)
{
generator = newValue;
var container = GetRoot().Q("generatorProperties");
container.Clear();
if (newValue == null)
{
container.Add(new Label("Select Generator"));
}
else
{
var root = newValue.CreateGUI();
root.Bind(new SerializedObject(generator));
container.Add(root);
}
}
void OnEnable()
{
titleContent = new GUIContent(titleText);
var data = EditorPrefs.GetString(nameof(LayerGenerator), JsonUtility.ToJson(this, false));
JsonUtility.FromJsonOverwrite(data, this);
generators = new Generator[] {
ScriptableObject.CreateInstance<SimpleToggleLayerGenerator>(),
ScriptableObject.CreateInstance<SimpleSwitchCaseLayerGenerator>(),
};
var target = new SerializedObject(this);
var root = Resources.Load<VisualTreeAsset>("UI/LayerGeneratorWindow").CloneTree(null);
root.AddStyleSheetPath("UI/LayerGeneratorWindow");
root.Bind(target);
GetRoot().Add(root);
root.Q<ObjectField>("Input:animatorController").OnValueChanged(e => OnAnimatorControllerChanged(e.newValue as AnimatorController));
OnAnimatorControllerChanged(animatorController);
generator = generators.First(g => generator == null ? true : generator.GetName() == g.GetName());
data = EditorPrefs.GetString(nameof(LayerGenerator), JsonUtility.ToJson(this, false));
JsonUtility.FromJsonOverwrite(data, generator);
var generatorField = new PopupField<string>(
generators.Select(g => g.GetName()).ToList(),
generators.Select((g, i) => (g, i)).FirstOrDefault(t => t.Item1.GetName() == generator.GetName()).Item2
);
generatorField.OnValueChanged(e => OnGeneratorChanged(generators[generatorField.index]));
root.Q<VisualElement>("Input:generator").Add(generatorField);
OnGeneratorChanged(generator);
root.Q<Button>("generateButton").clickable.clicked += () =>
{
var objects = generator.Generate(animatorController, animatorController.layers[layerIndex].stateMachine);
var name = $"{nameof(LayerGenerator)}_{System.DateTime.Now.ToString("o").Replace(':', '-')}";
ExAssetUtility.PackAssets(objects, $"{savePath}/{name}.asset");
};
}
void OnDisable()
{
foreach (var g in generators) g.Save();
var data = JsonUtility.ToJson(this, false);
EditorPrefs.SetString(nameof(LayerGenerator), data);
}
}
}
| 33.94702 | 143 | 0.590714 | [
"MIT"
] | esnya/EsnyaUnityTools | Assets/EsnyaUnityTools/AnimGenerator~/Editor/LayerGenerator.cs | 5,126 | 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.CSharp7.Lightup
{
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using StyleCop.Analyzers.Lightup;
using Xunit;
public class TupleElementSyntaxWrapperTests
{
[Fact]
public void TestNull()
{
var syntaxNode = default(SyntaxNode);
var wrapper = (TupleElementSyntaxWrapper)syntaxNode;
Assert.Null(wrapper.SyntaxNode);
Assert.Throws<NullReferenceException>(() => wrapper.Type);
Assert.Throws<NullReferenceException>(() => wrapper.Identifier);
Assert.Throws<NullReferenceException>(() => wrapper.WithType(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword))));
Assert.Throws<NullReferenceException>(() => wrapper.WithIdentifier(SyntaxFactory.Identifier("x")));
}
[Fact]
public void TestProperties()
{
var syntaxNode = this.CreateTupleElement();
Assert.True(syntaxNode.IsKind(SyntaxKind.TupleElement));
Assert.True(syntaxNode.IsKind(SyntaxKindEx.TupleElement));
var wrapper = (TupleElementSyntaxWrapper)syntaxNode;
Assert.Same(syntaxNode, wrapper.SyntaxNode);
Assert.Same(syntaxNode.Type, wrapper.Type);
Assert.True(syntaxNode.Identifier.IsEquivalentTo(wrapper.Identifier));
var newType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntKeyword));
var wrapperWithModifiedType = wrapper.WithType(newType);
Assert.NotNull(wrapperWithModifiedType.SyntaxNode);
Assert.NotSame(syntaxNode.Type, wrapperWithModifiedType.Type);
Assert.Equal(SyntaxKind.UIntKeyword, ((PredefinedTypeSyntax)wrapperWithModifiedType.Type).Keyword.Kind());
var newIdentifier = SyntaxFactory.Identifier("y").WithLeadingTrivia(SyntaxFactory.Space);
var wrapperWithModifiedIdentifier = wrapper.WithIdentifier(newIdentifier);
Assert.NotNull(wrapperWithModifiedIdentifier.SyntaxNode);
Assert.Single(wrapperWithModifiedIdentifier.Identifier.LeadingTrivia);
Assert.Equal(" ", wrapperWithModifiedIdentifier.Identifier.LeadingTrivia.ToString());
}
[Fact]
public void TestIsInstance()
{
Assert.False(TupleElementSyntaxWrapper.IsInstance(null));
Assert.False(TupleElementSyntaxWrapper.IsInstance(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)));
var syntaxNode = this.CreateTupleElement();
Assert.True(TupleElementSyntaxWrapper.IsInstance(syntaxNode));
}
[Fact]
public void TestConversionsNull()
{
var syntaxNode = default(SyntaxNode);
var wrapper = (TupleElementSyntaxWrapper)syntaxNode;
CSharpSyntaxNode syntax = wrapper;
Assert.Null(syntax);
}
[Fact]
public void TestConversions()
{
var syntaxNode = this.CreateTupleElement();
var wrapper = (TupleElementSyntaxWrapper)syntaxNode;
CSharpSyntaxNode syntax = wrapper;
Assert.Same(syntaxNode, syntax);
}
[Fact]
public void TestInvalidConversion()
{
var syntaxNode = SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression);
Assert.Throws<InvalidCastException>(() => (TupleElementSyntaxWrapper)syntaxNode);
}
private TupleElementSyntax CreateTupleElement()
{
return SyntaxFactory.TupleElement(
SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)),
SyntaxFactory.Identifier("id"));
}
}
}
| 41.55102 | 151 | 0.670432 | [
"Apache-2.0"
] | Andreyul/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/Lightup/TupleElementSyntaxWrapperTests.cs | 4,074 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace JsonLD.Entities
{
/// <summary>
/// Useful extensions of <see cref="Type"/>
/// </summary>
public static class TypeExtension
{
/// <summary>
/// Gets the class identifier for an entity type.
/// </summary>
public static Uri GetTypeIdentifier(this Type type)
{
var typesProperty = type.GetProperty("Type", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public) ??
type.GetProperty("Types", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public) ??
type.GetAnnotatedTypeProperty();
if (typesProperty == null)
{
throw new InvalidOperationException($"Type {type} does not statically declare @type");
}
var getter = typesProperty.GetGetMethod(true);
dynamic typeValue = getter.Invoke(null, null);
if (typeValue is IEnumerable && Enumerable.Count(typeValue) == 1)
{
typeValue = Enumerable.Single(typeValue);
}
if (typeValue is Uri)
{
return typeValue;
}
if (typeValue is string)
{
return new Uri(typeValue);
}
throw new InvalidOperationException("Cannot convert value to Uri");
}
/// <summary>
/// Determines whether the <paramref name="type"/> should be compacted after serialization.
/// </summary>
internal static bool IsMarkedForCompaction(this Type type)
{
return type.GetTypeInfo().GetCustomAttributes(typeof(SerializeCompactedAttribute), true).Any();
}
private static PropertyInfo GetAnnotatedTypeProperty(this Type type)
{
return (from prop in type.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)
let jsonProperty = prop.GetCustomAttributes(typeof(JsonPropertyAttribute), false).SingleOrDefault() as JsonPropertyAttribute
where jsonProperty != null
where jsonProperty.PropertyName == JsonLdKeywords.Type
select prop).FirstOrDefault();
}
}
}
| 35.782609 | 144 | 0.597813 | [
"MIT"
] | wikibus/JsonLD.Entities | src/JsonLD.Entities/TypeExtension.cs | 2,471 | C# |
/*
* MIT License
*
* Copyright (c) 2019 plexdata.de
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using Plexdata.GitHub.Accessor.Abstraction.Entities;
using System;
using System.Threading.Tasks;
namespace Plexdata.GitHub.Accessor.Abstraction
{
public interface IReader<TResult, TArguments>
{
Uri Host { get; }
Boolean IncludeApiPreviews { get; set; }
Task<IResult<TResult>> ReadAsync();
Task<IResult<TResult>> ReadAsync(TArguments arguments);
}
}
| 36.595238 | 81 | 0.739753 | [
"MIT"
] | akesseler/GitHubViewer | code/src/GitHubAccessor/Abstraction/IReader.cs | 1,539 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.