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.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Text.RegularExpressions;
namespace BD_PROJECT
{
public partial class AlterTurma : Form
{
string strConn = Form1.strConn;
private Form1 ParentForm;
public AlterTurma(Form1 form)
{
InitializeComponent();
fillComboBoxs();
ParentForm = form;
}
private void fillComboBoxs()
{
Dictionary<Int32, string> turmas = new Dictionary<Int32, string>();
Dictionary<Int32, string> profs = new Dictionary<Int32, string>();
Dictionary<Int32, string> alunos = new Dictionary<Int32, string>();
using (SqlConnection myConnection = new SqlConnection(strConn))
{
string query = "select * from TURMA;";
myConnection.Open();
using (SqlCommand cmd = new SqlCommand(query, myConnection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
turmas.Add((Int32)reader["idTurma"], (string)reader["Nome"]);
}
}
}
query = "select * from GET_PROFESSOR_WITH_TURMAS where refTurma=" + 1 + ";";
using (SqlCommand cmd = new SqlCommand(query, myConnection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
profs.Add((Int32)reader["BI"], (string)reader["Nome"] + " #" + (Int32)reader["BI"]);
}
}
}
query = "select * from GET_ALUNOS where Turma='" + 'A' + "';";
using (SqlCommand cmd = new SqlCommand(query, myConnection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
alunos.Add((Int32)reader["BI"], (string)reader["Nome"] + " #" + (Int32)reader["BI"]);
}
}
}
comboBox1.DataSource = new BindingSource(turmas, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
try
{
comboBoxDirector.DataSource = new BindingSource(profs, null);
comboBoxDirector.DisplayMember = "Value";
comboBoxDirector.ValueMember = "Key";
}
catch (Exception ex)
{
MessageBox.Show("Não existem professores nesta turma!");
button1.Enabled = false;
}
try
{
comboBoxDelegado.DataSource = new BindingSource(alunos, null);
comboBoxDelegado.DisplayMember = "Value";
comboBoxDelegado.ValueMember = "Key";
}
catch (Exception ex)
{
MessageBox.Show("Não existem alunos nesta turma!");
button1.Enabled = false;
}
// fill Ano Lectivo
string str;
query = "select * from ANO_LECTIVO;";
using (SqlCommand cmd = new SqlCommand(query, myConnection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
str = (Int32)reader["AnoInicio"] + " - " + (Int32)reader["AnoFim"];
comboBoxAnoLectivo.Items.Add(str);
}
}
}
// ultimo elemento
comboBoxAnoLectivo.Items.Add("Outro...");
myConnection.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
Int32 turma = ((KeyValuePair<Int32, string>)comboBox1.SelectedItem).Key;
string nome = textBoxNome.Text;
Int32 director = ((KeyValuePair<Int32, string>)comboBoxDirector.SelectedItem).Key;
Int32 delegado = ((KeyValuePair<Int32, string>)comboBoxDelegado.SelectedItem).Key;
string max = numericUpDownMaxAlunos.Value.ToString();
string inicio, fim;
if (comboBoxAnoLectivo.SelectedIndex >= comboBoxAnoLectivo.Items.Count - 1)
{
inicio = textBoxAnoInicio.Text;
fim = textBoxAnoFim.Text;
}
else
{
string ano;
try
{
ano = ((string)comboBoxAnoLectivo.SelectedItem.ToString());
}
catch (NullReferenceException en)
{
ano = " - ";
}
string[] outs = Regex.Split(ano, " - ");
inicio = outs[0];
fim = outs[1];
}
using (SqlConnection myConnection = new SqlConnection(strConn))
{
myConnection.Open();
using (SqlCommand cmd = myConnection.CreateCommand())
{
cmd.CommandText = "EXEC AlterarTurma @idTurma=" + turma + ", @Nome='"
+ nome + "', @Director="
+ director + ", @Delegado="
+ delegado + ", @Max_Alunos="
+ max + ", @AnoInicio="
+ inicio + ", @AnoFim="
+ fim + ";";
cmd.ExecuteNonQuery();
}
myConnection.Close();
}
ParentForm.updateData();
this.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Dictionary<Int32, string> profs = new Dictionary<Int32, string>();
Dictionary<Int32, string> alunos = new Dictionary<Int32, string>();
using (SqlConnection myConnection = new SqlConnection(strConn))
{
myConnection.Open();
string query = "select * from GET_PROFESSOR_WITH_TURMAS where refTurma=" + ((KeyValuePair<Int32, string>)comboBox1.SelectedItem).Key + ";";
using (SqlCommand cmd = new SqlCommand(query, myConnection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
profs.Add((Int32)reader["BI"], (string)reader["Nome"] + " #" + (Int32)reader["BI"]);
}
}
}
query = "select * from GET_ALUNOS where Turma='" + ((KeyValuePair<Int32, string>)comboBox1.SelectedItem).Value + "';";
using (SqlCommand cmd = new SqlCommand(query, myConnection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
alunos.Add((Int32)reader["BI"], (string)reader["Nome"] + " #" + (Int32)reader["BI"]);
}
}
}
try
{
comboBoxDirector.DataSource = new BindingSource(profs, null);
comboBoxDirector.DisplayMember = "Value";
comboBoxDirector.ValueMember = "Key";
}
catch (Exception ex)
{
MessageBox.Show("Não existem professores nesta turma!");
button1.Enabled = false;
}
try
{
comboBoxDelegado.DataSource = new BindingSource(alunos, null);
comboBoxDelegado.DisplayMember = "Value";
comboBoxDelegado.ValueMember = "Key";
}
catch (Exception ex)
{
MessageBox.Show("Não existem alunos nesta turma!");
button1.Enabled = false;
}
myConnection.Close();
}
}
private void comboBoxAnoLectivo_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxAnoLectivo.SelectedIndex >= comboBoxAnoLectivo.Items.Count - 1)
{
textBoxAnoInicio.Enabled = true;
textBoxAnoFim.Enabled = true;
}
else
{
textBoxAnoInicio.Enabled = false;
textBoxAnoFim.Enabled = false;
}
}
}
}
| 36.625984 | 155 | 0.456412 | [
"Apache-2.0"
] | ruineto/portfolio | dotNet/GestorEscolar/BD_PROJECT/AlterTurma.cs | 9,309 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AlibabaCloud.SDK.NAS20170626.Models
{
public class DescribeFileSystemsResponse : TeaModel {
[NameInMap("RequestId")]
[Validation(Required=true)]
public string RequestId { get; set; }
[NameInMap("TotalCount")]
[Validation(Required=true)]
public int? TotalCount { get; set; }
[NameInMap("PageSize")]
[Validation(Required=true)]
public int? PageSize { get; set; }
[NameInMap("PageNumber")]
[Validation(Required=true)]
public int? PageNumber { get; set; }
[NameInMap("FileSystems")]
[Validation(Required=true)]
public DescribeFileSystemsResponseFileSystems FileSystems { get; set; }
public class DescribeFileSystemsResponseFileSystems : TeaModel {
[NameInMap("FileSystem")]
[Validation(Required=true)]
public List<DescribeFileSystemsResponseFileSystemsFileSystem> FileSystem { get; set; }
public class DescribeFileSystemsResponseFileSystemsFileSystem : TeaModel {
public string FileSystemId { get; set; }
public string Description { get; set; }
public string CreateTime { get; set; }
public string ExpiredTime { get; set; }
public string RegionId { get; set; }
public string ZoneId { get; set; }
public string ProtocolType { get; set; }
public string StorageType { get; set; }
public string FileSystemType { get; set; }
public int? EncryptType { get; set; }
public long MeteredSize { get; set; }
public long MeteredIASize { get; set; }
public long Bandwidth { get; set; }
public long Capacity { get; set; }
public string AutoSnapshotPolicyId { get; set; }
public string Status { get; set; }
public string ChargeType { get; set; }
public long MountTargetCountLimit { get; set; }
public string NasNamespaceId { get; set; }
public string KMSKeyId { get; set; }
public string Version { get; set; }
public DescribeFileSystemsResponseFileSystemsFileSystemMountTargets MountTargets { get; set; }
public class DescribeFileSystemsResponseFileSystemsFileSystemMountTargets : TeaModel {
[NameInMap("MountTarget")]
[Validation(Required=true)]
public List<DescribeFileSystemsResponseFileSystemsFileSystemMountTargetsMountTarget> MountTarget { get; set; }
public class DescribeFileSystemsResponseFileSystemsFileSystemMountTargetsMountTarget : TeaModel {
[NameInMap("MountTargetDomain")]
[Validation(Required=true)]
public string MountTargetDomain { get; set; }
[NameInMap("NetworkType")]
[Validation(Required=true)]
public string NetworkType { get; set; }
[NameInMap("VpcId")]
[Validation(Required=true)]
public string VpcId { get; set; }
[NameInMap("VswId")]
[Validation(Required=true)]
public string VswId { get; set; }
[NameInMap("AccessGroupName")]
[Validation(Required=true)]
public string AccessGroupName { get; set; }
[NameInMap("Status")]
[Validation(Required=true)]
public string Status { get; set; }
}
}
public DescribeFileSystemsResponseFileSystemsFileSystemPackages Packages { get; set; }
public class DescribeFileSystemsResponseFileSystemsFileSystemPackages : TeaModel {
[NameInMap("Package")]
[Validation(Required=true)]
public List<DescribeFileSystemsResponseFileSystemsFileSystemPackagesPackage> Package { get; set; }
public class DescribeFileSystemsResponseFileSystemsFileSystemPackagesPackage : TeaModel {
[NameInMap("PackageId")]
[Validation(Required=true)]
public string PackageId { get; set; }
[NameInMap("PackageType")]
[Validation(Required=true)]
public string PackageType { get; set; }
[NameInMap("Size")]
[Validation(Required=true)]
public long Size { get; set; }
[NameInMap("StartTime")]
[Validation(Required=true)]
public string StartTime { get; set; }
[NameInMap("ExpiredTime")]
[Validation(Required=true)]
public string ExpiredTime { get; set; }
}
}
public DescribeFileSystemsResponseFileSystemsFileSystemLdap Ldap { get; set; }
public class DescribeFileSystemsResponseFileSystemsFileSystemLdap : TeaModel {
[NameInMap("BindDN")]
[Validation(Required=true)]
public string BindDN { get; set; }
[NameInMap("URI")]
[Validation(Required=true)]
public string URI { get; set; }
[NameInMap("SearchBase")]
[Validation(Required=true)]
public string SearchBase { get; set; }
}
public DescribeFileSystemsResponseFileSystemsFileSystemSupportedFeatures SupportedFeatures { get; set; }
public class DescribeFileSystemsResponseFileSystemsFileSystemSupportedFeatures : TeaModel {
[NameInMap("SupportedFeature")]
[Validation(Required=true)]
public List<string> SupportedFeature { get; set; }
}
}
};
}
}
| 46.122449 | 134 | 0.511504 | [
"Apache-2.0"
] | atptro/alibabacloud-sdk | nas-20170626/csharp/core/Models/DescribeFileSystemsResponse.cs | 6,780 | C# |
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection.Emit;
using Automatics.ModUtils;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;
namespace Automatics.Debug
{
[SuppressMessage("ReSharper", "InconsistentNaming")]
[HarmonyPatch]
internal static class Patches
{
private static KeyboardShortcut _toggleGodMode =
new KeyboardShortcut(KeyCode.T, KeyCode.LeftShift, KeyCode.LeftAlt);
private static KeyboardShortcut _toggleGhostMode =
new KeyboardShortcut(KeyCode.Y, KeyCode.LeftShift, KeyCode.LeftAlt);
private static KeyboardShortcut _toggleFlyMode =
new KeyboardShortcut(KeyCode.U, KeyCode.LeftShift, KeyCode.LeftAlt);
private static KeyboardShortcut _killAll =
new KeyboardShortcut(KeyCode.K, KeyCode.LeftShift, KeyCode.LeftAlt);
private static KeyboardShortcut _removeDrops =
new KeyboardShortcut(KeyCode.L, KeyCode.LeftShift, KeyCode.LeftAlt);
private static KeyboardShortcut _debug =
new KeyboardShortcut(KeyCode.P, KeyCode.LeftShift, KeyCode.LeftAlt);
[HarmonyPostfix, HarmonyPatch(typeof(Player), "Awake")]
private static void PlayerAwakePostfix(Player __instance)
{
__instance.SetGodMode(true);
__instance.SetGhostMode(true);
if (!__instance.NoCostCheat())
__instance.ToggleNoPlacementCost();
}
[HarmonyPostfix, HarmonyPatch(typeof(Player), "Update")]
private static void PlayerUpdatePostfix(Player __instance)
{
if (_toggleGodMode.IsDown())
{
__instance.SetGodMode(!__instance.InGodMode());
}
if (_toggleGhostMode.IsDown())
{
__instance.SetGhostMode(!__instance.InGhostMode());
}
if (_toggleFlyMode.IsDown())
{
Console.instance.TryRunCommand("fly");
}
if (_killAll.IsDown())
{
Console.instance.TryRunCommand("killall");
}
if (_removeDrops.IsDown())
{
Console.instance.TryRunCommand("removedrops");
}
if (_debug.IsDown())
{
// Add the process want to run during development
}
}
[HarmonyPrefix, HarmonyPatch(typeof(Player), "UseStamina")]
private static bool PlayerUseStaminaPrefix(Player __instance, float v)
{
return !__instance.InGodMode();
}
[HarmonyPostfix, HarmonyPatch(typeof(Terminal), "Awake")]
private static void TerminalAwakePostfix(Terminal __instance, bool ___m_cheat)
{
if (!___m_cheat)
{
Reflection.SetField(__instance, "m_cheat", true);
}
}
[HarmonyTranspiler, HarmonyPatch(typeof(Terminal), "InitTerminal")]
private static IEnumerable<CodeInstruction> TerminalInitTerminalTranspiler(
IEnumerable<CodeInstruction> instructions)
{
var Hook = AccessTools.Method(typeof(Patches), nameof(CallInitTerminalHook));
var codes = new List<CodeInstruction>(instructions);
var index = codes.FindLastIndex(x => x.opcode == OpCodes.Ret);
if (index != -1)
codes.Insert(index - 1, new CodeInstruction(OpCodes.Call, Hook));
return codes;
}
private static void CallInitTerminalHook() => Command.RegisterCommands();
}
} | 33.611111 | 89 | 0.615152 | [
"MIT"
] | eideehi/valheim-automatics | Automatics/Debug/Patches.cs | 3,632 | C# |
using System;
namespace LBHFSSPublicAPI.V1.Infrastructure.AddressesContextEntities
{
public class AddressEntity
{
public string AddressKey { get; set; }
public string Uprn { get; set; }
public string Usrn { get; set; }
public string ParentUPRN { get; set; }
public string AddressStatus { get; set; }
public string UnitName { get; set; }
public string UnitNumber { get; set; }
public string BuildingName { get; set; }
public string BuildingNumber { get; set; }
public string Street { get; set; }
public string Postcode { get; set; }
public string Locality { get; set; }
public string Town { get; set; }
public string Gazetteer { get; set; }
public string CommercialOccupier { get; set; }
public string Ward { get; set; }
public string UsageDescription { get; set; }
public string UsagePrimary { get; set; }
public string UsageCode { get; set; }
public string PlanningUseClass { get; set; }
public bool PropertyShell { get; set; }
public bool HackneyGazetteerOutOfBoroughAddress { get; set; }
public double Easting { get; set; }
public double Northing { get; set; }
public double Longitude { get; set; }
public double Latitude { get; set; }
public string AddressStartDate { get; set; }
public string AddressEndDate { get; set; }
public string AddressChangeDate { get; set; }
public string PropertyStartDate { get; set; }
public string PropertyEndDate { get; set; }
public string PropertyChangeDate { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string Line4 { get; set; }
}
}
| 41.133333 | 69 | 0.613182 | [
"MIT"
] | LBHackney-IT/lbh-fss-public-api | LBHFSSPublicAPI/V1/Infrastructure/AddressesContextEntities/AddressEntity.cs | 1,851 | C# |
// ***********************************************************************
// Copyright (c) 2009 Charlie Poole
//
// 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;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class Contains
{
#region Item
/// <summary>
/// Returns a new CollectionContainsConstraint checking for the
/// presence of a particular object in the collection.
/// </summary>
public static CollectionContainsConstraint Item(object expected)
{
return new CollectionContainsConstraint(expected);
}
#endregion
#region Key
/// <summary>
/// Returns a new DictionaryContainsKeyConstraint checking for the
/// presence of a particular key in the dictionary.
/// </summary>
public static DictionaryContainsKeyConstraint Key(object expected)
{
return new DictionaryContainsKeyConstraint(expected);
}
#endregion
#region Value
/// <summary>
/// Returns a new DictionaryContainsValueConstraint checking for the
/// presence of a particular value in the dictionary.
/// </summary>
public static DictionaryContainsValueConstraint Value(object expected)
{
return new DictionaryContainsValueConstraint(expected);
}
#endregion
#region Substring
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public static SubstringConstraint Substring(string expected)
{
return new SubstringConstraint(expected);
}
#endregion
}
}
| 34.573034 | 78 | 0.642184 | [
"MIT"
] | jnm2/nunit | src/NUnitFramework/framework/Contains.cs | 3,077 | C# |
using System;
namespace HananokiEditor {
public static partial class UnityTypes {
static Type _UnityEditor_PackageManager_UI_PackageManagerWindow;
public static Type UnityEditor_PackageManager_UI_PackageManagerWindow => Get( ref _UnityEditor_PackageManager_UI_PackageManagerWindow, "UnityEditor.PackageManager.UI.PackageManagerWindow", "UnityEditor" );
static Type _UnityEditor_PackageManager_UI_PackageDatabase;
public static Type UnityEditor_PackageManager_UI_PackageDatabase => Get( ref _UnityEditor_PackageManager_UI_PackageDatabase, "UnityEditor.PackageManager.UI.PackageDatabase", "UnityEditor" );
static Type _UnityEditor_PackageManager_UI_PackageDatabase_PackageDatabaseInternal;
public static Type UnityEditor_PackageManager_UI_PackageDatabase_PackageDatabaseInternal => Get( ref _UnityEditor_PackageManager_UI_PackageDatabase_PackageDatabaseInternal, "UnityEditor.PackageManager.UI.PackageDatabase+PackageDatabaseInternal", "UnityEditor" );
static Type _UnityEditor_PackageManager_UI_ServicesContainer;
public static Type UnityEditor_PackageManager_UI_ServicesContainer => Get( ref _UnityEditor_PackageManager_UI_ServicesContainer, "UnityEditor.PackageManager.UI.ServicesContainer", "UnityEditor" );
static Type _UnityEditor_PackageManager_UI_Package;
public static Type UnityEditor_PackageManager_UI_Package => Get( ref _UnityEditor_PackageManager_UI_Package, "UnityEditor.PackageManager.UI.Package", "UnityEditor" );
}
}
| 61 | 264 | 0.866803 | [
"MIT"
] | hananoki/SharedModule | UnitySymbol/Type/PackageManager.cs | 1,466 | C# |
using ADHDataManager.Library.Internal.DataAccess;
using ADHDataManager.Library.Models;
using System.Collections.Generic;
namespace ADHDataManager.Library.DataAccess
{
public class PatientNoteData : IPatientNoteData
{
private readonly ISqlDataAccess _sqlDataAccess;
public PatientNoteData(ISqlDataAccess sqlDataAccess)
{
_sqlDataAccess = sqlDataAccess;
}
public List<PatientNoteModel> GetNotes()
{
var output = _sqlDataAccess.LoadData<PatientNoteModel, dynamic>("dbo.spPatientNote_FindAll", new { });
return output;
}
public List<PatientNoteModel> GetNotesByPatientId(string patientId)
{
var Parameters = new { @PatientId = patientId };
var output = _sqlDataAccess.LoadData<PatientNoteModel, dynamic>("dbo.spPatientNote_FindByPatientId", Parameters);
return output;
}
public List<PatientNoteModel> GetNotesByPatientId_Show(string patientId)
{
var Parameters = new { @PatientId = patientId };
var output = _sqlDataAccess.LoadData<PatientNoteModel, dynamic>("dbo.spPatientNote_FindByPatientId_Show", Parameters);
return output;
}
public List<PatientNoteModel> GetNotesByPatientAndDoctorId(string patientId, string doctorId)
{
var Parameters = new { @PatientId = patientId, @DoctortId = doctorId };
var output = _sqlDataAccess.LoadData<PatientNoteModel, dynamic>("dbo.spPatientNote_FindByPatientIdAndDoctorID", Parameters);
return output;
}
public void AddNewPatientNote(PatientNoteModel patientNote)
{
var Parameters = new
{
@Id = patientNote.Id,
@Body = patientNote.Body,
@PatientId = patientNote.PatientId,
@AddedBy = patientNote.AddedBy,
@ShowToPatient = patientNote.ShowToPatient
};
_sqlDataAccess.SaveData<dynamic>("dbo.spPatientNote_AddNote", Parameters);
}
public void DeleteNote(string noteId)
{
var Parameters = new { @NoteId = noteId };
_sqlDataAccess.SaveData<dynamic>("dbo.spPatientNote_DeleteNoteById", Parameters);
}
public void UpdatePatient_PatientAndDoctorId(PatientNoteModel noteModel)
{
var Parameters = new
{
@Id = noteModel.Id,
@Body = noteModel.Body,
@ShowToPatient = noteModel.ShowToPatient
};
_sqlDataAccess.SaveData<dynamic>("dbo.spPatientNote_UpdatePatientByPatientAndDoctorID", Parameters);
}
}
}
| 33.851852 | 136 | 0.628738 | [
"MIT"
] | AhmedDuraid/ADH-Medical-System | ADHDataManager.Library/DataAccess/PatientNoteData.cs | 2,744 | C# |
using CyberCAT.Core.Classes.Mapping;
namespace CyberCAT.Core.Classes.DumpedClasses
{
[RealName("gameSourceData")]
public class GameSourceData : ISerializable
{
[RealName("name")]
public CName Name { get; set; }
[RealName("savable")]
public bool Savable { get; set; }
}
}
| 21.933333 | 47 | 0.617021 | [
"MIT"
] | Deweh/CyberCAT | CyberCAT.Core/Classes/DumpedClasses/GameSourceData.cs | 329 | C# |
using Captura.Models;
using Captura.ViewModels;
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Captura.Native;
using CommandLine;
using Screna;
using static System.Console;
// ReSharper disable LocalizableElement
namespace Captura
{
static class Program
{
static void Main(string[] Args)
{
if (Args.Length == 0)
{
var uiPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"captura.exe");
if (File.Exists(uiPath))
{
Process.Start(uiPath);
return;
}
}
User32.SetProcessDPIAware();
ServiceProvider.LoadModule(new CoreModule());
ServiceProvider.LoadModule(new FakesModule());
// Hide on Full Screen Screenshot doesn't work on Console
ServiceProvider.Get<Settings>().UI.HideOnFullScreenShot = false;
Parser.Default.ParseArguments<StartCmdOptions, ShotCmdOptions, FFmpegCmdOptions, ListCmdOptions>(Args)
.WithParsed<ListCmdOptions>(Options => List())
.WithParsed<StartCmdOptions>(Options =>
{
Banner();
using (var vm = ServiceProvider.Get<MainViewModel>())
{
vm.Init(false, false, false, false);
// Load settings dummy
var dummySettings = new Settings();
dummySettings.Load();
vm.Settings.WebcamOverlay = dummySettings.WebcamOverlay;
vm.Settings.MousePointerOverlay = dummySettings.MousePointerOverlay;
vm.Settings.Clicks = dummySettings.Clicks;
vm.Settings.Keystrokes = dummySettings.Keystrokes;
vm.Settings.Elapsed = dummySettings.Elapsed;
// FFmpeg Path
vm.Settings.FFmpeg.FolderPath = dummySettings.FFmpeg.FolderPath;
foreach (var overlay in dummySettings.Censored)
{
vm.Settings.Censored.Add(overlay);
}
foreach (var overlay in dummySettings.TextOverlays)
{
vm.Settings.TextOverlays.Add(overlay);
}
foreach (var overlay in dummySettings.ImageOverlays)
{
vm.Settings.ImageOverlays.Add(overlay);
}
Start(vm, Options);
}
})
.WithParsed<ShotCmdOptions>(Options =>
{
Banner();
using (var vm = ServiceProvider.Get<MainViewModel>())
{
vm.Init(false, false, false, false);
Shot(vm, Options);
}
})
.WithParsed<FFmpegCmdOptions>(Options =>
{
Banner();
FFmpeg(Options);
});
}
static void List()
{
Banner();
var underline = $"\n{new string('-', 30)}";
#region FFmpeg
var ffmpegExists = FFmpegService.FFmpegExists;
WriteLine($"FFmpeg Available: {(ffmpegExists ? "YES" : "NO")}");
WriteLine();
if (ffmpegExists)
{
WriteLine("FFmpeg ENCODERS" + underline);
var writerProvider = ServiceProvider.Get<FFmpegWriterProvider>();
var i = 0;
foreach (var codec in writerProvider)
{
WriteLine($"{i.ToString().PadRight(2)}: {codec}");
++i;
}
WriteLine();
}
#endregion
#region SharpAvi
var sharpAviExists = ServiceProvider.FileExists("SharpAvi.dll");
WriteLine($"SharpAvi Available: {(sharpAviExists ? "YES" : "NO")}");
WriteLine();
if (sharpAviExists)
{
WriteLine("SharpAvi ENCODERS" + underline);
var writerProvider = ServiceProvider.Get<SharpAviWriterProvider>();
var i = 0;
foreach (var codec in writerProvider)
{
WriteLine($"{i.ToString().PadRight(2)}: {codec}");
++i;
}
WriteLine();
}
#endregion
#region Windows
WriteLine("AVAILABLE WINDOWS" + underline);
// Window Picker is skipped automatically
foreach (var source in Window.EnumerateVisible())
{
WriteLine($"{source.Handle.ToString().PadRight(10)}: {source.Title}");
}
WriteLine();
#endregion
#region Screens
WriteLine("AVAILABLE SCREENS" + underline);
var j = 0;
// First is Full Screen, Second is Screen Picker
foreach (var screen in ScreenItem.Enumerate())
{
WriteLine($"{j.ToString().PadRight(2)}: {screen.Name}");
++j;
}
WriteLine();
#endregion
var audio = ServiceProvider.Get<AudioSource>();
WriteLine($"ManagedBass Available: {(audio is BassAudioSource ? "YES" : "NO")}");
WriteLine();
#region Microphones
if (audio.AvailableRecordingSources.Count > 0)
{
WriteLine("AVAILABLE MICROPHONES" + underline);
for (var i = 0; i < audio.AvailableRecordingSources.Count; ++i)
{
WriteLine($"{i.ToString().PadRight(2)}: {audio.AvailableRecordingSources[i]}");
}
WriteLine();
}
#endregion
#region Speaker
if (audio.AvailableLoopbackSources.Count > 0)
{
WriteLine("AVAILABLE SPEAKER SOURCES" + underline);
for (var i = 0; i < audio.AvailableLoopbackSources.Count; ++i)
{
WriteLine($"{i.ToString().PadRight(2)}: {audio.AvailableLoopbackSources[i]}");
}
WriteLine();
}
#endregion
#region Webcams
var webcam = ServiceProvider.Get<IWebCamProvider>();
if (webcam.AvailableCams.Count > 1)
{
WriteLine("AVAILABLE WEBCAMS" + underline);
for (var i = 1; i < webcam.AvailableCams.Count; ++i)
{
WriteLine($"{(i - 1).ToString().PadRight(2)}: {webcam.AvailableCams[i]}");
}
WriteLine();
}
#endregion
}
static void Banner()
{
var version = Assembly.GetExecutingAssembly().GetName().Version.ToString(3);
WriteLine($@"Captura v{version}
(c) {DateTime.Now.Year} Mathew Sachin
");
}
static void HandleVideoSource(MainViewModel ViewModel, CommonCmdOptions CommonOptions)
{
// Desktop
if (CommonOptions.Source == null || CommonOptions.Source == "desktop")
return;
var video = ViewModel.VideoViewModel;
// Region
if (Regex.IsMatch(CommonOptions.Source, @"^\d+,\d+,\d+,\d+$"))
{
if (MainViewModel.RectangleConverter.ConvertFromInvariantString(CommonOptions.Source) is Rectangle rect)
{
FakeRegionProvider.Instance.SelectedRegion = rect.Even();
video.SelectedVideoSourceKind = ServiceProvider.Get<RegionSourceProvider>();
}
}
// Screen
else if (Regex.IsMatch(CommonOptions.Source, @"^screen:\d+$"))
{
var index = int.Parse(CommonOptions.Source.Substring(7));
if (index < ScreenItem.Count)
{
var screenSourceProvider = ServiceProvider.Get<ScreenSourceProvider>();
screenSourceProvider.Set(index);
video.SelectedVideoSourceKind = screenSourceProvider;
}
}
// Window
else if (Regex.IsMatch(CommonOptions.Source, @"^win:\d+$"))
{
var handle = new IntPtr(int.Parse(CommonOptions.Source.Substring(4)));
var winProvider = ServiceProvider.Get<WindowSourceProvider>();
winProvider.Set(handle);
video.SelectedVideoSourceKind = winProvider;
}
// Start command only
else if (CommonOptions is StartCmdOptions)
{
// Desktop Duplication
if (Regex.IsMatch(CommonOptions.Source, @"^deskdupl:\d+$"))
{
var index = int.Parse(CommonOptions.Source.Substring(9));
if (index < ScreenItem.Count)
{
var deskDuplSourceProvider = ServiceProvider.Get<DeskDuplSourceProvider>();
deskDuplSourceProvider.Set(new ScreenWrapper(Screen.AllScreens[index]));
video.SelectedVideoSourceKind = deskDuplSourceProvider;
}
}
// No Video for Start
else if (CommonOptions.Source == "none")
{
video.SelectedVideoSourceKind = ServiceProvider.Get<NoVideoSourceProvider>();
}
}
}
static void HandleAudioSource(MainViewModel ViewModel, StartCmdOptions StartOptions)
{
var source = ViewModel.AudioSource;
if (StartOptions.Microphone != -1 && StartOptions.Microphone < source.AvailableRecordingSources.Count)
{
ViewModel.Settings.Audio.Enabled = true;
source.AvailableRecordingSources[StartOptions.Microphone].Active = true;
}
if (StartOptions.Speaker != -1 && StartOptions.Speaker < source.AvailableLoopbackSources.Count)
{
ViewModel.Settings.Audio.Enabled = true;
source.AvailableLoopbackSources[StartOptions.Speaker].Active = true;
}
}
static void HandleVideoEncoder(MainViewModel ViewModel, StartCmdOptions StartOptions)
{
if (StartOptions.Encoder == null)
return;
var video = ViewModel.VideoViewModel;
// FFmpeg
if (FFmpegService.FFmpegExists && Regex.IsMatch(StartOptions.Encoder, @"^ffmpeg:\d+$"))
{
var index = int.Parse(StartOptions.Encoder.Substring(7));
video.SelectedVideoWriterKind = ServiceProvider.Get<FFmpegWriterProvider>();
if (index < video.AvailableVideoWriters.Count)
video.SelectedVideoWriter = video.AvailableVideoWriters[index];
}
// SharpAvi
else if (ServiceProvider.FileExists("SharpAvi.dll") && Regex.IsMatch(StartOptions.Encoder, @"^sharpavi:\d+$"))
{
var index = int.Parse(StartOptions.Encoder.Substring(9));
video.SelectedVideoWriterKind = ServiceProvider.Get<SharpAviWriterProvider>();
if (index < video.AvailableVideoWriters.Count)
video.SelectedVideoWriter = video.AvailableVideoWriters[index];
}
// Gif
else if (StartOptions.Encoder == "gif")
{
video.SelectedVideoWriterKind = ServiceProvider.Get<GifWriterProvider>();
}
}
static void HandleWebcam(StartCmdOptions StartOptions)
{
var webcam = ServiceProvider.Get<IWebCamProvider>();
if (StartOptions.Webcam != -1 && StartOptions.Webcam < webcam.AvailableCams.Count - 1)
{
webcam.SelectedCam = webcam.AvailableCams[StartOptions.Webcam + 1];
// Sleep to prevent AccessViolationException
Thread.Sleep(500);
}
}
static async void FFmpeg(FFmpegCmdOptions FFmpegOptions)
{
if (FFmpegOptions.Install != null)
{
var downloadFolder = FFmpegOptions.Install;
if (!Directory.Exists(downloadFolder))
{
WriteLine("Directory doesn't exist");
return;
}
var ffMpegDownload = ServiceProvider.Get<FFmpegDownloadViewModel>();
ffMpegDownload.TargetFolder = FFmpegOptions.Install;
await ffMpegDownload.Start();
WriteLine(ffMpegDownload.Status);
}
}
static void Shot(MainViewModel ViewModel, ShotCmdOptions ShotOptions)
{
ViewModel.Settings.IncludeCursor = ShotOptions.Cursor;
// Screenshot Window with Transparency
if (ShotOptions.Source != null && Regex.IsMatch(ShotOptions.Source, @"win:\d+"))
{
var ptr = int.Parse(ShotOptions.Source.Substring(4));
try
{
var bmp = ViewModel.ScreenShotViewModel.ScreenShotWindow(new Window(new IntPtr(ptr)));
ViewModel.ScreenShotViewModel.SaveScreenShot(bmp, ShotOptions.FileName).Wait();
}
catch
{
// Suppress Errors
}
}
else
{
HandleVideoSource(ViewModel, ShotOptions);
ViewModel.ScreenShotViewModel.CaptureScreenShot(ShotOptions.FileName);
}
}
static void Start(MainViewModel ViewModel, StartCmdOptions StartOptions)
{
ViewModel.Settings.IncludeCursor = StartOptions.Cursor;
ViewModel.Settings.Clicks.Display = StartOptions.Clicks;
ViewModel.Settings.Keystrokes.Display = StartOptions.Keys;
if (File.Exists(StartOptions.FileName))
{
if (!StartOptions.Overwrite)
{
if (!ServiceProvider.MessageProvider
.ShowYesNo("Output File Already Exists, Do you want to overwrite?", ""))
return;
}
File.Delete(StartOptions.FileName);
}
HandleVideoSource(ViewModel, StartOptions);
HandleVideoEncoder(ViewModel, StartOptions);
HandleAudioSource(ViewModel, StartOptions);
HandleWebcam(StartOptions);
ViewModel.Settings.Video.FrameRate = StartOptions.FrameRate;
ViewModel.Settings.Audio.Quality = StartOptions.AudioQuality;
ViewModel.Settings.Video.Quality = StartOptions.VideoQuality;
if (!ViewModel.RecordingViewModel.RecordCommand.CanExecute(null))
{
WriteLine("Nothing to Record");
return;
}
if (StartOptions.Delay > 0)
Thread.Sleep(StartOptions.Delay);
if (!ViewModel.RecordingViewModel.StartRecording(StartOptions.FileName))
return;
Task.Factory.StartNew(() =>
{
Loop(ViewModel, StartOptions);
ViewModel.RecordingViewModel.StopRecording().Wait();
Application.Exit();
});
// MouseKeyHook requires a Window Handle to register
Application.Run(new ApplicationContext());
}
static void Loop(MainViewModel ViewModel, StartCmdOptions StartOptions)
{
if (StartOptions.Length > 0)
{
var elapsed = 0;
Write(TimeSpan.Zero);
while (elapsed++ < StartOptions.Length)
{
Thread.Sleep(1000);
Write(new string('\b', 8) + TimeSpan.FromSeconds(elapsed));
}
Write(new string('\b', 8));
}
else
{
const string recordingText = "Press p to pause or resume, q to quit";
WriteLine(recordingText);
char ReadChar()
{
if (IsInputRedirected)
{
var line = ReadLine();
if (line != null && line.Length == 1)
return line[0];
return char.MinValue;
}
return char.ToLower(ReadKey(true).KeyChar);
}
char c;
do
{
c = ReadChar();
if (c != 'p')
continue;
ViewModel.RecordingViewModel.PauseCommand.ExecuteIfCan();
if (ViewModel.RecordingViewModel.RecorderState != RecorderState.Paused)
{
WriteLine("Resumed");
}
} while (c != 'q');
}
}
}
}
| 32.17029 | 122 | 0.505181 | [
"MIT"
] | sonumeewa/Captura | src/Captura.Console/Program.cs | 17,760 | C# |
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace T4TS.Build.Builder
{
class SourceFileMerger
{
static readonly SourceFileVisitor Visitor = new SourceFileVisitor();
/// <summary>
/// Merges all the source files (they are assumed to be C# files).
/// </summary>
/// <returns>A string with all C# classes found in the source files.</returns>
public string MergeSourceFileClasses(IEnumerable<FileInfo> files)
{
Visitor.Clear();
foreach (var file in files)
VisitFile(file);
var sb = new StringBuilder();
sb.AppendLine();
foreach (string classDefinition in Visitor.Classes)
{
// Indentation is important!
sb.Append(" ");
sb.AppendLine(classDefinition);
sb.AppendLine();
}
return sb.ToString();
}
void VisitFile(FileInfo file)
{
using (var sr = new StreamReader(file.OpenRead()))
{
var syntaxTree = CSharpSyntaxTree.ParseText(sr.ReadToEnd());
var root = (CompilationUnitSyntax)syntaxTree.GetRoot();
foreach (var child in root.ChildNodes())
VisitNode(child as CSharpSyntaxNode);
}
}
void VisitNode(CSharpSyntaxNode node)
{
if (node == null)
return;
node.Accept(Visitor);
var children = node.ChildNodes();
if (children != null)
{
foreach (var child in children)
VisitNode(child as CSharpSyntaxNode);
}
}
}
}
| 28.454545 | 86 | 0.530351 | [
"Apache-2.0"
] | Panopto/panopto-t4ts | T4TS.Build.Builder/SourceFileMerger.cs | 1,880 | C# |
using System;
using System.Runtime.InteropServices;
using UnityEngine;
namespace bosqmode.libvlc
{
public class VLCPlayer : IDisposable
{
private IntPtr _media;
private IntPtr _mediaPlayer;
private IntPtr _imageIntPtr;
private IntPtr _libvlc;
private LockCB _lockHandle;
private UnlockCB _unlockHandle;
private DisplayCB _displayHandle;
private GCHandle _gcHandle;
private bool _locked = true;
private bool _update = false;
private byte[] _currentImage;
private int _width = 480;
private int _height = 256;
private int _channels = 3;
private const string _defaultArgs = "--ignore-config;--no-xlib;--no-video-title-show;--no-osd";
private libvlc_video_track_t? _videoTrack = null;
private IntPtr _tracktorelease;
private int _tracks;
private volatile bool _cancel = false;
/// <summary>
/// Gets the video tracks information that libvlc receives
/// </summary>
public libvlc_video_track_t? VideoTrack
{
get
{
return _videoTrack;
}
}
/// <summary>
/// Checks if image has been updated since last check, and outs the image bytes
/// </summary>
/// <param name="currentImage">arr where to store the image bytes</param>
/// <returns>whether update happened or not</returns>
public bool CheckForImageUpdate(out byte[] currentImage)
{
currentImage = null;
if (_update)
{
currentImage = _currentImage;
_update = false;
return true;
}
return false;
}
public VLCPlayer(int width, int height, string mediaUrl, bool audio)
{
Debug.Log("Playing: " + mediaUrl);
_width = width;
_height = height;
_gcHandle = GCHandle.Alloc(this);
string argstrings = _defaultArgs;
if (!audio)
{
argstrings += ";--no-audio";
}
string[] args = argstrings.Split(';');
_libvlc = LibVLCWrapper.libvlc_new(args.Length, args);
if (_libvlc == IntPtr.Zero)
{
Debug.LogError("Failed loading new libvlc instance...");
return;
}
_media = LibVLCWrapper.libvlc_media_new_location(_libvlc, mediaUrl);
if (_media == IntPtr.Zero)
{
Debug.LogError("For some reason media is null, maybe typo in the URL?");
return;
}
_mediaPlayer = LibVLCWrapper.libvlc_media_player_new(_libvlc);
LibVLCWrapper.libvlc_media_player_set_media(_mediaPlayer, _media);
_lockHandle = vlc_lock;
_unlockHandle = vlc_unlock;
_displayHandle = vlc_picture;
LibVLCWrapper.libvlc_video_set_callbacks(_mediaPlayer, _lockHandle, _unlockHandle, _displayHandle, GCHandle.ToIntPtr(_gcHandle));
LibVLCWrapper.libvlc_video_set_format(_mediaPlayer, "RV24", (uint)_width, (uint)_height, (uint)_width * (uint)_channels);
LibVLCWrapper.libvlc_media_player_play(_mediaPlayer);
System.Threading.Thread t = new System.Threading.Thread(TrackReaderThread);
t.Start();
}
private void TrackReaderThread()
{
int _trackGetAttempts = 0;
while (_trackGetAttempts < 10 && _cancel == false)
{
libvlc_video_track_t? track = GetVideoTrack();
if (track.HasValue && track.Value.i_width > 0 && track.Value.i_height > 0)
{
_videoTrack = track;
if (_width <= 0 || _height <= 0)
{
_width = (int)_videoTrack.Value.i_width;
_height = (int)_videoTrack.Value.i_height;
LibVLCWrapper.libvlc_video_set_format(_mediaPlayer, "RV24", _videoTrack.Value.i_width, _videoTrack.Value.i_height, (uint)_width * (uint)_channels);
}
break;
}
_trackGetAttempts++;
System.Threading.Thread.Sleep(500);
}
if (_trackGetAttempts >= 10)
{
Debug.LogError("Maximum attempts of getting video track reached, maybe opening failed?");
}
}
private void vlc_unlock(IntPtr opaque, IntPtr picture, ref IntPtr planes)
{
_locked = false;
}
private IntPtr vlc_lock(IntPtr opaque, ref IntPtr planes)
{
_locked = true;
if (_imageIntPtr == IntPtr.Zero)
{
_imageIntPtr = Marshal.AllocHGlobal(_width * _channels * _height);
}
planes = _imageIntPtr;
return _imageIntPtr;
}
private void vlc_picture(IntPtr opaque, IntPtr picture)
{
if (!_update)
{
_currentImage = new byte[_width * _channels * _height];
Marshal.Copy(picture, _currentImage, 0, _width * _channels * _height);
_update = true;
}
}
private libvlc_video_track_t? GetVideoTrack()
{
libvlc_video_track_t? vtrack = null;
IntPtr p;
int tracks = LibVLCWrapper.libvlc_media_tracks_get(_media, out p);
_tracks = tracks;
_tracktorelease = p;
for (int i = 0; i < tracks; i++)
{
IntPtr mtrackptr = Marshal.ReadIntPtr(p, i * IntPtr.Size);
libvlc_media_track_t mtrack = Marshal.PtrToStructure<libvlc_media_track_t>(mtrackptr);
if (mtrack.i_type == libvlc_track_type_t.libvlc_track_video)
{
vtrack = Marshal.PtrToStructure<libvlc_video_track_t>(mtrack.media);
}
}
return vtrack;
}
public void Dispose()
{
_cancel = true;
if (_tracktorelease != IntPtr.Zero)
{
LibVLCWrapper.libvlc_media_tracks_release(_tracktorelease, _tracks);
}
if (_mediaPlayer != IntPtr.Zero)
{
LibVLCWrapper.libvlc_media_player_release(_mediaPlayer);
}
if (_media != IntPtr.Zero)
{
LibVLCWrapper.libvlc_media_release(_media);
}
if (_libvlc != IntPtr.Zero)
{
LibVLCWrapper.libvlc_release(_libvlc);
}
_mediaPlayer = IntPtr.Zero;
_media = IntPtr.Zero;
_libvlc = IntPtr.Zero;
}
}
} | 31.958333 | 171 | 0.5402 | [
"MIT"
] | bosqmode/UnityVLCPlayer | Assets/UnityVLCPlayer/VLCPlayer.cs | 6,905 | C# |
using System;
using System.Diagnostics;
using System.Threading;
namespace Unity_Interception
{
public class Logger
{
internal void WriteFunctionStart(FunctionStartInfo v)
{
WriteLine(v.ToString());
}
internal void WriteFunctionEndInfo(FunctionEndInfo v)
{
WriteLine(v.ToString());
}
internal void WriteException(ExceptionInfo ei)
{
WriteLine(ei.ToString());
}
private void WriteLine(string msg)
{
Trace.WriteLine($"Thread Id:{Thread.CurrentThread.ManagedThreadId},{msg}");
}
}
} | 22.785714 | 87 | 0.590909 | [
"Apache-2.0"
] | joymon/dotnet-demos | patterns-practices/DI/unity/Interception/Unity_Interception/Logging/InterceptionLogger.cs | 640 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace TweetSharp.Demo.Mvc.Models
{
#region Models
public class ChangePasswordModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LogOnModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
#endregion
#region Services
// The FormsAuthentication type is sealed and contains static members, so it is difficult to
// unit test code that calls its members. The interface and helper class below demonstrate
// how to create an abstract wrapper around such a type in order to make the AccountController
// code unit testable.
public interface IMembershipService
{
int MinPasswordLength { get; }
bool ValidateUser(string userName, string password);
MembershipCreateStatus CreateUser(string userName, string password, string email);
bool ChangePassword(string userName, string oldPassword, string newPassword);
}
public class AccountMembershipService : IMembershipService
{
private readonly MembershipProvider _provider;
public AccountMembershipService()
: this(null)
{
}
public AccountMembershipService(MembershipProvider provider)
{
_provider = provider ?? Membership.Provider;
}
public int MinPasswordLength
{
get
{
return _provider.MinRequiredPasswordLength;
}
}
public bool ValidateUser(string userName, string password)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
return _provider.ValidateUser(userName, password);
}
public MembershipCreateStatus CreateUser(string userName, string password, string email)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
MembershipCreateStatus status;
_provider.CreateUser(userName, password, email, null, null, true, null, out status);
return status;
}
public bool ChangePassword(string userName, string oldPassword, string newPassword)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");
// The underlying ChangePassword() will throw an exception rather
// than return false in certain failure scenarios.
try
{
MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */);
return currentUser.ChangePassword(oldPassword, newPassword);
}
catch (ArgumentException)
{
return false;
}
catch (MembershipPasswordException)
{
return false;
}
}
}
public interface IFormsAuthenticationService
{
void SignIn(string userName, bool createPersistentCookie);
void SignOut();
}
public class FormsAuthenticationService : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
#endregion
#region Validation
public static class AccountValidation
{
public static string ErrorCodeToString(MembershipCreateStatus createStatus)
{
// See http://go.microsoft.com/fwlink/?LinkID=177550 for
// a full list of status codes.
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
return "Username already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A username for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidUserName:
return "The user name provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidatePasswordLengthAttribute : ValidationAttribute, IClientValidatable
{
private const string _defaultErrorMessage = "'{0}' must be at least {1} characters long.";
private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;
public ValidatePasswordLengthAttribute()
: base(_defaultErrorMessage)
{
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture, ErrorMessageString,
name, _minCharacters);
}
public override bool IsValid(object value)
{
string valueAsString = value as string;
return (valueAsString != null && valueAsString.Length >= _minCharacters);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new[]{
new ModelClientValidationStringLengthRule(FormatErrorMessage(metadata.GetDisplayName()), _minCharacters, int.MaxValue)
};
}
}
#endregion
}
| 37.607143 | 183 | 0.642292 | [
"MIT"
] | DavidChristiansen/tweetsharp | src/net40/TweetSharp.Demo.Mvc/Models/AccountModels.cs | 9,479 | C# |
using System;
namespace m4k.Progression {
[Serializable]
public abstract class Condition {
public virtual void InitializeCondition() {}
public abstract bool CheckConditionMet();
public virtual void FinalizeCondition() {}
}
} | 23.7 | 48 | 0.755274 | [
"MIT"
] | khncao/com.minus4kelvin.core | Runtime/Progression/Conditions/Condition.cs | 237 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrbitCamera : MonoBehaviour {
[SerializeField]
private Transform target = null;
public float rotateSpeed = 1.5f;
private float _rotateY;
private Vector3 _offset;
// Use this for initialization
void Start () {
_rotateY = transform.eulerAngles.y;
_offset = target.position - transform.position;
}
private void LateUpdate() {
float horInput = Input.GetAxis("Horizontal");
if (horInput != 0) {
_rotateY += horInput * rotateSpeed;
} else {
_rotateY += Input.GetAxis("Mouse X") * rotateSpeed * 3;
}
Quaternion rotation = Quaternion.Euler(0, _rotateY, 0);
transform.position = target.position - (rotation * _offset);
transform.LookAt(target);
}
// Update is called once per frame
void Update () {
}
}
| 25.135135 | 68 | 0.634409 | [
"MIT"
] | mrvon/Unity | TPG/Assets/Scripts/OrbitCamera.cs | 932 | C# |
using Newtonsoft.Json;
using RealView.Core.Model;
using RealView.Core.Parser;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
namespace RealView.Providers.KickAss
{
public class KickAssParser : ParserContract
{
private Regex pattern;
private Regex metaPattern;
public KickAssParser()
{
pattern = new Regex(@"<tr.+?id=""[\s\S]+?<\/tr>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
metaPattern = new Regex(@"data-sc-params=""(.+?)""", RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
public ResourceSet Parse(object o)
{
ResourceSet resources = null;
Stream rawStream = null;
GZipStream gzipStream = null;
StreamReader reader = null;
try
{
rawStream = (Stream) o;
gzipStream = new GZipStream(rawStream, CompressionMode.Decompress);
reader = new StreamReader(gzipStream);
String result = reader.ReadToEnd();
resources = Compose(result);
}
catch (Exception)
{
}
finally
{
if (reader != null) reader.Close();
if (gzipStream != null) gzipStream.Close();
if (rawStream != null) rawStream.Close();
}
return resources;
}
public ResourceSet Compose(string data)
{
ResourceSet resources = new ResourceSet();
MatchCollection matches = pattern.Matches(data);
if (matches.Count > 0)
{
resources.ResourceList = new List<ResourceInfo>(matches.Count);
foreach (Match match in matches)
{
var meta = metaPattern.Match(match.Value);
// Convent to MetaInfo instance
MetaInfo mi = JsonConvert.DeserializeObject<MetaInfo>(meta.Groups[1].Value);
ResourceInfo ri = new ResourceInfo();
ri.Title = HttpUtility.UrlDecode(mi.Name);
ri.MagnetLink = HttpUtility.UrlDecode(mi.Magnet);
resources.ResourceList.Add(ri);
}
}
return resources;
}
}
}
| 28.793103 | 114 | 0.546906 | [
"Apache-2.0"
] | soxfmr/RealView | RealView/Providers/KickAss/KickAssParser.cs | 2,507 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ListExtensions.cs" company="Helix Toolkit">
// Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace HelixToolkit.Wpf.SharpDX.Extensions
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
public static class CollectionExtensions
{
static class ArrayAccessor<T>
{
public static readonly Func<List<T>, T[]> Getter;
static ArrayAccessor()
{
var dm = new DynamicMethod(
"get",
MethodAttributes.Static | MethodAttributes.Public,
CallingConventions.Standard,
typeof(T[]),
new Type[] { typeof(List<T>) },
typeof(ArrayAccessor<T>),
true);
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // Load List<T> argument
il.Emit(OpCodes.Ldfld,
typeof(List<T>).GetField("_items",
BindingFlags.NonPublic | BindingFlags.Instance)); // Replace argument by field
il.Emit(OpCodes.Ret); // Return field
Getter = (Func<List<T>, T[]>)dm.CreateDelegate(typeof(Func<List<T>, T[]>));
}
}
/// <summary>
/// Gets the internal array of a <see cref="List{T}"/>.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="list">The respective list.</param>
/// <returns>The internal array of the list.</returns>
public static T[] GetInternalArray<T>(this List<T> list)
{
return ArrayAccessor<T>.Getter(list);
}
/// <summary>
/// Tries to get a value from a <see cref="IDictionary{K,V}"/>.
/// </summary>
/// <typeparam name="K">The type of the key.</typeparam>
/// <typeparam name="V">The type of the value.</typeparam>
/// <param name="dict">The respective dictionary.</param>
/// <param name="key">The respective key.</param>
/// <returns>The value if exists, else <c>null</c>.</returns>
public static V Get<K, V>(this IDictionary<K, V> dict, K key)
{
V val;
if (dict.TryGetValue(key, out val))
{
return val;
}
return default(V);
}
}
}
| 39.183099 | 121 | 0.468368 | [
"MIT"
] | Unknown6656/helix-toolkit | Source/HelixToolkit.Wpf.SharpDX/Extensions/CollectionExtensions.cs | 2,784 | 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.
#if ENABLEDATABINDING
using System;
using Microsoft.Xml;
using Microsoft.Xml.XPath;
using Microsoft.Xml.Schema;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
namespace Microsoft.Xml.XPath.DataBinding
{
internal class XPathNodeViewPropertyDescriptor : PropertyDescriptor {
Shape rowShape;
Shape colShape;
int colIndex;
internal XPathNodeViewPropertyDescriptor(Shape rowShape)
: base( rowShape.Name, null) {
this.rowShape = rowShape;
this.colShape = rowShape;
this.colIndex = 0;
}
internal XPathNodeViewPropertyDescriptor(Shape rowShape, Shape colShape, int colIndex)
: base( colShape.Name, null) {
this.rowShape = rowShape;
this.colShape = colShape;
this.colIndex = colIndex;
}
public Shape Shape {
get { return colShape; }
}
public override Type ComponentType {
get { return null; }
}
public override string Name {
get { return this.colShape.Name; }
}
public override bool IsReadOnly {
get { return true; }
}
public override Type PropertyType {
get {
return this.colShape.IsNestedTable
? typeof(XPathDocumentView)
: typeof(string);
}
}
public override bool CanResetValue(object o) {
return false;
}
public override object GetValue(object o) {
if (null == o)
throw new ArgumentNullException("XPathNodeViewPropertyDescriptor.GetValue");
XPathNodeView xiv = (XPathNodeView)o;
if (xiv.Collection.RowShape != this.rowShape)
throw new ArgumentException("XPathNodeViewPropertyDescriptor.GetValue");
object val = xiv.Column(this.colIndex);
XPathNode nd = val as XPathNode;
if (null != nd) {
XPathDocumentNavigator nav = new XPathDocumentNavigator(nd, null);
XmlSchemaType xst = nd.SchemaType;
XmlSchemaComplexType xsct = xst as XmlSchemaComplexType;
if (null == xst || ( (null != xsct) && xsct.IsMixed) ) {
return nav.InnerXml;
}
else {
return nav.TypedValue;
}
}
return val;
}
public override void ResetValue(object o) {
throw new NotImplementedException();
}
public override void SetValue(object o, object value) {
throw new NotImplementedException();
}
public override bool ShouldSerializeValue(object o) {
return false;
}
}
}
#endif
| 31.343434 | 95 | 0.577506 | [
"MIT"
] | Bencargs/wcf | src/dotnet-svcutil/lib/src/FrameworkFork/Microsoft.Xml/Xml/Cache/XPathNodeViewPropertyDescriptor.cs | 3,103 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Instrucciones : MonoBehaviour
{
// Start is called before the first frame update
public void PlayGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
}
public void Menu()
{
SceneManager.LoadScene(0);
}
}
| 21.25 | 78 | 0.670588 | [
"MIT"
] | codyvi/Parcial2Scripts | Scripts/Instrucciones.cs | 427 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V4200</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V4200 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="xhtml:NPfIT:PresentationText")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="xhtml:NPfIT:PresentationText")]
public partial class bodyType {
private object[] itemsField;
private static System.Xml.Serialization.XmlSerializer serializer;
[System.Xml.Serialization.XmlElementAttribute("a", typeof(a))]
[System.Xml.Serialization.XmlElementAttribute("br", typeof(brType))]
[System.Xml.Serialization.XmlElementAttribute("h2", typeof(h2))]
[System.Xml.Serialization.XmlElementAttribute("h3", typeof(h3))]
[System.Xml.Serialization.XmlElementAttribute("h4", typeof(h4))]
[System.Xml.Serialization.XmlElementAttribute("h5", typeof(h5))]
[System.Xml.Serialization.XmlElementAttribute("h6", typeof(h6))]
[System.Xml.Serialization.XmlElementAttribute("ol", typeof(ol))]
[System.Xml.Serialization.XmlElementAttribute("p", typeof(p))]
[System.Xml.Serialization.XmlElementAttribute("pre", typeof(pre))]
[System.Xml.Serialization.XmlElementAttribute("table", typeof(table))]
[System.Xml.Serialization.XmlElementAttribute("ul", typeof(ul))]
public object[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(bodyType));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current bodyType object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if ((streamReader != null)) {
streamReader.Dispose();
}
if ((memoryStream != null)) {
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an bodyType object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output bodyType object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out bodyType obj, out System.Exception exception) {
exception = null;
obj = default(bodyType);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out bodyType obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static bodyType Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((bodyType)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current bodyType object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception) {
exception = null;
try {
SaveToFile(fileName);
return true;
}
catch (System.Exception e) {
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName) {
System.IO.StreamWriter streamWriter = null;
try {
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally {
if ((streamWriter != null)) {
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an bodyType object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output bodyType object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out bodyType obj, out System.Exception exception) {
exception = null;
obj = default(bodyType);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out bodyType obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static bodyType LoadFromFile(string fileName) {
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try {
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally {
if ((file != null)) {
file.Dispose();
}
if ((sr != null)) {
sr.Dispose();
}
}
}
#endregion
#region Clone method
/// <summary>
/// Create a clone of this bodyType object
/// </summary>
public virtual bodyType Clone() {
return ((bodyType)(this.MemberwiseClone()));
}
#endregion
}
}
| 45.446009 | 1,358 | 0.586054 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V4200/Generated/bodyType.cs | 9,680 | C# |
using UnityEngine;
namespace CustomAvatar
{
public class FirstPersonExclusion : MonoBehaviour
{
[HideInInspector] public GameObject[] Exclude;
public GameObject[] exclude;
public void Awake()
{
if (Exclude != null && Exclude.Length > 0) exclude = Exclude;
}
}
} | 21.866667 | 73 | 0.603659 | [
"MIT"
] | ErrorUser-not-found/BeatSaberCustomAvatars | Source/CustomAvatar/FirstPersonExclusion.cs | 330 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SmartCarRentals.Data;
namespace SmartCarRentals.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20200328195953_AddTransferType")]
partial class AddTransferType
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.2")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("Name")
.HasColumnType("nvarchar(450)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.ApplicationRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("Address")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<int>("Age")
.HasColumnType("int");
b.Property<DateTime>("BirthDate")
.HasColumnType("datetime2");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Nationality")
.HasColumnType("nvarchar(max)");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<int?>("ParkingId")
.HasColumnType("int");
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<int>("Points")
.HasColumnType("int");
b.Property<int>("Rank")
.HasColumnType("int");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.HasIndex("ParkingId");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Car", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ApplicationUserId")
.HasColumnType("nvarchar(450)");
b.Property<int>("Class")
.HasColumnType("int");
b.Property<int>("Condition")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("Fuel")
.HasColumnType("int");
b.Property<int>("HireStatus")
.HasColumnType("int");
b.Property<string>("Image")
.IsRequired()
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int>("KmRun")
.HasColumnType("int");
b.Property<string>("Make")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<string>("Model")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int?>("ParkingId")
.HasColumnType("int");
b.Property<int>("PassengersCapacity")
.HasColumnType("int");
b.Property<string>("PlateNumber")
.IsRequired()
.HasColumnType("nvarchar(30)")
.HasMaxLength(30);
b.Property<int>("PricePerDay")
.HasColumnType("int");
b.Property<int>("PricePerHour")
.HasColumnType("int");
b.Property<double?>("Rating")
.HasColumnType("float");
b.Property<int>("ReservationStatus")
.HasColumnType("int");
b.Property<int>("ServiceStatus")
.HasColumnType("int");
b.Property<int>("Transmition")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ApplicationUserId");
b.HasIndex("IsDeleted");
b.HasIndex("ParkingId");
b.ToTable("Cars");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.CarRating", b =>
{
b.Property<string>("CarId")
.HasColumnType("nvarchar(450)");
b.Property<string>("ClientId")
.HasColumnType("nvarchar(450)");
b.Property<int>("TripId")
.HasColumnType("int");
b.Property<string>("Coment")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("Id")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<double>("RatingVote")
.HasColumnType("float");
b.HasKey("CarId", "ClientId", "TripId");
b.HasIndex("ClientId");
b.HasIndex("IsDeleted");
b.HasIndex("TripId")
.IsUnique();
b.ToTable("CarsRatings");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Country", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.ToTable("Countries");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Driver", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<string>("Image")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<double>("Rating")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.ToTable("Drivers");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.DriverRating", b =>
{
b.Property<string>("DriverId")
.HasColumnType("nvarchar(450)");
b.Property<string>("ClientId")
.HasColumnType("nvarchar(450)");
b.Property<int>("TransferId")
.HasColumnType("int");
b.Property<string>("Coment")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("Id")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<double>("RatingVote")
.HasColumnType("float");
b.HasKey("DriverId", "ClientId", "TransferId");
b.HasIndex("ClientId");
b.HasIndex("IsDeleted");
b.HasIndex("TransferId")
.IsUnique();
b.ToTable("DriversRatings");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Parking", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<int>("Capacity")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<int>("FreeParkingSlots")
.HasColumnType("int");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<int>("TownId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.HasIndex("TownId");
b.ToTable("Parkings");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.ParkingSlot", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("CarId")
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int>("Number")
.HasColumnType("int");
b.Property<int>("ParkingId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("IsDeleted");
b.HasIndex("ParkingId");
b.ToTable("ParkingSlots");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Reservation", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("CarId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int>("ParkingId")
.HasColumnType("int");
b.Property<DateTime>("ReservationDate")
.HasColumnType("datetime2");
b.Property<int>("Status")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("ClientId");
b.HasIndex("IsDeleted");
b.HasIndex("ParkingId");
b.ToTable("Reservations");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Setting", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.ToTable("Settings");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Town", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CountryId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.HasKey("Id");
b.HasIndex("CountryId");
b.HasIndex("IsDeleted");
b.ToTable("Towns");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Transfer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClientId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<string>("DriverId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int?>("DriverRatingId")
.HasColumnType("int");
b.Property<string>("EndingLokation")
.IsRequired()
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int>("Points")
.HasColumnType("int");
b.Property<decimal>("Price")
.HasColumnType("decimal(18,4)");
b.Property<string>("StartingLocation")
.IsRequired()
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<DateTime>("TransferDate")
.HasColumnType("datetime2");
b.Property<int>("TransferTypeId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("DriverId");
b.HasIndex("IsDeleted");
b.HasIndex("TransferTypeId");
b.ToTable("Transfers");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.TransferType", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<decimal>("Price")
.HasColumnType("decimal(18,4)");
b.HasKey("Id");
b.HasIndex("IsDeleted");
b.ToTable("TransfersTypes");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Trip", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("CarId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int?>("CarRatingId")
.HasColumnType("int");
b.Property<string>("ClientId")
.HasColumnType("nvarchar(450)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime?>("DeletedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("EndDate")
.HasColumnType("datetime2");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int?>("KmRun")
.HasColumnType("int");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<int>("Points")
.HasColumnType("int");
b.Property<decimal>("Price")
.HasColumnType("decimal(18,4)");
b.Property<int>("Status")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("ClientId");
b.HasIndex("IsDeleted");
b.ToTable("Trips");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("SmartCarRentals.Data.Models.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("SmartCarRentals.Data.Models.ApplicationUser", null)
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("SmartCarRentals.Data.Models.ApplicationUser", null)
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("SmartCarRentals.Data.Models.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("SmartCarRentals.Data.Models.ApplicationUser", null)
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("SmartCarRentals.Data.Models.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("SmartCarRentals.Data.Models.ApplicationUser", b =>
{
b.HasOne("SmartCarRentals.Data.Models.Parking", "Parking")
.WithMany()
.HasForeignKey("ParkingId");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Car", b =>
{
b.HasOne("SmartCarRentals.Data.Models.ApplicationUser", null)
.WithMany("Cars")
.HasForeignKey("ApplicationUserId");
b.HasOne("SmartCarRentals.Data.Models.Parking", "Parking")
.WithMany("Cars")
.HasForeignKey("ParkingId");
});
modelBuilder.Entity("SmartCarRentals.Data.Models.CarRating", b =>
{
b.HasOne("SmartCarRentals.Data.Models.Car", "Car")
.WithMany("Ratings")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("SmartCarRentals.Data.Models.ApplicationUser", "Client")
.WithMany("CarRatings")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("SmartCarRentals.Data.Models.Trip", "Trip")
.WithOne("CarRating")
.HasForeignKey("SmartCarRentals.Data.Models.CarRating", "TripId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("SmartCarRentals.Data.Models.DriverRating", b =>
{
b.HasOne("SmartCarRentals.Data.Models.ApplicationUser", "Client")
.WithMany("DriverRatings")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("SmartCarRentals.Data.Models.Driver", "Driver")
.WithMany("Ratings")
.HasForeignKey("DriverId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("SmartCarRentals.Data.Models.Transfer", "Transfer")
.WithOne("DriverRating")
.HasForeignKey("SmartCarRentals.Data.Models.DriverRating", "TransferId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Parking", b =>
{
b.HasOne("SmartCarRentals.Data.Models.Town", "Town")
.WithMany("Parkings")
.HasForeignKey("TownId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("SmartCarRentals.Data.Models.ParkingSlot", b =>
{
b.HasOne("SmartCarRentals.Data.Models.Car", "Car")
.WithMany()
.HasForeignKey("CarId");
b.HasOne("SmartCarRentals.Data.Models.Parking", "Parking")
.WithMany("ParkingSlots")
.HasForeignKey("ParkingId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Reservation", b =>
{
b.HasOne("SmartCarRentals.Data.Models.Car", "Car")
.WithMany()
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("SmartCarRentals.Data.Models.ApplicationUser", "Client")
.WithMany("Reservations")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("SmartCarRentals.Data.Models.Parking", "Parking")
.WithMany("Reservations")
.HasForeignKey("ParkingId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Town", b =>
{
b.HasOne("SmartCarRentals.Data.Models.Country", "Country")
.WithMany("Towns")
.HasForeignKey("CountryId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Transfer", b =>
{
b.HasOne("SmartCarRentals.Data.Models.ApplicationUser", "Client")
.WithMany("Transfers")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("SmartCarRentals.Data.Models.Driver", "Driver")
.WithMany("Transfers")
.HasForeignKey("DriverId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("SmartCarRentals.Data.Models.TransferType", "Type")
.WithMany("Transfers")
.HasForeignKey("TransferTypeId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("SmartCarRentals.Data.Models.Trip", b =>
{
b.HasOne("SmartCarRentals.Data.Models.Car", "Car")
.WithMany("Trips")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("SmartCarRentals.Data.Models.ApplicationUser", "Client")
.WithMany("Trips")
.HasForeignKey("ClientId");
});
#pragma warning restore 612, 618
}
}
}
| 36.468435 | 125 | 0.437832 | [
"MIT"
] | ulivegenov/SmartCarRentals | Data/SmartCarRentals.Data/Migrations/20200328195953_AddTransferType.Designer.cs | 39,862 | C# |
/*
Copyright (c) 2014 <a href="http://www.gutgames.com">James Craig</a>
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.Data;
using System.Linq;
using Utilities.DataTypes;
using Utilities.ORM.Interfaces;
using Utilities.ORM.Manager.Schema.Default.Database;
using Utilities.ORM.Manager.Schema.Interfaces;
using Utilities.ORM.Manager.SourceProvider.Interfaces;
using Xunit;
namespace UnitTests.ORM.Manager
{
public class ORMManager : DatabaseBaseClass
{
[Fact]
public void Create()
{
var Temp = new Utilities.ORM.Manager.ORMManager(Utilities.IoC.Manager.Bootstrapper.Resolve<Utilities.ORM.Manager.Mapper.Manager>(),
Utilities.IoC.Manager.Bootstrapper.Resolve<Utilities.ORM.Manager.QueryProvider.Manager>(),
Utilities.IoC.Manager.Bootstrapper.Resolve<Utilities.ORM.Manager.Schema.Manager>(),
Utilities.IoC.Manager.Bootstrapper.Resolve<Utilities.ORM.Manager.SourceProvider.Manager>(),
Utilities.IoC.Manager.Bootstrapper.ResolveAll<IDatabase>());
Assert.NotNull(Temp);
Assert.Equal("ORM Manager\r\n", Temp.ToString());
}
}
} | 45.229167 | 143 | 0.750806 | [
"MIT"
] | JaCraig/Craig-s-Utility-Library | UnitTests/ORM/Manager/ORMManager.cs | 2,173 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
namespace okteto_dotnet_poc
{
public class Program
{
public static async Task<int> Main(string[] args)
{
var logger =
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
IHost host = null;
try
{
host = CreateHostBuilder(args).Build();
await MigrateDatabase(host);
}
catch(Exception ex)
{
logger.Fatal(ex, "Unable to create the host");
Log.CloseAndFlush();
throw;
}
try
{
await host.RunAsync();
return 0;
}
catch(Exception ex)
{
logger.Fatal(ex, "Host shutdown unexpectedly");
throw;
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) => Host
.CreateDefaultBuilder(args)
.UseSerilog(ConfigureSerilog)
.ConfigureWebHostDefaults(webBuilder => webBuilder
.ConfigureAppConfiguration(ConfigureAppConfiguration)
.UseStartup<Startup>()
);
private static async Task MigrateDatabase(IHost host)
{
using var context = host.Services.GetService<Database>();
await context?.Database?.MigrateAsync();
}
private static void ConfigureAppConfiguration(WebHostBuilderContext context, IConfigurationBuilder config)
{
config.AddJsonFile($"configmap/appsettings.json", optional: true, reloadOnChange: true);
config.AddJsonFile($"secret/appsettings.json", optional: true, reloadOnChange: true);
}
private static void ConfigureSerilog(HostBuilderContext context, LoggerConfiguration config)
{
config
.MinimumLevel.Debug()
.MinimumLevel.Override("System", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.ReadFrom.Configuration(context.Configuration)
.Enrich.FromLogContext()
;
}
}
}
| 32.477273 | 115 | 0.571379 | [
"MIT"
] | chrishaland/okteto-dotnet-poc | src/Program.cs | 2,858 | 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.Reactive.Disposables;
using System.Reactive.PlatformServices;
using System.Threading;
namespace System.Reactive.Concurrency
{
public partial class LocalScheduler
{
/// <summary>
/// Gate to protect local scheduler queues.
/// </summary>
private static readonly object Gate = new object();
/// <summary>
/// Gate to protect queues and to synchronize scheduling decisions and system clock
/// change management.
/// </summary>
private static readonly object StaticGate = new object();
/// <summary>
/// Long term work queue. Contains work that's due beyond SHORTTERM, computed at the
/// time of enqueueing.
/// </summary>
private static readonly PriorityQueue<WorkItem/*!*/> LongTerm = new PriorityQueue<WorkItem/*!*/>();
/// <summary>
/// Disposable resource for the long term timer that will reevaluate and dispatch the
/// first item in the long term queue. A serial disposable is used to make "dispose
/// current and assign new" logic easier. The disposable itself is never disposed.
/// </summary>
private static readonly SerialDisposable NextLongTermTimer = new SerialDisposable();
/// <summary>
/// Item at the head of the long term queue for which the current long term timer is
/// running. Used to detect changes in the queue and decide whether we should replace
/// or can continue using the current timer (because no earlier long term work was
/// added to the queue).
/// </summary>
private static WorkItem _nextLongTermWorkItem;
/// <summary>
/// Short term work queue. Contains work that's due soon, computed at the time of
/// enqueueing or upon reevaluation of the long term queue causing migration of work
/// items. This queue is kept in order to be able to relocate short term items back
/// to the long term queue in case a system clock change occurs.
/// </summary>
private readonly PriorityQueue<WorkItem/*!*/> _shortTerm = new PriorityQueue<WorkItem/*!*/>();
/// <summary>
/// Set of disposable handles to all of the current short term work Schedule calls,
/// allowing those to be cancelled upon a system clock change.
/// </summary>
private readonly HashSet<IDisposable> _shortTermWork = new HashSet<IDisposable>();
/// <summary>
/// Threshold where an item is considered to be short term work or gets moved from
/// long term to short term.
/// </summary>
private static readonly TimeSpan ShortTerm = TimeSpan.FromSeconds(10);
/// <summary>
/// Maximum error ratio for timer drift. We've seen machines with 10s drift on a
/// daily basis, which is in the order 10E-4, so we allow for extra margin here.
/// This value is used to calculate early arrival for the long term queue timer
/// that will reevaluate work for the short term queue.
///
/// Example: -------------------------------...---------------------*-----$
/// ^ ^
/// | |
/// early due
/// 0.999 1.0
///
/// We also make the gap between early and due at least LONGTOSHORT so we have
/// enough time to transition work to short term and as a courtesy to the
/// destination scheduler to manage its queues etc.
/// </summary>
private const int MaxErrorRatio = 1000;
/// <summary>
/// Minimum threshold for the long term timer to fire before the queue is reevaluated
/// for short term work. This value is chosen to be less than SHORTTERM in order to
/// ensure the timer fires and has work to transition to the short term queue.
/// </summary>
private static readonly TimeSpan LongToShort = TimeSpan.FromSeconds(5);
/// <summary>
/// Threshold used to determine when a short term timer has fired too early compared
/// to the absolute due time. This provides a last chance protection against early
/// completion of scheduled work, which can happen in case of time adjustment in the
/// operating system (cf. GetSystemTimeAdjustment).
/// </summary>
private static readonly TimeSpan RetryShort = TimeSpan.FromMilliseconds(50);
/// <summary>
/// Longest interval supported by timers in the BCL.
/// </summary>
private static readonly TimeSpan MaxSupportedTimer = TimeSpan.FromMilliseconds((1L << 32) - 2);
/// <summary>
/// Creates a new local scheduler.
/// </summary>
[Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "We can't really lift this into a field initializer, and would end up checking for an initialization flag in every static method anyway (which is roughly what the JIT does in a thread-safe manner).")]
protected LocalScheduler()
{
//
// Hook up for system clock change notifications. This doesn't do anything until the
// AddRef method is called (which can throw).
//
SystemClock.Register(this);
}
/// <summary>
/// Enqueues absolute time scheduled work in the timer queue or the short term work list.
/// </summary>
/// <param name="state">State to pass to the action.</param>
/// <param name="dueTime">Absolute time to run the work on. The timer queue is responsible to execute the work close to the specified time, also accounting for system clock changes.</param>
/// <param name="action">Action to run, potentially recursing into the scheduler.</param>
/// <returns>Disposable object to prevent the work from running.</returns>
private IDisposable Enqueue<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
{
//
// Work that's due in the past is sent to the underlying scheduler through the Schedule
// overload for execution at TimeSpan.Zero. We don't go to the overload for immediate
// scheduling in order to:
//
// - Preserve the time-based nature of the call as surfaced to the underlying scheduler,
// as it may use different queuing strategies.
//
// - Optimize for the default behavior of LocalScheduler where a virtual call to Schedule
// for immediate execution calls into the abstract Schedule method with TimeSpan.Zero.
//
var due = Scheduler.Normalize(dueTime - Now);
if (due == TimeSpan.Zero)
{
return Schedule(state, TimeSpan.Zero, action);
}
//
// We're going down the path of queueing up work or scheduling it, so we need to make
// sure we can get system clock change notifications. If not, the call below is expected
// to throw NotSupportedException. WorkItem.Invoke decreases the ref count again to allow
// the system clock monitor to stop if there's no work left. Notice work items always
// reach an execution stage since we don't dequeue items but merely mark them as cancelled
// through WorkItem.Dispose. Double execution is also prevented, so the ref count should
// correctly balance out.
//
SystemClock.AddRef();
var workItem = new WorkItem<TState>(this, state, dueTime, action);
if (due <= ShortTerm)
{
ScheduleShortTermWork(workItem);
}
else
{
ScheduleLongTermWork(workItem);
}
return workItem;
}
/// <summary>
/// Schedule work that's due in the short term. This leads to relative scheduling calls to the
/// underlying scheduler for short TimeSpan values. If the system clock changes in the meantime,
/// the short term work is attempted to be cancelled and reevaluated.
/// </summary>
/// <param name="item">Work item to schedule in the short term. The caller is responsible to determine the work is indeed short term.</param>
private void ScheduleShortTermWork(WorkItem/*!*/ item)
{
lock (Gate)
{
_shortTerm.Enqueue(item);
//
// We don't bother trying to dequeue the item or stop the timer upon cancellation,
// but always let the timer fire to do the queue maintenance. When the item is
// cancelled, it won't run (see WorkItem.Invoke). In the event of a system clock
// change, all outstanding work in _shortTermWork is cancelled and the short
// term queue is reevaluated, potentially prompting rescheduling of short term
// work. Notice work is protected against double execution by the implementation
// of WorkItem.Invoke.
//
var d = new SingleAssignmentDisposable();
_shortTermWork.Add(d);
//
// We normalize the time delta again (possibly redundant), because we can't assume
// the underlying scheduler implementations is valid and deals with negative values
// (though it should).
//
var dueTime = Scheduler.Normalize(item.DueTime - item.Scheduler.Now);
d.Disposable = item.Scheduler.Schedule((@this: this, d), dueTime, (self, tuple) => tuple.@this.ExecuteNextShortTermWorkItem(self, tuple.d));
}
}
/// <summary>
/// Callback to process the next short term work item.
/// </summary>
/// <param name="scheduler">Recursive scheduler supplied by the underlying scheduler.</param>
/// <param name="cancel">Disposable used to identify the work the timer was triggered for (see code for usage).</param>
/// <returns>Empty disposable. Recursive work cancellation is wired through the original WorkItem.</returns>
private IDisposable ExecuteNextShortTermWorkItem(IScheduler scheduler, IDisposable cancel)
{
var next = default(WorkItem);
lock (Gate)
{
//
// Notice that even though we try to cancel all work in the short term queue upon a
// system clock change, cancellation may not be honored immediately and there's a
// small chance this code runs for work that has been cancelled. Because the handler
// doesn't execute the work that triggered the time-based Schedule call, but always
// runs the work from the short term queue in order, we need to make sure we're not
// stealing items in the queue. We can do so by remembering the object identity of
// the disposable and check whether it still exists in the short term work list. If
// not, a system clock change handler has gotten rid of it as part of reevaluating
// the short term queue, but we still ended up here because the inherent race in the
// call to Dispose versus the underlying timer. It's also possible the underlying
// scheduler does a bad job at cancellation, so this measure helps for that too.
//
if (_shortTermWork.Remove(cancel) && _shortTerm.Count > 0)
{
next = _shortTerm.Dequeue();
}
}
if (next != null)
{
//
// If things don't make sense and we're way too early to run the work, this is our
// final chance to prevent us from running before the due time. This situation can
// arise when Windows applies system clock adjustment (see SetSystemTimeAdjustment)
// and as a result the clock is ticking slower. If the clock is ticking faster due
// to such an adjustment, too bad :-). We try to minimize the window for the final
// relative time based scheduling such that 10%+ adjustments to the clock rate
// have only "little" impact (range of 100s of ms). On an absolute time scale, we
// don't provide stronger guarantees.
//
if (next.DueTime - next.Scheduler.Now >= RetryShort)
{
ScheduleShortTermWork(next);
}
else
{
//
// Invocation happens on the recursive scheduler supplied to the function. We
// are already running on the target scheduler, so we should stay on board.
// Not doing so would have unexpected behavior for e.g. NewThreadScheduler,
// causing a whole new thread to be allocated because of a top-level call to
// the Schedule method rather than a recursive one.
//
// Notice if work got cancelled, the call to Invoke will not propagate to user
// code because of the IsDisposed check inside.
//
next.Invoke(scheduler);
}
}
//
// No need to return anything better here. We already handed out the original WorkItem
// object upon the call to Enqueue (called itself by Schedule). The disposable inside
// the work item allows a cancellation request to chase the underlying computation.
//
return Disposable.Empty;
}
/// <summary>
/// Schedule work that's due on the long term. This leads to the work being queued up for
/// eventual transitioning to the short term work list.
/// </summary>
/// <param name="item">Work item to schedule on the long term. The caller is responsible to determine the work is indeed long term.</param>
private static void ScheduleLongTermWork(WorkItem/*!*/ item)
{
lock (StaticGate)
{
LongTerm.Enqueue(item);
//
// In case we're the first long-term item in the queue now, the timer will have
// to be updated.
//
UpdateLongTermProcessingTimer();
}
}
/// <summary>
/// Updates the long term timer which is responsible to transition work from the head of the
/// long term queue to the short term work list.
/// </summary>
/// <remarks>Should be called under the scheduler lock.</remarks>
private static void UpdateLongTermProcessingTimer()
{
/*
* CALLERS - Ensure this is called under the lock!
*
lock (s_gate) */
{
if (LongTerm.Count == 0)
{
return;
}
//
// To avoid setting the timer all over again for the first work item if it hasn't changed,
// we keep track of the next long term work item that will be processed by the timer.
//
var next = LongTerm.Peek();
if (next == _nextLongTermWorkItem)
{
return;
}
//
// We need to arrive early in order to accommodate for potential drift. The relative amount
// of drift correction is kept in MAXERRORRATIO. At the very least, we want to be LONGTOSHORT
// early to make the final jump from long term to short term, giving the target scheduler
// enough time to process the item through its queue. LONGTOSHORT is chosen such that the
// error due to drift is negligible.
//
var due = Scheduler.Normalize(next.DueTime - next.Scheduler.Now);
var remainder = TimeSpan.FromTicks(Math.Max(due.Ticks / MaxErrorRatio, LongToShort.Ticks));
var dueEarly = due - remainder;
//
// Limit the interval to maximum supported by underlying Timer.
//
var dueCapped = TimeSpan.FromTicks(Math.Min(dueEarly.Ticks, MaxSupportedTimer.Ticks));
_nextLongTermWorkItem = next;
NextLongTermTimer.Disposable = ConcurrencyAbstractionLayer.Current.StartTimer(_ => EvaluateLongTermQueue(), null, dueCapped);
}
}
/// <summary>
/// Evaluates the long term queue, transitioning short term work to the short term list,
/// and adjusting the new long term processing timer accordingly.
/// </summary>
private static void EvaluateLongTermQueue()
{
lock (StaticGate)
{
while (LongTerm.Count > 0)
{
var next = LongTerm.Peek();
var due = Scheduler.Normalize(next.DueTime - next.Scheduler.Now);
if (due >= ShortTerm)
{
break;
}
var item = LongTerm.Dequeue();
item.Scheduler.ScheduleShortTermWork(item);
}
_nextLongTermWorkItem = null;
UpdateLongTermProcessingTimer();
}
}
/// <summary>
/// Callback invoked when a system clock change is observed in order to adjust and reevaluate
/// the internal scheduling queues.
/// </summary>
/// <param name="args">Currently not used.</param>
/// <param name="sender">Currently not used.</param>
internal virtual void SystemClockChanged(object sender, SystemClockChangedEventArgs args)
{
lock (StaticGate)
{
lock (Gate)
{
//
// Best-effort cancellation of short term work. A check for presence in the hash set
// is used to notice race conditions between cancellation and the timer firing (also
// guarded by the same gate object). See checks in ExecuteNextShortTermWorkItem.
//
foreach (var d in _shortTermWork)
{
d.Dispose();
}
_shortTermWork.Clear();
//
// Transition short term work to the long term queue for reevaluation by calling the
// EvaluateLongTermQueue method. We don't know which direction the clock was changed
// in, so we don't optimize for special cases, but always transition the whole queue.
// Notice the short term queue is bounded to SHORTTERM length.
//
while (_shortTerm.Count > 0)
{
var next = _shortTerm.Dequeue();
LongTerm.Enqueue(next);
}
//
// Reevaluate the queue and don't forget to null out the current timer to force the
// method to create a new timer for the new first long term item.
//
_nextLongTermWorkItem = null;
EvaluateLongTermQueue();
}
}
}
/// <summary>
/// Represents a work item in the absolute time scheduler.
/// </summary>
/// <remarks>
/// This type is very similar to ScheduledItem, but we need a different Invoke signature to allow customization
/// of the target scheduler (e.g. when called in a recursive scheduling context, see ExecuteNextShortTermWorkItem).
/// </remarks>
private abstract class WorkItem : IComparable<WorkItem>, IDisposable
{
public readonly LocalScheduler Scheduler;
public readonly DateTimeOffset DueTime;
private IDisposable _disposable;
private int _hasRun;
protected WorkItem(LocalScheduler scheduler, DateTimeOffset dueTime)
{
Scheduler = scheduler;
DueTime = dueTime;
_hasRun = 0;
}
public void Invoke(IScheduler scheduler)
{
//
// Protect against possible maltreatment of the scheduler queues or races in
// execution of a work item that got relocated across system clock changes.
// Under no circumstance whatsoever we should run work twice. The monitor's
// ref count should also be subject to this policy.
//
if (Interlocked.Exchange(ref _hasRun, 1) == 0)
{
try
{
if (!Disposable.GetIsDisposed(ref _disposable))
{
Disposable.SetSingle(ref _disposable, InvokeCore(scheduler));
}
}
finally
{
SystemClock.Release();
}
}
}
protected abstract IDisposable InvokeCore(IScheduler scheduler);
public int CompareTo(WorkItem/*!*/ other) => Comparer<DateTimeOffset>.Default.Compare(DueTime, other.DueTime);
public void Dispose() => Disposable.TryDispose(ref _disposable);
}
/// <summary>
/// Represents a work item that closes over scheduler invocation state. Subtyping is
/// used to have a common type for the scheduler queues.
/// </summary>
private sealed class WorkItem<TState> : WorkItem
{
private readonly TState _state;
private readonly Func<IScheduler, TState, IDisposable> _action;
public WorkItem(LocalScheduler scheduler, TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
: base(scheduler, dueTime)
{
_state = state;
_action = action;
}
protected override IDisposable InvokeCore(IScheduler scheduler) => _action(scheduler, _state);
}
}
}
| 48.112936 | 343 | 0.567112 | [
"MIT"
] | ltrzesniewski/reactive | Rx.NET/Source/src/System.Reactive/Concurrency/LocalScheduler.TimerQueue.cs | 23,433 | 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 elasticfilesystem-2015-02-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.ElasticFileSystem.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ElasticFileSystem.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for LifecyclePolicy Object
/// </summary>
public class LifecyclePolicyUnmarshaller : IUnmarshaller<LifecyclePolicy, XmlUnmarshallerContext>, IUnmarshaller<LifecyclePolicy, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
LifecyclePolicy IUnmarshaller<LifecyclePolicy, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public LifecyclePolicy Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
LifecyclePolicy unmarshalledObject = new LifecyclePolicy();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("TransitionToIA", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.TransitionToIA = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static LifecyclePolicyUnmarshaller _instance = new LifecyclePolicyUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static LifecyclePolicyUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 34.054348 | 158 | 0.646026 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/ElasticFileSystem/Generated/Model/Internal/MarshallTransformations/LifecyclePolicyUnmarshaller.cs | 3,133 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RandomizeWords
{
class RandomizeWords
{
static void Main()
{
var words = Console.ReadLine().Split(' ').ToArray();
var random = new Random();
for (int i = 0; i < words.Length; i++)
{
var currentWord = words[i];
var randomPos = random.Next(0, words.Length);
var temp = words[randomPos];
words[randomPos] = currentWord;
words[i] = temp;
}
foreach (var word in words)
{
Console.WriteLine(word);
}
}
}
}
| 19.852941 | 58 | 0.557037 | [
"MIT"
] | svet110/ProgrammingFundamentalsExtended | ObjectsAndSimpleClassesLab/RandomizeWords/RandomizeWords.cs | 677 | C# |
using System;
using UnityEngine;
public static class JsonHelper
{
public static T[] FromJson<T>(string json)
{
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.Items;
}
public static string ToJson<T>(T[] array)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper);
}
public static string ToJson<T>(T[] array, bool prettyPrint)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper, prettyPrint);
}
public static string FixJson(string json)
{
return "{\"Items\":" + json + "}";
}
[Serializable]
private class Wrapper<T>
{
public T[] Items;
}
} | 22.055556 | 68 | 0.602015 | [
"MIT"
] | J3573R/simple-scoreboard-example | Assets/JsonHelper.cs | 796 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading; // import the threading namespace to use the dispatcher timer first
namespace Clicky_Game_WPF_MOO_ICT
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
DispatcherTimer gameTimer = new DispatcherTimer(); // create a new instance of the dispatcher time called gameTimer
List<Ellipse> removeThis = new List<Ellipse>(); // make a list of ellipse called remove this it will be used to remove the circles we click on from the game
// below are all the necessary integers declared for this game
int spawnRate = 60; // this is the default spawn rate of the circles
int currentRate; // current rate will help add an interval between spawning of the circles
int lastScore = 0; // this will hold the last played score for this game
int health = 350; // total health of the player in the begining of the game
int posX; // x position of the circles
int posY; // y position of the circles
int score = 0; // current score for the game
double growthRate = 0.6; // the default growth rate for each circle in the game
Random rand = new Random(); // a random number generator
// below are the two media player classes one for the clicked sound and one for the pop sound
MediaPlayer playClickSound = new MediaPlayer();
MediaPlayer playerPopSound = new MediaPlayer();
// below are the two URI location finder for both mp3 files we imported for this game
Uri ClickedSound;
Uri PoppedSound;
// colour for the circles
Brush brush;
public MainWindow()
{
InitializeComponent();
// inside the main constructor we will write the instructors for the begining of the game
gameTimer.Tick += GameLoop; // set the game timer event called game loop
gameTimer.Interval = TimeSpan.FromMilliseconds(20); // this time will tick every 20 milliseconds
gameTimer.Start(); // start the timer
currentRate = spawnRate; // set the current rate to the spawn rate number
// locate both of the mp3 files inside sound folder and add them to the correct URI below
ClickedSound = new Uri("pack://siteoforigin:,,,/sound/clickedpop.mp3");
PoppedSound = new Uri("pack://siteoforigin:,,,/sound/pop.mp3");
}
private void GameLoop(object sender, EventArgs e)
{
// this is the game loop event, all of the instructions inside of this event will run each time the timer ticks
// first we update the score and show the last score on the labels
txtScore.Content = "Score: " + score;
txtLastScore.Content = "Last Score: " + lastScore;
// reduce 2 from the current rate as the time runs
currentRate -= 2;
// if the current rate is below 1
if (currentRate < 1)
{
// reset current rate back to spawn rate
currentRate = spawnRate;
// generate a random number for the X and Y value for the circles
posX = rand.Next(15, 700);
posY = rand.Next(50, 350);
// generate a random colour for the circles and save it inside the brush
brush = new SolidColorBrush(Color.FromRgb((byte)rand.Next(1, 255), (byte)rand.Next(1, 255), (byte)rand.Next(1, 255)));
// create a new ellipse called circle
// this circle will have a tag, default height and width, border colour and fill
Ellipse circle = new Ellipse
{
Tag = "circle",
Height = 10,
Width = 10,
Stroke = Brushes.Black,
StrokeThickness = 1,
Fill = brush
};
// place the newly created circle to the canvas with the X and Y position generated earlier
Canvas.SetLeft(circle, posX);
Canvas.SetTop(circle, posY);
// finally add the circle to the canvas
MyCanvas.Children.Add(circle);
}
// the for each loop below will find each ellipse inside of the canvas and grow it
foreach (var x in MyCanvas.Children.OfType<Ellipse>())
{
// we search the canvas and find the ellipse that exists inside of it
x.Height += growthRate; // grow the height of the circle
x.Width += growthRate; // grow the width of the circle
x.RenderTransformOrigin = new Point(0.5, 0.5); // grow from the centre of the circle by resetting the transform origin
// if the width of the circle goes above 70 we want to pop the circle
if (x.Width > 70)
{
// if the width if above 70 then add this circle to the remove this list
removeThis.Add(x);
health -= 15; // reduce health by 15
playerPopSound.Open(PoppedSound); // load the popped sound uri inside of the player pop sound media player
playerPopSound.Play(); // now play the pop sound
}
} // end of for each loop
// if health is above 1
if (health > 1)
{
// link the health bar rectangle to the health integer
healthBar.Width = health;
}
else
{
// if health is below 1 then run the game over function
GameOverFunction();
}
// to remov ethe ellipse from the game we need another for each loop
foreach (Ellipse i in removeThis)
{
// this for each loop will search for each ellipse that exist inside of the remove this list
MyCanvas.Children.Remove(i); // when it finds one it will remove it from the canvas
}
// if the score if above 5
if (score > 5)
{
// speed up the spawn rate
spawnRate = 25;
}
// if the score is above 20
if (score > 20)
{
// speed up the growth and and spawn rate
spawnRate = 15;
growthRate = 1.5;
}
}
private void ClickOnCanvas(object sender, MouseButtonEventArgs e)
{
// this click event is linked inside of the canvas, we need to check if we have clicked on the ellipse
// if the original source clicked is a ellipse
if (e.OriginalSource is Ellipse)
{
// create a local ellipse and link it to the original source
Ellipse circle = (Ellipse)e.OriginalSource;
// now remove that ellipse we clicked on from the canvas
MyCanvas.Children.Remove(circle);
// add 1 to the score
score++;
// load the clicked sound uri to the play click sound media player and play the sound file
playClickSound.Open(ClickedSound);
playClickSound.Play();
}
}
private void GameOverFunction()
{
// this is the game over function
gameTimer.Stop(); // first stop the game timer
// show a message box to the end screen and wait for the player to click ok
MessageBox.Show("Game Over" + Environment.NewLine + "You Scored: " + score + Environment.NewLine + "Click Ok to play again!", "Moo Says: ");
// after the player clicked ok now we need to do a for each loop
foreach (var y in MyCanvas.Children.OfType<Ellipse>())
{
// find all of the existing ellipse that are on the screen and add them to the remove this list
removeThis.Add(y);
}
// here we need another for each loop to remove everything from inside of the remove this list
foreach (Ellipse i in removeThis)
{
MyCanvas.Children.Remove(i);
}
// reset all of the game values to default including clearling all of the ellipses from the remove this list
growthRate = .6;
spawnRate = 60;
lastScore = score;
score = 0;
currentRate = 5;
health = 350;
removeThis.Clear();
gameTimer.Start();
}
}
}
| 39.271967 | 165 | 0.560516 | [
"Apache-2.0"
] | mooict/WPF-Clicking-Game-with-Sound | Clicky Game WPF MOO ICT/MainWindow.xaml.cs | 9,388 | C# |
using System;
namespace PrevisaoTempo.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
| 17.666667 | 70 | 0.669811 | [
"MIT"
] | karolinagb/PrevisaoTempo | PrevisaoTempo/PrevisaoTempo/Models/ErrorViewModel.cs | 212 | C# |
namespace AutomatedLab
{
public class Disk
{
public bool SkipInitialization { get; set; }
public string Path { get; set; }
public string Name { get; set; }
public int DiskSize { get; set; }
public long AllocationUnitSize { get; set; }
public bool UseLargeFRS { get; set; }
public string Label { get; set; }
public char DriveLetter { get; set; }
public PartitionStyle PartitionStyle {get; set;}
// Specifically used on Azure to properly assign drive letters and partition/format
public int Lun { get; set; }
public string FileName
{
get
{
return System.IO.Path.GetFileName(Path);
}
}
public override string ToString()
{
return Name;
}
}
}
| 21.75 | 91 | 0.53908 | [
"MIT"
] | ebell451/AutomatedLab | LabXml/Disks/Disk.cs | 872 | C# |
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using EPiServer.Research.Translation4.Core;
using EPiServer.Research.Translation4.Common;
using EPiServer.Core;
using System.Collections.Generic;
using EPiServer.FileSystem;
using System.IO;
using EPiServer.Web.Hosting;
namespace EPiServer.Research.Translation4.UI
{
public partial class ImportPage : EPiServer.SimplePage
{
protected void Page_Load(object sender, EventArgs e)
{
ConnectorDefinition cd = Manager.Current.GetConntectorDefinitionByName(CurrentProject.ConnectorName);
if (cd.ControlToImportStep != string.Empty)
{
customerStep.UserControlString = cd.ControlToImportStep;
}
else
{
Wizard1.WizardSteps.RemoveAt(0);
}
}
TranslationProject CurrentProject
{
get
{
if (_currentProject == null)
{
int projectid = int.Parse(Request.QueryString["projectid"]);
_currentProject = Manager.Current.GetTranslationProject(projectid);
_currentProject.Connector = Manager.Current.GetConntectorByName(_currentProject.ConnectorName);
}
return _currentProject;
}
}
TranslationProject _currentProject = null;
protected void WizardFinished(object sender, EventArgs e)
{
if (ViewState["pageselected"] != null)
createAt.PageLink = (PageReference)ViewState["pageselected"];
if (ViewState["importas"]!=null)
importas.SelectedIndex = (int)(ViewState["importas"]);
int projectid = int.Parse(Request.QueryString["projectid"]);
int importtype = importas.Value == "0" ? 0 : 1;
EPiServer.DataAccess.SaveAction saveAction = publishtype.Value=="0"? EPiServer.DataAccess.SaveAction.Publish:EPiServer.DataAccess.SaveAction.CheckIn;
TranslationProject tp = CurrentProject;
if (importtype == 0)
{
// new version
List<TranslationPage> pages = tp.Pages;
foreach (TranslationPage page in pages)
{
foreach (string lang in tp.TargetLanguages)
{
if (page.GetStatus(lang) == TranslationStatus.Imported)
continue;
TranslationPage tpdata = tp.Connector.GetPage(page.GetData(lang));
PageData epPage = DataFactory.Instance.GetPage(PageReference.Parse(page.OriginalID));
string locale = EPLangUtil.FindLangIDFromLocale(lang);
if (locale == "")
locale = Manager.Current.ToInvalidLocale(lang);
ILanguageSelector langSel = new LanguageSelector(locale);
PageData newPage = DataFactory.Instance.GetPage( new PageReference(epPage.PageLink.ID), langSel);
if (newPage == null)
newPage = DataFactory.Instance.CreateLanguageBranch(epPage.PageLink, langSel);
else
{
newPage = newPage.CreateWritableClone();
}
foreach (string key in tpdata.Properties.Keys)
{
if ( ( newPage.Property[key]!=null) &&
(!newPage.Property[key].IsDynamicProperty)
&& (newPage.Property[key].IsLanguageSpecific)
&& ((!newPage.Property[key].IsMetaData) || (key.ToLower() == "pagename"))
)
{
if ((key.ToLower() == "pagename") && ( string.IsNullOrEmpty( tpdata.Properties[key] as string) ))
continue;
newPage[key] = tpdata.Properties[key];
}
}
PageReference newPr = DataFactory.Instance.Save(newPage, saveAction);
page.SetStatus(lang, TranslationStatus.Imported);
}
}
foreach (TranslationFile file in tp.Files)
{
UnifiedDirectory upd = DataFactory.Instance.GetPage(PageReference.Parse(file.PageLink)).GetPageDirectory(true);
string orginalfilename = Path.GetFileName(file.FilePath);
string newfilename = "";
foreach (string lang in tp.TargetLanguages)
{
newfilename = Path.GetFileNameWithoutExtension(orginalfilename) + suffixtext.Text + lang.Replace("-","_") + Path.GetExtension(orginalfilename);
UnifiedFile uf = upd.CreateFile(newfilename);
BinaryWriter write = new BinaryWriter( uf.Open(FileMode.OpenOrCreate));
write.Write(file.GetData(lang));
write.Close();
file.SetStatus(lang, TranslationStatus.Imported);
}
}
}
else
{
// for each language we do:
// 1. create a new node
// 2. add children according to indent pages list in db.
foreach (string lang in tp.TargetLanguages)
{
List<TranslationPage> pages = tp.Pages;
int indent = 1;
PageReference startNode = createAt.PageLink;
string parentNode = "0";
createNewPage(lang, startNode, indent,parentNode, saveAction,ref pages, ref tp);
}
}
tp.Status = TranslationStatus.Imported;
tp.Save();
closeWindowPanel.Visible = true;
}
private List<string> GetRequiredAndLanguageNeutralPropertyKeys(PageData page)
{
List<string> properties = new List<string>();
foreach (PropertyData prop in page.Property)
{
if (prop.IsDynamicProperty)
{
continue;
}
if (prop.IsNull)
{
continue;
}
if (!page.IsMasterLanguageBranch )
{
continue;
}
if ((prop.IsMetaData) && ( prop.Name.ToLower() !="pagename" ))
{
continue;
}
if ((prop.IsLanguageSpecific) &&(!prop.IsRequired))
{
continue;
}
if (prop.Name == "PageLink" || prop.Name == "PageParentLink")
{
continue;
}
properties.Add(prop.Name);
}
return properties;
}
private void createNewPage(string lang, PageReference startNode, int indent, string parentNode, EPiServer.DataAccess.SaveAction saveAction, ref List<TranslationPage> pages, ref TranslationProject tp)
{
foreach (TranslationPage page in pages)
{
if ( (page.Indent == indent) && ( indent==1 || page.ParentNode == parentNode ) )
{
TranslationPage tpdata = tp.Connector.GetPage(page.GetData(lang));
PageData epPage = DataFactory.Instance.GetPage(PageReference.Parse(page.OriginalID));
string locale = EPLangUtil.FindLangIDFromLocale(lang);
if (locale == "")
locale = EPLangUtil.FindLangIDFromLocale(lang.Substring(0, 2));
if (locale == "")
locale = EPLangUtil.FindLangIDFromLocale(lang.Substring(3, 2));
ILanguageSelector langSel = new LanguageSelector(locale);
PageData newPage = DataFactory.Instance.GetDefaultPageData(startNode, epPage.PageTypeID, langSel);
// we need do it twice
// one for all properties defined in master language
// then override all properties defined in original language
// get from master language
PageData masterPage = DataFactory.Instance.GetPage(epPage.PageLink, new LanguageSelector(epPage.MasterLanguageBranch));
List<string> props = GetRequiredAndLanguageNeutralPropertyKeys(masterPage);
foreach (string key in props)
{
newPage[key] = masterPage.Property[key].Value;
}
if (masterPage.PageLink != epPage.PageLink)
{
// override from original language
props = GetRequiredAndLanguageNeutralPropertyKeys(epPage);
foreach (string key in props)
{
newPage[key] = epPage.Property[key].Value;
}
}
// override with translated language
foreach (string key in tpdata.Properties.Keys)
{
// new page we take all data in.
if ((newPage.Property[key] != null) && (!newPage.Property[key].IsDynamicProperty)
&& (newPage.Property[key].IsLanguageSpecific)
&& ((!newPage.Property[key].IsMetaData) || (key.ToLower() == "pagename"))
)
{
newPage[key] = tpdata.Properties[key];
}
}
PageReference newNode = DataFactory.Instance.Save(newPage, saveAction);
foreach (TranslationFile file in tp.Files)
{
if (file.PageLink == page.OriginalID)
{
UnifiedDirectory upd = DataFactory.Instance.GetPage(newNode).GetPageDirectory(true);
string orginalfilename = Path.GetFileName(file.FilePath);
string newfilename = "";
newfilename = orginalfilename;
UnifiedFile uf = upd.CreateFile(newfilename);
BinaryWriter write = new BinaryWriter(uf.Open(FileMode.OpenOrCreate));
write.Write(file.GetData(lang));
write.Close();
}
}
createNewPage(lang, newNode, indent + 1, page.OriginalID.Split(new char[]{'_'})[0],saveAction, ref pages,ref tp);
}
}
}
protected void StepChanged(object sender, EventArgs e)
{
if (ViewState["pageselected"] != null)
createAt.PageLink = (PageReference) ViewState["pageselected"];
if (ViewState["importas"] != null)
importas.SelectedIndex = (int)(ViewState["importas"]);
if (Wizard1.ActiveStep == WizardStep1)
{
if (customerStep != null)
{
ICustomerStep iccs = customerStep.InnerControl as ICustomerStep;
iccs.Save(CurrentProject);
}
}
}
protected void NextStep(object sender, EventArgs e)
{
ViewState["importas"] = importas.SelectedIndex;
if (createAt.PageLink != null)
{
ViewState["pageselected"] = createAt.PageLink;
}
}
protected void PrevStep(object sender, EventArgs e)
{
ViewState["importas"] = importas.SelectedIndex;
if (createAt.PageLink != null)
{
ViewState["pageselected"] = createAt.PageLink;
}
}
}
}
| 42.805369 | 207 | 0.494512 | [
"MIT"
] | Episerver-trainning/episever6_translatex | EPiServer.Research.TranslateX/EPiServer5.2/UI/ImportPage.aspx.cs | 12,758 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace XFTranslator.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
global::Xamarin.Forms.FormsMaterial.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
| 36.1875 | 98 | 0.676166 | [
"MIT"
] | aimore/XamUI | XFTranslator/XFTranslator.iOS/AppDelegate.cs | 1,160 | C# |
/*************************************************************************************
Toolkit for WPF
Copyright (C) 2007-2017 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
For more features, controls, and fast professional support,
pick up the Plus Edition at https://xceed.com/xceed-toolkit-plus-for-wpf/
Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
***********************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Globalization;
using System.Reflection;
using Xceed.Wpf.Toolkit.LiveExplorer;
using Xceed.Wpf.Toolkit.LiveExplorer.Core;
using System.Diagnostics;
namespace Xceed.Wpf.Toolkit.LiveExplorer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private const string toolkitAssembly = "Xceed.Wpf.Toolkit.LiveExplorer";
public MainWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler( this.MainWindow_Loaded );
VersionTextBlock.Text = "Version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
#region Properties
#region View
public static readonly DependencyProperty ViewProperty = DependencyProperty.Register( "View", typeof( DemoView ), typeof( MainWindow ), new UIPropertyMetadata( null, OnViewChanged ) );
public DemoView View
{
get
{
return ( DemoView )GetValue( ViewProperty );
}
set
{
SetValue( ViewProperty, value );
}
}
private static void OnViewChanged( DependencyObject o, DependencyPropertyChangedEventArgs e )
{
MainWindow window = o as MainWindow;
if( window != null )
window.OnViewChanged( ( DemoView )e.OldValue, ( DemoView )e.NewValue );
}
protected virtual void OnViewChanged( DemoView oldValue, DemoView newValue )
{
this.InitView();
}
#endregion //View
#endregion //Properties
#region Event Handler
void MainWindow_Loaded( object sender, RoutedEventArgs e )
{
this.InitView();
}
private void OnTreeViewSelectionChanged( object sender, RoutedPropertyChangedEventArgs<Object> e )
{
this.UpdateSelectedView( e.NewValue as LiveExplorerTreeViewItem );
}
private void UpdateSelectedView( LiveExplorerTreeViewItem treeViewItem )
{
if( treeViewItem != null )
{
treeViewItem.IsExpanded = true;
Type type = treeViewItem.SampleType;
if( type != null )
{
string name = type.FullName;
Assembly assembly = Assembly.Load( toolkitAssembly );
Type sampleType = assembly.GetType( name );
this.View = ( DemoView )Activator.CreateInstance( sampleType );
}
}
}
private void Hyperlink_RequestNavigate( object sender, System.Windows.Navigation.RequestNavigateEventArgs e )
{
Process.Start( new ProcessStartInfo( e.Uri.AbsoluteUri ) );
e.Handled = true;
}
private void Image_MouseLeftButtonDown( object sender, MouseButtonEventArgs e )
{
//When the user clicks the Xceed logo on the top left.
//
}
#endregion //EventHandler
#region Methods
private void InitView()
{
if( ( _flowDocumentDesc != null ) && ( this.View != null) )
{
_flowDocumentDesc.Blocks.Clear();
if( this.View.Description != null )
{
_flowDocumentDesc.Blocks.Add( this.View.Description );
}
}
if( _contentScrollViewer != null )
{
_contentScrollViewer.ScrollToHome();
}
}
#endregion
}
}
| 27.25 | 188 | 0.646306 | [
"MIT"
] | 0xflotus/Materia | wpftoolkit-master/wpftoolkit-master/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.Toolkit.LiveExplorer/MainWindow.xaml.cs | 4,144 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.IIS.Administration.WebServer.Handlers
{
using Core;
using System;
public class Defines
{
private const string ENDPOINT = "http-handlers";
private const string MAPPINGS_ENDPOINT = "entries";
public const string HandlersName = "Microsoft.WebServer.Handlers";
public static readonly string PATH = $"{WebServer.Defines.PATH}/{ENDPOINT}";
public static readonly ResDef Resource = new ResDef("handlers", new Guid("D06CE65A-DC11-4E9F-87CF-7D04923B7C22"), ENDPOINT);
public const string IDENTIFIER = "handler.id";
public const string EntriesName = "Microsoft.WebServer.Handlers.Entries";
public const string EntryName = "Microsoft.WebServer.Handlers.Entry";
public static readonly string MAPPINGS_PATH = $"{PATH}/{MAPPINGS_ENDPOINT}";
public static readonly ResDef MappingsResource = new ResDef("entries", new Guid("18243D38-42F6-421E-A318-841B0F7EDA62"), MAPPINGS_ENDPOINT);
public const string MAPPINGS_IDENTIFIER = "mapping.id";
}
}
| 45.333333 | 148 | 0.720588 | [
"MIT"
] | 202006233011/IIS.Administration | src/Microsoft.IIS.Administration.WebServer.Handlers/Defines.cs | 1,224 | C# |
// <copyright file="NoRetryStrategyShould.cs" company="Okta, Inc">
// Copyright (c) 2014 - present Okta, Inc. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NSubstitute;
using Xunit;
namespace Okta.Sdk.UnitTests
{
public class NoRetryStrategyShould
{
[Fact]
public async Task NotRetry429()
{
var dateHeader = DateTime.Now;
var resetTime = new DateTimeOffset(dateHeader).AddSeconds(1).ToUnixTimeSeconds();
var response = Substitute.For<HttpResponseMessage>();
response.StatusCode = (HttpStatusCode)429;
response.Headers.Add("X-Rate-Limit-Reset", resetTime.ToString());
response.Headers.Add("Date", dateHeader.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"));
response.Headers.Add("X-Okta-Request-Id", "foo");
var request = Substitute.For<HttpRequestMessage>();
request.RequestUri = new Uri("https://foo.dev");
var operation = Substitute.For<Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>>>();
operation(request, default(CancellationToken)).Returns(response);
operation(request, default(CancellationToken)).Result.StatusCode.Should().Be(429);
operation.ClearReceivedCalls();
var retryStrategy = new NoRetryStrategy();
var retryResponse = await retryStrategy.WaitAndRetryAsync(request, default(CancellationToken), operation);
operation.ReceivedCalls().Count().Should().Be(1);
retryResponse.StatusCode.Should().Be((HttpStatusCode)429);
}
}
}
| 38.54 | 118 | 0.679294 | [
"Apache-2.0"
] | KOSASIH/okta-sdk-dotnet | src/Okta.Sdk.UnitTests/NoRetryStrategyShould.cs | 1,929 | 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.CommandLine.Rendering.Views;
using System.CommandLine.Tests;
using System.CommandLine.Tests.Utility;
using System.Drawing;
using FluentAssertions;
using Xunit;
namespace System.CommandLine.Rendering.Tests.Views
{
public class StackLayoutViewTests
{
[Fact]
public void Vertical_stack_displays_content_stacked_on_top_of_each_other()
{
var stackLayout = new StackLayoutView();
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
stackLayout.Render(renderer, new Region(0, 0, 10, 2));
terminal.Events.Should().BeEquivalentSequenceTo(
new TestTerminal.CursorPositionChanged(new Point(0, 0)),
new TestTerminal.ContentWritten("The quick"),
new TestTerminal.CursorPositionChanged(new Point(0, 1)),
new TestTerminal.ContentWritten("brown fox"));
}
[Fact]
public void Vertical_stack_clips_content_when_region_is_not_tall_enough()
{
var stackLayout = new StackLayoutView();
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
stackLayout.Render(renderer, new Region(0, 0, 10, 1));
terminal.Events.Should().BeEquivalentSequenceTo(
new TestTerminal.CursorPositionChanged(new Point(0, 0)),
new TestTerminal.ContentWritten("The quick"));
}
[Fact]
public void Vertical_stack_wraps_content_when_region_is_not_wide_enough()
{
var stackLayout = new StackLayoutView();
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
stackLayout.Render(renderer, new Region(0, 0, 5, 4));
terminal.Events.Should().BeEquivalentSequenceTo(
new TestTerminal.CursorPositionChanged(new Point(0, 0)),
new TestTerminal.ContentWritten("The "),
new TestTerminal.CursorPositionChanged(new Point(0, 1)),
new TestTerminal.ContentWritten("quick"),
new TestTerminal.CursorPositionChanged(new Point(0, 2)),
new TestTerminal.ContentWritten("brown"),
new TestTerminal.CursorPositionChanged(new Point(0, 3)),
new TestTerminal.ContentWritten("fox ")
);
}
[Fact]
public void Horizontal_stack_displays_content_stacked_on_next_to_each_other()
{
var stackLayout = new StackLayoutView(Orientation.Horizontal);
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
stackLayout.Render(renderer, new Region(0, 0, 18, 1));
terminal.Events.Should().BeEquivalentSequenceTo(
new TestTerminal.CursorPositionChanged(new Point(0, 0)),
new TestTerminal.ContentWritten("The quick "),
new TestTerminal.CursorPositionChanged(new Point(9, 0)),
new TestTerminal.ContentWritten("brown fox"));
}
[Fact]
public void Horizontal_stack_clips_content_when_region_is_not_wide_enough()
{
var stackLayout = new StackLayoutView(Orientation.Horizontal);
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
stackLayout.Render(renderer, new Region(0, 0, 16, 1));
terminal.Events.Should().BeEquivalentSequenceTo(
new TestTerminal.CursorPositionChanged(new Point(0, 0)),
new TestTerminal.ContentWritten("The quick "),
new TestTerminal.CursorPositionChanged(new Point(9, 0)),
new TestTerminal.ContentWritten("brown "));
}
[Fact]
public void Horizontal_stack_wraps_content_when_region_is_not_wide_enough()
{
var stackLayout = new StackLayoutView(Orientation.Horizontal);
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
stackLayout.Render(renderer, new Region(0, 0, 14, 2));
terminal.Events.Should().BeEquivalentSequenceTo(
new TestTerminal.CursorPositionChanged(new Point(0, 0)),
new TestTerminal.ContentWritten("The quick "),
new TestTerminal.CursorPositionChanged(new Point(9, 0)),
new TestTerminal.ContentWritten("brown"),
new TestTerminal.CursorPositionChanged(new Point(9, 1)),
new TestTerminal.ContentWritten("fox ")
);
}
[Fact]
public void Measuring_a_vertical_stack_sums_content_height()
{
var stackLayout = new StackLayoutView(Orientation.Vertical);
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
var size = stackLayout.Measure(renderer, new Size(10, 10));
size.Should().BeEquivalentTo(new Size(9, 2));
}
[Fact]
public void Measuring_a_vertical_stack_with_word_wrap_it_sums_max_height_for_each_row()
{
var stackLayout = new StackLayoutView(Orientation.Vertical);
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
var size = stackLayout.Measure(renderer, new Size(7, 10));
size.Should().BeEquivalentTo(new Size("brown ".Length, 4));
}
[Fact]
public void Measuring_a_vertical_stack_with_row_truncation_the_top_row_is_measured_first()
{
var stackLayout = new StackLayoutView(Orientation.Vertical);
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
var size = stackLayout.Measure(renderer, new Size(7, 1));
var firstViewTopRow = "The ".Length;
size.Should().BeEquivalentTo(new Size(firstViewTopRow, 1));
}
[Fact]
public void Measuring_a_horizontal_stack_sums_content_width()
{
var stackLayout = new StackLayoutView(Orientation.Horizontal);
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
var size = stackLayout.Measure(renderer, new Size(20, 20));
size.Should().BeEquivalentTo(new Size("The quickbrown fox".Length, 1));
}
[Fact]
public void Measuring_a_horizontal_stack_with_word_wrap_it_sums_max_width_for_each_child()
{
var stackLayout = new StackLayoutView(Orientation.Horizontal);
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
var size = stackLayout.Measure(renderer, new Size(10, 10));
size.Should().BeEquivalentTo(new Size(10, 2));
}
[Fact]
public void Measuring_a_horizontal_stack_with_truncated_height_measures_max_for_each_child()
{
var stackLayout = new StackLayoutView(Orientation.Horizontal);
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
var size = stackLayout.Measure(renderer, new Size(7, 1));
size.Should().BeEquivalentTo(new Size(7, 1));
}
[Fact]
public void Measuring_a_horizontal_stack_with_wide_children_wraps_last_child()
{
var stackLayout = new StackLayoutView(Orientation.Horizontal);
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
var size = stackLayout.Measure(renderer, new Size(12, 5));
size.Should().BeEquivalentTo(new Size(12, 2));
}
[Fact]
public void Measuring_a_vertical_stack_with_tall_children_trims_last_child()
{
var stackLayout = new StackLayoutView(Orientation.Vertical);
var child1 = new ContentView("The quick");
var child2 = new ContentView("brown fox");
stackLayout.Add(child1);
stackLayout.Add(child2);
var terminal = new TestTerminal();
var renderer = new ConsoleRenderer(terminal);
var size = stackLayout.Measure(renderer, new Size(5, 3));
size.Should().BeEquivalentTo(new Size(5, 3));
}
}
}
| 38.040956 | 101 | 0.603086 | [
"MIT"
] | jeredm/command-line-api | src/System.CommandLine.Rendering.Tests/Views/StackLayoutViewTests.cs | 11,148 | C# |
using System;
using Xamarin.Forms;
namespace Xamarin.CommunityToolkit.Core
{
[TypeConverter(typeof(FileMediaSourceConverter))]
public sealed class FileMediaSource : MediaSource
{
public static readonly BindableProperty FileProperty
= BindableProperty.Create(nameof(File), typeof(string), typeof(FileMediaSource), propertyChanged: OnFileMediaSourceChanged);
public string File
{
get => (string)GetValue(FileProperty);
set => SetValue(FileProperty, value);
}
public override string ToString() => $"File: {File}";
public static implicit operator FileMediaSource(string file) => (FileMediaSource)FromFile(file);
public static implicit operator string(FileMediaSource file) => file?.File;
static void OnFileMediaSourceChanged(BindableObject bindable, object oldValue, object newValue) =>
((FileMediaSource)bindable).OnSourceChanged();
}
} | 32.296296 | 127 | 0.772936 | [
"MIT"
] | AbuMandour/XamarinCommunityToolkit | XamarinCommunityToolkit/Core/FileMediaSource.shared.cs | 874 | C# |
namespace ClearHl7.Codes.V280
{
/// <summary>
/// HL7 Version 2 Table 0207 - Processing Mode.
/// </summary>
/// <remarks>https://www.hl7.org/fhir/v2/0207</remarks>
public enum CodeProcessingMode
{
/// <summary>
/// A - Archive.
/// </summary>
Archive,
/// <summary>
/// I - Initial load.
/// </summary>
InitialLoad,
/// <summary>
/// Not present - Not present (the default, meaning current processing).
/// </summary>
NotPresent,
/// <summary>
/// R - Restore from archive.
/// </summary>
RestoreFromArchive,
/// <summary>
/// T - Current processing, transmitted at intervals (scheduled or on demand).
/// </summary>
CurrentProcessing
}
}
| 23.828571 | 86 | 0.509592 | [
"MIT"
] | kamlesh-microsoft/clear-hl7-net | src/ClearHl7.Codes/V280/CodeProcessingMode.cs | 836 | C# |
using System;
using System.Runtime.InteropServices;
using starshipxac.Shell.Components.Interop;
using starshipxac.Shell.Interop;
namespace starshipxac.Shell.Components.Internal
{
/// <summary>
/// Define shell change notification.
/// </summary>
internal class ShellChangeNotify
{
/// <summary>
/// Initialize a instance of the <see cref="ShellChangeNotify"/> class.
/// </summary>
/// <param name="wParam"><c>WPARAM</c>.</param>
/// <param name="lParam"><c>LPARAM</c>.</param>
internal ShellChangeNotify(IntPtr wParam, IntPtr lParam)
{
var hwnd = wParam;
var processId = (UInt32)lParam.ToInt64();
IntPtr pidl;
uint lEvent;
var lockId = ShellWatcherNativeMethods.SHChangeNotification_Lock(hwnd, processId, out pidl, out lEvent);
try
{
this.ChangeType = (ShellChangeTypes)lEvent;
var notifyStruct = (ShellNotifyStruct)Marshal.PtrToStructure(pidl, typeof(ShellNotifyStruct));
var guid = new Guid(ShellIID.IShellItem2);
// dwItem1
if (notifyStruct.item1 != IntPtr.Zero &&
(this.ChangeType & ShellChangeTypes.SystemImageUpdate) == ShellChangeTypes.None)
{
var shellObject = CreateShellObject(notifyStruct.item1, ref guid);
if (shellObject != null)
{
this.ShellObject = shellObject;
}
}
else
{
ImageIndex = notifyStruct.item1.ToInt32();
}
// dwItem2
if (notifyStruct.item2 != IntPtr.Zero)
{
var shellObject = CreateShellObject(notifyStruct.item2, ref guid);
if (shellObject != null)
{
this.ShellObject2 = shellObject;
}
}
}
finally
{
if (lockId != IntPtr.Zero)
{
ShellWatcherNativeMethods.SHChangeNotification_Unlock(lockId);
}
}
}
/// <summary>
/// Get the shell change type.
/// </summary>
public ShellChangeTypes ChangeType { get; }
/// <summary>
/// Get a value that determines whether the event that occurred is a system event.
/// </summary>
public bool FromSystemInterrupt => (this.ChangeType & ShellChangeTypes.FromInterrupt) != ShellChangeTypes.None;
/// <summary>
/// Get the <see cref="ShellObject" />.
/// </summary>
public ShellObject ShellObject { get; }
/// <summary>
/// Get the second <see cref="ShellObject" />.
/// </summary>
public ShellObject ShellObject2 { get; }
/// <summary>
/// Get the image index.
/// </summary>
public int ImageIndex { get; private set; }
/// <summary>
/// Create a new instance of the <see cref="ShellObject" /> class.
/// </summary>
/// <param name="pidl"><c>PIDL</c>。</param>
/// <param name="riid"><c>GUID</c>。</param>
/// <returns></returns>
private static ShellObject CreateShellObject(IntPtr pidl, ref Guid riid)
{
IShellItem2 shellItem2;
var code = ShellNativeMethods.SHCreateItemFromIDList(pidl, ref riid, out shellItem2);
if (HRESULT.Failed(code))
{
return null;
}
return ShellFactory.FromShellItem(new ShellItem(shellItem2));
}
}
} | 34.917431 | 119 | 0.516027 | [
"MIT"
] | rasmus-z/starshipxac.ShellLibrary | Source/starshipxac.Shell/Components/Internal/ShellChangeNotify.cs | 3,812 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace service.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
| 28.475 | 110 | 0.598771 | [
"MIT"
] | 4thex/farm | service/Controllers/WeatherForecastController.cs | 1,141 | C# |
using System.IO;
using System.Text;
using Itg.ZabbixAgent.Core;
using NFluent;
using Xunit;
namespace Itg.ZabbixAgent.Tests
{
public class ZabbixProtocolTests
{
[Theory]
[InlineData("", null, "ZBXD\x01\x00\x00\x00\x00\x00\x00\x00\x00")]
[InlineData("foo", null, "ZBXD\x01\x03\x00\x00\x00\x00\x00\x00\x0000foo")]
[InlineData("foo", "bar", "ZBXD\x01\x03\x00\x00\x00\x00\x00\x00\x0000foo\0bar")]
public void WriteWithHeader_theory(string value, string error, string expected)
{
using (var stream = new MemoryStream())
{
ZabbixProtocol.WriteWithHeader(stream, value, error);
var actualBytes = stream.ToArray();
var expectedBytes = Encoding.ASCII.GetBytes(expected);
Check.That(actualBytes).ContainsExactly(expectedBytes);
}
}
}
}
| 33.185185 | 88 | 0.617188 | [
"MIT"
] | RFQ-hub/ZabbixAgentLib | src/ZabbixAgent.Tests/Core/ZabbixProtocolTests.cs | 898 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Mobet.Dependency;
namespace Mobet.Runtime.Session
{
/// <summary>
/// Implements <see cref="IAppSession"/> to get session properties from claims of <see cref="Thread.CurrentPrincipal"/>.
/// </summary>
public class AppClaimsSession : IAppSession, IDependency
{
public virtual string Name
{
get
{
var claims = System.Security.Claims.ClaimsPrincipal.Current.Claims;
if (claims == null)
{
return null;
}
var userNameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);
if (userNameClaim == null || string.IsNullOrEmpty(userNameClaim.Value))
{
return null;
}
return userNameClaim.Value;
}
}
public virtual string UserId
{
get
{
var claims = System.Security.Claims.ClaimsPrincipal.Current.Claims;
if (claims == null)
{
return null;
}
var userIdClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
if (userIdClaim == null || string.IsNullOrEmpty(userIdClaim.Value))
{
return null;
}
return userIdClaim.Value;
}
}
}
}
| 28.206897 | 124 | 0.518337 | [
"Apache-2.0"
] | Mobet/mobet | Mobet-Net/Mobet/Runtime/Session/AppClaimsSession.cs | 1,638 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the directconnect-2012-10-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.DirectConnect.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DirectConnect.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for AllocatePrivateVirtualInterface operation
/// </summary>
public class AllocatePrivateVirtualInterfaceResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
AllocatePrivateVirtualInterfaceResponse response = new AllocatePrivateVirtualInterfaceResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("addressFamily", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.AddressFamily = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("amazonAddress", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.AmazonAddress = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("amazonSideAsn", targetDepth))
{
var unmarshaller = LongUnmarshaller.Instance;
response.AmazonSideAsn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("asn", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
response.Asn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("authKey", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.AuthKey = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("awsDeviceV2", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.AwsDeviceV2 = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("awsLogicalDeviceId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.AwsLogicalDeviceId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("bgpPeers", targetDepth))
{
var unmarshaller = new ListUnmarshaller<BGPPeer, BGPPeerUnmarshaller>(BGPPeerUnmarshaller.Instance);
response.BgpPeers = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("connectionId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.ConnectionId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("customerAddress", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.CustomerAddress = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("customerRouterConfig", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.CustomerRouterConfig = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("directConnectGatewayId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.DirectConnectGatewayId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("jumboFrameCapable", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
response.JumboFrameCapable = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("location", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Location = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("mtu", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
response.Mtu = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ownerAccount", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.OwnerAccount = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("region", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Region = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("routeFilterPrefixes", targetDepth))
{
var unmarshaller = new ListUnmarshaller<RouteFilterPrefix, RouteFilterPrefixUnmarshaller>(RouteFilterPrefixUnmarshaller.Instance);
response.RouteFilterPrefixes = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("siteLinkEnabled", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
response.SiteLinkEnabled = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("tags", targetDepth))
{
var unmarshaller = new ListUnmarshaller<Tag, TagUnmarshaller>(TagUnmarshaller.Instance);
response.Tags = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("virtualGatewayId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.VirtualGatewayId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("virtualInterfaceId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.VirtualInterfaceId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("virtualInterfaceName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.VirtualInterfaceName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("virtualInterfaceState", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.VirtualInterfaceState = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("virtualInterfaceType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.VirtualInterfaceType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("vlan", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
response.Vlan = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("DirectConnectClientException"))
{
return DirectConnectClientExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("DirectConnectServerException"))
{
return DirectConnectServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("DuplicateTagKeysException"))
{
return DuplicateTagKeysExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyTagsException"))
{
return TooManyTagsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonDirectConnectException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static AllocatePrivateVirtualInterfaceResponseUnmarshaller _instance = new AllocatePrivateVirtualInterfaceResponseUnmarshaller();
internal static AllocatePrivateVirtualInterfaceResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static AllocatePrivateVirtualInterfaceResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 45.176471 | 196 | 0.572591 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/DirectConnect/Generated/Model/Internal/MarshallTransformations/AllocatePrivateVirtualInterfaceResponseUnmarshaller.cs | 12,288 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Security;
using System.Windows.Forms;
namespace CriticalCode
{
public class TesteCriticalCode : Interface1
{
public string Procesa_Algo()
{
return "Procesado o texto";
}
public List<String> ListaArquivos_Windows()
{
var path_Directory = @"C:\Windows";
var olista = new List<String>();
// Obter arquivo de um diretório específico usando a classe de diretório
string[] fileNames = Directory.GetFiles(path_Directory);
foreach (var name in fileNames)
{
olista.Add("Arquivo: " + name);
}
return olista;
}
public void ShowDialog()
{
OpenFileDialog window = new OpenFileDialog();
window.ShowDialog();
}
}
}
| 23.512821 | 84 | 0.564885 | [
"MIT"
] | shyoutarou/Exam-70-483_Depurar_seguran-a | Exemplos/02_Cripto/CodeAccessPermissions/CriticalCode/TesteCriticalCode.cs | 922 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Demo.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 32.483871 | 149 | 0.608739 | [
"MIT"
] | ariksman/XamlThemes | Demo/Properties/Settings.Designer.cs | 1,009 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Castr.IntegrationTests.Models
{
class Stats
{
public string Home_team_name { get; set; }
public string Away_team_name { get; set; }
public string Referee { get; set; }
public float Home_team_corner_count { get; set; }
public float Away_team_corner_count { get; set; }
public float Total_corners { get; set; }
public string Stadium_name { get; set; }
}
} | 19.884615 | 57 | 0.634429 | [
"MIT"
] | pcmichaels/CastDataAs | Castr.IntegrationTests/Models/Stats.cs | 519 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
namespace Microsoft.Azure.Management.Insights.Models
{
/// <summary>
/// The status of the diagnostic settings being applied.
/// </summary>
public enum DiagnosticSettingsStatus
{
/// <summary>
/// The configuration has been successfully applied and is active.
/// </summary>
Succeeded = 0,
/// <summary>
/// The configuration was accepted and is being applied.
/// </summary>
Accepted = 1,
/// <summary>
/// The configuration was not successfully applied.
/// </summary>
Failed = 2,
}
}
| 30.166667 | 76 | 0.655387 | [
"Apache-2.0"
] | chuanboz/HDInsight | src/Insights/Generated/Management/Insights/Models/DiagnosticSettingsStatus.cs | 1,448 | C# |
using Microsoft.EntityFrameworkCore;
namespace ADSBackend.Data
{
public static class ContextExtensions
{
public static void AddOrUpdate(this ApplicationDbContext ctx, object entity)
{
var entry = ctx.Entry(entity);
switch (entry.State)
{
case EntityState.Detached:
ctx.Add(entity);
break;
case EntityState.Modified:
ctx.Update(entity);
break;
case EntityState.Added:
ctx.Add(entity);
break;
case EntityState.Unchanged:
// item already in db no need to do anything
break;
default:
throw new System.ArgumentOutOfRangeException();
}
}
}
}
| 28.548387 | 84 | 0.479096 | [
"MIT"
] | Taranveer1/ADSBackend | ADSBackend/Data/ContextExtensions.cs | 887 | C# |
namespace Uno.Native.Fonts
{
public struct RenderedGlyph
{
public float AdvanceX, AdvanceY;
public float BearingX, BearingY;
public Textures.PixelFormat PixelFormat;
public int Width, Height;
public byte[] Bitmap;
}
} | 24.454545 | 48 | 0.64684 | [
"MIT"
] | fuse-open/Uno.Native | Source/Uno.Native/Fonts/RenderedGlyph.cs | 269 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
[ExportArgumentProvider(nameof(ContextVariableArgumentProvider), LanguageNames.CSharp)]
[ExtensionOrder(After = nameof(FirstBuiltInArgumentProvider))]
[Shared]
internal sealed class ContextVariableArgumentProvider : AbstractContextVariableArgumentProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ContextVariableArgumentProvider() { }
}
}
| 38 | 99 | 0.783493 | [
"MIT"
] | belav/roslyn | src/Features/CSharp/Portable/Completion/Providers/ContextVariableArgumentProvider.cs | 838 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Media.V20200501.Outputs
{
/// <summary>
/// The IP access control for live event input.
/// </summary>
[OutputType]
public sealed class LiveEventInputAccessControlResponse
{
/// <summary>
/// The IP access control properties.
/// </summary>
public readonly Outputs.IPAccessControlResponse? Ip;
[OutputConstructor]
private LiveEventInputAccessControlResponse(Outputs.IPAccessControlResponse? ip)
{
Ip = ip;
}
}
}
| 27.290323 | 88 | 0.669031 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Media/V20200501/Outputs/LiveEventInputAccessControlResponse.cs | 846 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Media.SpeechSynthesis;
using Windows.UI.Popups;
namespace Zeitansage
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| 37.252174 | 99 | 0.629318 | [
"MIT"
] | stephanhuewe/PiBuch | Zeitansage/App.xaml.cs | 4,286 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
namespace Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts.ExecuteRequests
{
/// <summary>
/// Parameters for executing a query directly
/// </summary>
public class ExecuteStringParams : ExecuteRequestParamsBase
{
/// <summary>
/// The query to execute
/// </summary>
public string Query { get; set; }
}
public class ExecuteStringRequest
{
public static readonly
RequestType<ExecuteStringParams, ExecuteRequestResult> Type =
RequestType<ExecuteStringParams, ExecuteRequestResult>.Create("query/executeString");
}
}
| 29.964286 | 101 | 0.686532 | [
"MIT"
] | Bhaskers-Blu-Org2/sqltoolsservice | src/Microsoft.SqlTools.ServiceLayer/QueryExecution/Contracts/ExecuteRequests/ExecuteStringRequest.cs | 841 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the quicksight-2018-04-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.QuickSight.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.QuickSight.Model.Internal.MarshallTransformations
{
/// <summary>
/// DeleteThemeAlias Request Marshaller
/// </summary>
public class DeleteThemeAliasRequestMarshaller : IMarshaller<IRequest, DeleteThemeAliasRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((DeleteThemeAliasRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DeleteThemeAliasRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.QuickSight");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-04-01";
request.HttpMethod = "DELETE";
if (!publicRequest.IsSetAliasName())
throw new AmazonQuickSightException("Request object does not have required field AliasName set");
request.AddPathResource("{AliasName}", StringUtils.FromString(publicRequest.AliasName));
if (!publicRequest.IsSetAwsAccountId())
throw new AmazonQuickSightException("Request object does not have required field AwsAccountId set");
request.AddPathResource("{AwsAccountId}", StringUtils.FromString(publicRequest.AwsAccountId));
if (!publicRequest.IsSetThemeId())
throw new AmazonQuickSightException("Request object does not have required field ThemeId set");
request.AddPathResource("{ThemeId}", StringUtils.FromString(publicRequest.ThemeId));
request.ResourcePath = "/accounts/{AwsAccountId}/themes/{ThemeId}/aliases/{AliasName}";
request.MarshallerVersion = 2;
return request;
}
private static DeleteThemeAliasRequestMarshaller _instance = new DeleteThemeAliasRequestMarshaller();
internal static DeleteThemeAliasRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteThemeAliasRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.787234 | 148 | 0.650267 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/QuickSight/Generated/Model/Internal/MarshallTransformations/DeleteThemeAliasRequestMarshaller.cs | 3,740 | C# |
using UnityEngine;
using UnityEngine.EventSystems;
#pragma warning disable 0618 // Disabled warning due to SetVertices being deprecated until new release with SetMesh() is available.
namespace TMPro.Examples
{
public class TMP_TextSelector_B : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler, IPointerUpHandler
{
public RectTransform TextPopup_Prefab_01;
private RectTransform m_TextPopup_RectTransform;
private TextMeshProUGUI m_TextPopup_TMPComponent;
private const string k_LinkText = "You have selected link <#ffff00>";
private const string k_WordText = "Word Index: <#ffff00>";
private TextMeshProUGUI m_TextMeshPro;
private Canvas m_Canvas;
private Camera m_Camera;
// Flags
private bool isHoveringObject;
private int m_selectedWord = -1;
private int m_selectedLink = -1;
private int m_lastIndex = -1;
private Matrix4x4 m_matrix;
private TMP_MeshInfo[] m_cachedMeshInfoVertexData;
void Awake()
{
m_TextMeshPro = gameObject.GetComponent<TextMeshProUGUI>();
m_Canvas = gameObject.GetComponentInParent<Canvas>();
// Get a reference to the camera if Canvas Render Mode is not ScreenSpace Overlay.
if (m_Canvas.renderMode == RenderMode.ScreenSpaceOverlay)
m_Camera = null;
else
m_Camera = m_Canvas.worldCamera;
// Create pop-up text object which is used to show the link information.
m_TextPopup_RectTransform = Instantiate(TextPopup_Prefab_01) as RectTransform;
m_TextPopup_RectTransform.SetParent(m_Canvas.transform, false);
m_TextPopup_TMPComponent = m_TextPopup_RectTransform.GetComponentInChildren<TextMeshProUGUI>();
m_TextPopup_RectTransform.gameObject.SetActive(false);
}
void OnEnable()
{
// Subscribe to event fired when text object has been regenerated.
TMPro_EventManager.TEXT_CHANGED_EVENT.Add(ON_TEXT_CHANGED);
}
void OnDisable()
{
// UnSubscribe to event fired when text object has been regenerated.
TMPro_EventManager.TEXT_CHANGED_EVENT.Remove(ON_TEXT_CHANGED);
}
void ON_TEXT_CHANGED(Object obj)
{
if (obj == m_TextMeshPro)
{
// Update cached vertex data.
m_cachedMeshInfoVertexData = m_TextMeshPro.textInfo.CopyMeshInfoVertexData();
}
}
void LateUpdate()
{
if (isHoveringObject)
{
// Check if Mouse Intersects any of the characters. If so, assign a random color.
#region Handle Character Selection
int charIndex = TMP_TextUtilities.FindIntersectingCharacter(m_TextMeshPro, Input.mousePosition, m_Camera, true);
// Undo Swap and Vertex Attribute changes.
if (charIndex == -1 || charIndex != m_lastIndex)
{
RestoreCachedVertexAttributes(m_lastIndex);
m_lastIndex = -1;
}
if (charIndex != -1 && charIndex != m_lastIndex && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
{
m_lastIndex = charIndex;
// Get the index of the material / sub text object used by this character.
int materialIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].materialReferenceIndex;
// Get the index of the first vertex of the selected character.
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].vertexIndex;
// Get a reference to the vertices array.
Vector3[] vertices = m_TextMeshPro.textInfo.meshInfo[materialIndex].vertices;
// Determine the center point of the character.
Vector2 charMidBasline = (vertices[vertexIndex + 0] + vertices[vertexIndex + 2]) / 2;
// Need to translate all 4 vertices of the character to aligned with middle of character / baseline.
// This is needed so the matrix TRS is applied at the origin for each character.
Vector3 offset = charMidBasline;
// Translate the character to the middle baseline.
vertices[vertexIndex + 0] = vertices[vertexIndex + 0] - offset;
vertices[vertexIndex + 1] = vertices[vertexIndex + 1] - offset;
vertices[vertexIndex + 2] = vertices[vertexIndex + 2] - offset;
vertices[vertexIndex + 3] = vertices[vertexIndex + 3] - offset;
float zoomFactor = 1.5f;
// Setup the Matrix for the scale change.
m_matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, Vector3.one * zoomFactor);
// Apply Matrix operation on the given character.
vertices[vertexIndex + 0] = m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 0]);
vertices[vertexIndex + 1] = m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 1]);
vertices[vertexIndex + 2] = m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 2]);
vertices[vertexIndex + 3] = m_matrix.MultiplyPoint3x4(vertices[vertexIndex + 3]);
// Translate the character back to its original position.
vertices[vertexIndex + 0] = vertices[vertexIndex + 0] + offset;
vertices[vertexIndex + 1] = vertices[vertexIndex + 1] + offset;
vertices[vertexIndex + 2] = vertices[vertexIndex + 2] + offset;
vertices[vertexIndex + 3] = vertices[vertexIndex + 3] + offset;
// Change Vertex Colors of the highlighted character
Color32 c = new Color32(255, 255, 192, 255);
// Get a reference to the vertex color
Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[materialIndex].colors32;
vertexColors[vertexIndex + 0] = c;
vertexColors[vertexIndex + 1] = c;
vertexColors[vertexIndex + 2] = c;
vertexColors[vertexIndex + 3] = c;
// Get a reference to the meshInfo of the selected character.
TMP_MeshInfo meshInfo = m_TextMeshPro.textInfo.meshInfo[materialIndex];
// Get the index of the last character's vertex attributes.
int lastVertexIndex = vertices.Length - 4;
// Swap the current character's vertex attributes with those of the last element in the vertex attribute arrays.
// We do this to make sure this character is rendered last and over other characters.
meshInfo.SwapVertexData(vertexIndex, lastVertexIndex);
// Need to update the appropriate
m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
}
#endregion
#region Word Selection Handling
//Check if Mouse intersects any words and if so assign a random color to that word.
int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextMeshPro, Input.mousePosition, m_Camera);
// Clear previous word selection.
if (m_TextPopup_RectTransform != null && m_selectedWord != -1 && (wordIndex == -1 || wordIndex != m_selectedWord))
{
TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[m_selectedWord];
// Iterate through each of the characters of the word.
for (int i = 0; i < wInfo.characterCount; i++)
{
int characterIndex = wInfo.firstCharacterIndex + i;
// Get the index of the material / sub text object used by this character.
int meshIndex = m_TextMeshPro.textInfo.characterInfo[characterIndex].materialReferenceIndex;
// Get the index of the first vertex of this character.
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[characterIndex].vertexIndex;
// Get a reference to the vertex color
Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[meshIndex].colors32;
Color32 c = vertexColors[vertexIndex + 0].Tint(1.33333f);
vertexColors[vertexIndex + 0] = c;
vertexColors[vertexIndex + 1] = c;
vertexColors[vertexIndex + 2] = c;
vertexColors[vertexIndex + 3] = c;
}
// Update Geometry
m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
m_selectedWord = -1;
}
// Word Selection Handling
if (wordIndex != -1 && wordIndex != m_selectedWord && !(Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)))
{
m_selectedWord = wordIndex;
TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[wordIndex];
// Iterate through each of the characters of the word.
for (int i = 0; i < wInfo.characterCount; i++)
{
int characterIndex = wInfo.firstCharacterIndex + i;
// Get the index of the material / sub text object used by this character.
int meshIndex = m_TextMeshPro.textInfo.characterInfo[characterIndex].materialReferenceIndex;
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[characterIndex].vertexIndex;
// Get a reference to the vertex color
Color32[] vertexColors = m_TextMeshPro.textInfo.meshInfo[meshIndex].colors32;
Color32 c = vertexColors[vertexIndex + 0].Tint(0.75f);
vertexColors[vertexIndex + 0] = c;
vertexColors[vertexIndex + 1] = c;
vertexColors[vertexIndex + 2] = c;
vertexColors[vertexIndex + 3] = c;
}
// Update Geometry
m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
}
#endregion
#region Example of Link Handling
// Check if mouse intersects with any links.
int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextMeshPro, Input.mousePosition, m_Camera);
// Clear previous link selection if one existed.
if ((linkIndex == -1 && m_selectedLink != -1) || linkIndex != m_selectedLink)
{
m_TextPopup_RectTransform.gameObject.SetActive(false);
m_selectedLink = -1;
}
// Handle new Link selection.
if (linkIndex != -1 && linkIndex != m_selectedLink)
{
m_selectedLink = linkIndex;
TMP_LinkInfo linkInfo = m_TextMeshPro.textInfo.linkInfo[linkIndex];
// Debug.Log("Link ID: \"" + linkInfo.GetLinkID() + "\" Link Text: \"" + linkInfo.GetLinkText() + "\""); // Example of how to retrieve the Link ID and Link Text.
Vector3 worldPointInRectangle = Vector3.zero;
RectTransformUtility.ScreenPointToWorldPointInRectangle(m_TextMeshPro.rectTransform, Input.mousePosition, m_Camera, out worldPointInRectangle);
switch (linkInfo.GetLinkID())
{
case "id_01": // 100041637: // id_01
m_TextPopup_RectTransform.position = worldPointInRectangle;
m_TextPopup_RectTransform.gameObject.SetActive(true);
m_TextPopup_TMPComponent.text = k_LinkText + " ID 01";
break;
case "id_02": // 100041638: // id_02
m_TextPopup_RectTransform.position = worldPointInRectangle;
m_TextPopup_RectTransform.gameObject.SetActive(true);
m_TextPopup_TMPComponent.text = k_LinkText + " ID 02";
break;
}
}
#endregion
}
else
{
// Restore any character that may have been modified
if (m_lastIndex != -1)
{
RestoreCachedVertexAttributes(m_lastIndex);
m_lastIndex = -1;
}
}
}
public void OnPointerEnter(PointerEventData eventData)
{
//Debug.Log("OnPointerEnter()");
isHoveringObject = true;
}
public void OnPointerExit(PointerEventData eventData)
{
//Debug.Log("OnPointerExit()");
isHoveringObject = false;
}
public void OnPointerClick(PointerEventData eventData)
{
//Debug.Log("Click at POS: " + eventData.position + " World POS: " + eventData.worldPosition);
// Check if Mouse Intersects any of the characters. If so, assign a random color.
#region Character Selection Handling
/*
int charIndex = TMP_TextUtilities.FindIntersectingCharacter(m_TextMeshPro, Input.mousePosition, m_Camera, true);
if (charIndex != -1 && charIndex != m_lastIndex)
{
//Debug.Log("Character [" + m_TextMeshPro.textInfo.characterInfo[index].character + "] was selected at POS: " + eventData.position);
m_lastIndex = charIndex;
Color32 c = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255);
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[charIndex].vertexIndex;
UIVertex[] uiVertices = m_TextMeshPro.textInfo.meshInfo.uiVertices;
uiVertices[vertexIndex + 0].color = c;
uiVertices[vertexIndex + 1].color = c;
uiVertices[vertexIndex + 2].color = c;
uiVertices[vertexIndex + 3].color = c;
m_TextMeshPro.canvasRenderer.SetVertices(uiVertices, uiVertices.Length);
}
*/
#endregion
#region Word Selection Handling
//Check if Mouse intersects any words and if so assign a random color to that word.
/*
int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextMeshPro, Input.mousePosition, m_Camera);
// Clear previous word selection.
if (m_TextPopup_RectTransform != null && m_selectedWord != -1 && (wordIndex == -1 || wordIndex != m_selectedWord))
{
TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[m_selectedWord];
// Get a reference to the uiVertices array.
UIVertex[] uiVertices = m_TextMeshPro.textInfo.meshInfo.uiVertices;
// Iterate through each of the characters of the word.
for (int i = 0; i < wInfo.characterCount; i++)
{
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[wInfo.firstCharacterIndex + i].vertexIndex;
Color32 c = uiVertices[vertexIndex + 0].color.Tint(1.33333f);
uiVertices[vertexIndex + 0].color = c;
uiVertices[vertexIndex + 1].color = c;
uiVertices[vertexIndex + 2].color = c;
uiVertices[vertexIndex + 3].color = c;
}
m_TextMeshPro.canvasRenderer.SetVertices(uiVertices, uiVertices.Length);
m_selectedWord = -1;
}
// Handle word selection
if (wordIndex != -1 && wordIndex != m_selectedWord)
{
m_selectedWord = wordIndex;
TMP_WordInfo wInfo = m_TextMeshPro.textInfo.wordInfo[wordIndex];
// Get a reference to the uiVertices array.
UIVertex[] uiVertices = m_TextMeshPro.textInfo.meshInfo.uiVertices;
// Iterate through each of the characters of the word.
for (int i = 0; i < wInfo.characterCount; i++)
{
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[wInfo.firstCharacterIndex + i].vertexIndex;
Color32 c = uiVertices[vertexIndex + 0].color.Tint(0.75f);
uiVertices[vertexIndex + 0].color = c;
uiVertices[vertexIndex + 1].color = c;
uiVertices[vertexIndex + 2].color = c;
uiVertices[vertexIndex + 3].color = c;
}
m_TextMeshPro.canvasRenderer.SetVertices(uiVertices, uiVertices.Length);
}
*/
#endregion
#region Link Selection Handling
/*
// Check if Mouse intersects any words and if so assign a random color to that word.
int linkIndex = TMP_TextUtilities.FindIntersectingLink(m_TextMeshPro, Input.mousePosition, m_Camera);
if (linkIndex != -1)
{
TMP_LinkInfo linkInfo = m_TextMeshPro.textInfo.linkInfo[linkIndex];
int linkHashCode = linkInfo.hashCode;
//Debug.Log(TMP_TextUtilities.GetSimpleHashCode("id_02"));
switch (linkHashCode)
{
case 291445: // id_01
if (m_LinkObject01 == null)
m_LinkObject01 = Instantiate(Link_01_Prefab);
else
{
m_LinkObject01.gameObject.SetActive(true);
}
break;
case 291446: // id_02
break;
}
// Example of how to modify vertex attributes like colors
#region Vertex Attribute Modification Example
UIVertex[] uiVertices = m_TextMeshPro.textInfo.meshInfo.uiVertices;
Color32 c = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), 255);
for (int i = 0; i < linkInfo.characterCount; i++)
{
TMP_CharacterInfo cInfo = m_TextMeshPro.textInfo.characterInfo[linkInfo.firstCharacterIndex + i];
if (!cInfo.isVisible) continue; // Skip invisible characters.
int vertexIndex = cInfo.vertexIndex;
uiVertices[vertexIndex + 0].color = c;
uiVertices[vertexIndex + 1].color = c;
uiVertices[vertexIndex + 2].color = c;
uiVertices[vertexIndex + 3].color = c;
}
m_TextMeshPro.canvasRenderer.SetVertices(uiVertices, uiVertices.Length);
#endregion
}
*/
#endregion
}
public void OnPointerUp(PointerEventData eventData)
{
//Debug.Log("OnPointerUp()");
}
void RestoreCachedVertexAttributes(int index)
{
if (index == -1 || index > m_TextMeshPro.textInfo.characterCount - 1) return;
// Get the index of the material / sub text object used by this character.
int materialIndex = m_TextMeshPro.textInfo.characterInfo[index].materialReferenceIndex;
// Get the index of the first vertex of the selected character.
int vertexIndex = m_TextMeshPro.textInfo.characterInfo[index].vertexIndex;
// Restore Vertices
// Get a reference to the cached / original vertices.
Vector3[] src_vertices = m_cachedMeshInfoVertexData[materialIndex].vertices;
// Get a reference to the vertices that we need to replace.
Vector3[] dst_vertices = m_TextMeshPro.textInfo.meshInfo[materialIndex].vertices;
// Restore / Copy vertices from source to destination
dst_vertices[vertexIndex + 0] = src_vertices[vertexIndex + 0];
dst_vertices[vertexIndex + 1] = src_vertices[vertexIndex + 1];
dst_vertices[vertexIndex + 2] = src_vertices[vertexIndex + 2];
dst_vertices[vertexIndex + 3] = src_vertices[vertexIndex + 3];
// Restore Vertex Colors
// Get a reference to the vertex colors we need to replace.
Color32[] dst_colors = m_TextMeshPro.textInfo.meshInfo[materialIndex].colors32;
// Get a reference to the cached / original vertex colors.
Color32[] src_colors = m_cachedMeshInfoVertexData[materialIndex].colors32;
// Copy the vertex colors from source to destination.
dst_colors[vertexIndex + 0] = src_colors[vertexIndex + 0];
dst_colors[vertexIndex + 1] = src_colors[vertexIndex + 1];
dst_colors[vertexIndex + 2] = src_colors[vertexIndex + 2];
dst_colors[vertexIndex + 3] = src_colors[vertexIndex + 3];
// Restore UV0S
// UVS0
Vector2[] src_uv0s = m_cachedMeshInfoVertexData[materialIndex].uvs0;
Vector2[] dst_uv0s = m_TextMeshPro.textInfo.meshInfo[materialIndex].uvs0;
dst_uv0s[vertexIndex + 0] = src_uv0s[vertexIndex + 0];
dst_uv0s[vertexIndex + 1] = src_uv0s[vertexIndex + 1];
dst_uv0s[vertexIndex + 2] = src_uv0s[vertexIndex + 2];
dst_uv0s[vertexIndex + 3] = src_uv0s[vertexIndex + 3];
// UVS2
Vector2[] src_uv2s = m_cachedMeshInfoVertexData[materialIndex].uvs2;
Vector2[] dst_uv2s = m_TextMeshPro.textInfo.meshInfo[materialIndex].uvs2;
dst_uv2s[vertexIndex + 0] = src_uv2s[vertexIndex + 0];
dst_uv2s[vertexIndex + 1] = src_uv2s[vertexIndex + 1];
dst_uv2s[vertexIndex + 2] = src_uv2s[vertexIndex + 2];
dst_uv2s[vertexIndex + 3] = src_uv2s[vertexIndex + 3];
// Restore last vertex attribute as we swapped it as well
int lastIndex = (src_vertices.Length / 4 - 1) * 4;
// Vertices
dst_vertices[lastIndex + 0] = src_vertices[lastIndex + 0];
dst_vertices[lastIndex + 1] = src_vertices[lastIndex + 1];
dst_vertices[lastIndex + 2] = src_vertices[lastIndex + 2];
dst_vertices[lastIndex + 3] = src_vertices[lastIndex + 3];
// Vertex Colors
src_colors = m_cachedMeshInfoVertexData[materialIndex].colors32;
dst_colors = m_TextMeshPro.textInfo.meshInfo[materialIndex].colors32;
dst_colors[lastIndex + 0] = src_colors[lastIndex + 0];
dst_colors[lastIndex + 1] = src_colors[lastIndex + 1];
dst_colors[lastIndex + 2] = src_colors[lastIndex + 2];
dst_colors[lastIndex + 3] = src_colors[lastIndex + 3];
// UVS0
src_uv0s = m_cachedMeshInfoVertexData[materialIndex].uvs0;
dst_uv0s = m_TextMeshPro.textInfo.meshInfo[materialIndex].uvs0;
dst_uv0s[lastIndex + 0] = src_uv0s[lastIndex + 0];
dst_uv0s[lastIndex + 1] = src_uv0s[lastIndex + 1];
dst_uv0s[lastIndex + 2] = src_uv0s[lastIndex + 2];
dst_uv0s[lastIndex + 3] = src_uv0s[lastIndex + 3];
// UVS2
src_uv2s = m_cachedMeshInfoVertexData[materialIndex].uvs2;
dst_uv2s = m_TextMeshPro.textInfo.meshInfo[materialIndex].uvs2;
dst_uv2s[lastIndex + 0] = src_uv2s[lastIndex + 0];
dst_uv2s[lastIndex + 1] = src_uv2s[lastIndex + 1];
dst_uv2s[lastIndex + 2] = src_uv2s[lastIndex + 2];
dst_uv2s[lastIndex + 3] = src_uv2s[lastIndex + 3];
// Need to update the appropriate
m_TextMeshPro.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
}
}
}
| 45.009174 | 182 | 0.573461 | [
"MIT"
] | Kalystee/Platformer_NoName | Assets/Imports/TextMesh Pro/Examples & Extras/Scripts/TMP_TextSelector_B.cs | 24,532 | C# |
// Write a program that downloads a file from Internet (e.g. http://www.devbg.org/img/Logo-BASD.jpg)
// and stores it the current directory. Find in Google how to download files in C#.
// Be sure to catch all exceptions and to free any used resources in the finally block.
using System;
using System.Net;
class DownloadFile
{
static void Main()
{
using (WebClient webClient = new WebClient())
{
string addres = @"http://www.devbg.org/img/Logo-BASD.jpg";
string filePath = @"..\..\downloads\logo.jpg";
try
{
webClient.DownloadFile(addres, filePath);
Console.WriteLine("Download complete!");
}
catch (ArgumentNullException)
{
Console.WriteLine("The address parameter is null");
}
catch (WebException)
{
Console.WriteLine("The address is invalid.");
}
catch (NotSupportedException)
{
Console.WriteLine("The method has been called simultaneously on multiple threads.");
}
}
}
} | 31.459459 | 101 | 0.559278 | [
"MIT"
] | PetarMetodiev/Telerik-Homeworks | C# Part 2/07.Exception-Handling/ExceptionHandling/04.DownloadFile/Program.cs | 1,166 | C# |
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using SteffBeckers.Abp.Generator.Helpers;
using SteffBeckers.Abp.Generator.Settings;
using System.Diagnostics;
using System.Text;
using System.Text.Json;
namespace SteffBeckers.Abp.Generator.Templates;
public class ProjectTemplatesService
{
private readonly SettingsService _settingsService;
private List<ProjectTemplate> _templates = new List<ProjectTemplate>();
public ProjectTemplatesService(SettingsService settingsService)
{
_settingsService = settingsService;
}
public Task GenerateAsync(ProjectTemplateGenerateInputDto input)
{
ProjectTemplate? template = _templates.FirstOrDefault(x => x.Name == input.TemplateName);
if (template == null || string.IsNullOrEmpty(template.FullPath))
{
return Task.CompletedTask;
}
string templateSourcePath = Path.Combine(template.FullPath, "Source");
List<string> templateSourceFilePaths = Directory.GetFiles(path: templateSourcePath, searchPattern: "*", searchOption: SearchOption.AllDirectories).ToList();
return Parallel.ForEachAsync(
templateSourceFilePaths,
async (sourceFilePath, cancellationToken) =>
{
string outputPath = sourceFilePath
.Replace($"{templateSourcePath}{Path.DirectorySeparatorChar}", string.Empty)
.Replace(Path.DirectorySeparatorChar, '/');
string fullOutputPath = Path.Combine(_settingsService.Settings.ProjectPath, outputPath);
if (fullOutputPath == null)
{
return;
}
fullOutputPath = ReplaceContextVariables(fullOutputPath);
string? fullOutputDirectoryPath = Path.GetDirectoryName(fullOutputPath);
if (fullOutputDirectoryPath == null)
{
return;
}
if (!Directory.Exists(fullOutputPath))
{
Directory.CreateDirectory(fullOutputDirectoryPath);
}
string sourceFileText = await File.ReadAllTextAsync(sourceFilePath, cancellationToken);
sourceFileText = ReplaceContextVariables(sourceFileText);
await File.WriteAllTextAsync(fullOutputPath, sourceFileText, cancellationToken);
});
}
public Task<List<ProjectTemplate>> GetListAsync()
{
return Task.FromResult(_templates);
}
public async Task InitializeAsync()
{
// Copy project templates from source to user based project templates folder.
if (Directory.Exists(FileHelpers.UserBasedProjectTemplatesPath))
{
Directory.Delete(FileHelpers.UserBasedProjectTemplatesPath, true);
}
Directory.CreateDirectory(FileHelpers.UserBasedProjectTemplatesPath);
FileHelpers.CopyFilesRecursively(FileHelpers.ProjectTemplatesPath, FileHelpers.UserBasedProjectTemplatesPath);
// Load all project templates on startup.
await LoadTemplatesAsync();
// Reload all snippet templates when the settings change.
_settingsService.Monitor.OnChange(async (settings) => await LoadTemplatesAsync());
}
public Task OpenFolderAsync()
{
Process.Start(
new ProcessStartInfo()
{
FileName = FileHelpers.UserBasedProjectTemplatesPath,
UseShellExecute = true,
Verb = "open"
});
return Task.CompletedTask;
}
private async Task LoadTemplatesAsync()
{
string? templateFilesDirectory = Path.GetDirectoryName(FileHelpers.UserBasedProjectTemplatesPath);
if (string.IsNullOrEmpty(templateFilesDirectory))
{
throw new Exception($"Template files directory not found: {FileHelpers.UserBasedProjectTemplatesPath}");
}
List<string> templateSettingFilePaths = Directory.GetFiles(
path: templateFilesDirectory,
searchPattern: "templatesettings.json",
searchOption: SearchOption.AllDirectories)
.ToList();
foreach (string templateSettingFilePath in templateSettingFilePaths)
{
string templateSettingFileText = await File.ReadAllTextAsync(templateSettingFilePath);
ProjectTemplate? projectTemplate = JsonConvert.DeserializeObject<ProjectTemplate>(templateSettingFileText);
if (projectTemplate == null)
{
continue;
}
projectTemplate.FullPath = Path.GetDirectoryName(templateSettingFilePath);
_templates.Add(projectTemplate);
}
}
private string ReplaceContextVariables(string text)
{
StringBuilder stringBuilder = new StringBuilder(text);
stringBuilder.Replace("MyCompany.MyProduct", _settingsService.Settings.Context.Project.Name);
stringBuilder.Replace("MyCompany", _settingsService.Settings.Context.Project.CompanyName);
stringBuilder.Replace("myCompany", JsonNamingPolicy.CamelCase.ConvertName(_settingsService.Settings.Context.Project.CompanyName ?? string.Empty));
stringBuilder.Replace("MyProduct", _settingsService.Settings.Context.Project.ProductName);
stringBuilder.Replace("myProduct", JsonNamingPolicy.CamelCase.ConvertName(_settingsService.Settings.Context.Project.ProductName ?? string.Empty));
return stringBuilder.ToString();
}
} | 37.187919 | 164 | 0.669554 | [
"MIT"
] | steffbeckers/abp-generator | Templates/ProjectTemplatesService.cs | 5,541 | 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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CodeGen
{
/// <summary>
/// Some features of the compiler (such as anonymous types, pay-as-you-go, NoPIA, ...)
/// rely on all referenced symbols to go through translate mechanism. Because by default
/// symbol translator does not translate some of indirectly referenced symbols, such as
/// type argument, we have to force translation here
///
/// This class provides unified implementation for this functionality.
/// </summary>
internal static class ReferenceDependencyWalker
{
public static void VisitReference(Microsoft.Cci.IReference reference, Microsoft.CodeAnalysis.Emit.Context context)
{
var typeReference = reference as Microsoft.Cci.ITypeReference;
if (typeReference != null)
{
VisitTypeReference(typeReference, context);
return;
}
var methodReference = reference as Microsoft.Cci.IMethodReference;
if (methodReference != null)
{
VisitMethodReference(methodReference, context);
return;
}
var fieldReference = reference as Microsoft.Cci.IFieldReference;
if (fieldReference != null)
{
VisitFieldReference(fieldReference, context);
return;
}
}
private static void VisitTypeReference(Microsoft.Cci.ITypeReference typeReference, Microsoft.CodeAnalysis.Emit.Context context)
{
Debug.Assert(typeReference != null);
Microsoft.Cci.IArrayTypeReference arrayType = typeReference as Microsoft.Cci.IArrayTypeReference;
if (arrayType != null)
{
VisitTypeReference(arrayType.GetElementType(context), context);
return;
}
Microsoft.Cci.IPointerTypeReference pointerType = typeReference as Microsoft.Cci.IPointerTypeReference;
if (pointerType != null)
{
VisitTypeReference(pointerType.GetTargetType(context), context);
return;
}
Debug.Assert(!(typeReference is Microsoft.Cci.IManagedPointerTypeReference));
//Microsoft.Cci.IManagedPointerTypeReference managedPointerType = typeReference as Microsoft.Cci.IManagedPointerTypeReference;
//if (managedPointerType != null)
//{
// VisitTypeReference(managedPointerType.GetTargetType(this.context));
// return;
//}
Microsoft.Cci.IModifiedTypeReference modifiedType = typeReference as Microsoft.Cci.IModifiedTypeReference;
if (modifiedType != null)
{
foreach (var custModifier in modifiedType.CustomModifiers)
{
VisitTypeReference(custModifier.GetModifier(context), context);
}
VisitTypeReference(modifiedType.UnmodifiedType, context);
return;
}
// Visit containing type
Microsoft.Cci.INestedTypeReference nestedType = typeReference.AsNestedTypeReference;
if (nestedType != null)
{
VisitTypeReference(nestedType.GetContainingType(context), context);
}
// Visit generic arguments
Microsoft.Cci.IGenericTypeInstanceReference genericInstance = typeReference.AsGenericTypeInstanceReference;
if (genericInstance != null)
{
foreach (var arg in genericInstance.GetGenericArguments(context))
{
VisitTypeReference(arg, context);
}
}
}
private static void VisitMethodReference(Microsoft.Cci.IMethodReference methodReference, Microsoft.CodeAnalysis.Emit.Context context)
{
Debug.Assert(methodReference != null);
// Visit containing type
VisitTypeReference(methodReference.GetContainingType(context), context);
// Visit generic arguments if any
Microsoft.Cci.IGenericMethodInstanceReference genericInstance = methodReference.AsGenericMethodInstanceReference;
if (genericInstance != null)
{
foreach (var arg in genericInstance.GetGenericArguments(context))
{
VisitTypeReference(arg, context);
}
methodReference = genericInstance.GetGenericMethod(context);
}
// Translate substituted method to original definition
Microsoft.Cci.ISpecializedMethodReference specializedMethod = methodReference.AsSpecializedMethodReference;
if (specializedMethod != null)
{
methodReference = specializedMethod.UnspecializedVersion;
}
// Visit parameter types
VisitParameters(methodReference.GetParameters(context), context);
if (methodReference.AcceptsExtraArguments)
{
VisitParameters(methodReference.ExtraParameters, context);
}
// Visit return value type
VisitTypeReference(methodReference.GetType(context), context);
if (methodReference.ReturnValueIsModified)
{
foreach (var typeModifier in methodReference.ReturnValueCustomModifiers)
{
VisitTypeReference(typeModifier.GetModifier(context), context);
}
}
}
private static void VisitParameters(ImmutableArray<Microsoft.Cci.IParameterTypeInformation> parameters, Microsoft.CodeAnalysis.Emit.Context context)
{
foreach (var param in parameters)
{
VisitTypeReference(param.GetType(context), context);
if (param.IsModified)
{
foreach (var typeModifier in param.CustomModifiers)
{
VisitTypeReference(typeModifier.GetModifier(context), context);
}
}
}
}
private static void VisitFieldReference(Microsoft.Cci.IFieldReference fieldReference, Microsoft.CodeAnalysis.Emit.Context context)
{
Debug.Assert(fieldReference != null);
// Visit containing type
VisitTypeReference(fieldReference.GetContainingType(context), context);
// Translate substituted field to original definition
Microsoft.Cci.ISpecializedFieldReference specializedField = fieldReference.AsSpecializedFieldReference;
if (specializedField != null)
{
fieldReference = specializedField.UnspecializedVersion;
}
// Visit field type
VisitTypeReference(fieldReference.GetType(context), context);
}
}
}
| 40.549451 | 184 | 0.619783 | [
"Apache-2.0"
] | codemonkey85/roslyn | Src/Compilers/Core/Source/CodeGen/ReferenceDependencyWalker.cs | 7,382 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace PuppeteerSharp.Tests.OOPIFTests
{
[Collection("PuppeteerLoaderFixture collection")]
public class OOPIFTests : PuppeteerPageBaseTest
{
public OOPIFTests(ITestOutputHelper output) : base(output)
{
DefaultOptions = TestConstants.DefaultBrowserOptions();
DefaultOptions.Args = new[] { "--site-per-process" };
}
[Fact(Skip = "Skipped in puppeteer")]
public async Task ShouldReportOopifFrames()
{
await Page.GoToAsync(TestConstants.ServerUrl + "/dynamic-oopif.html");
Assert.Single(Oopifs);
Assert.Equal(2, Page.Frames.Length);
}
[Fact]
public async Task ShouldLoadOopifIframesWithSubresourcesAndRequestInterception()
{
await Page.SetRequestInterceptionAsync(true);
Page.Request += (sender, e) => _ = e.Request.ContinueAsync();
await Page.GoToAsync(TestConstants.ServerUrl + "/dynamic-oopif.html");
Assert.Single(Oopifs);
}
private IEnumerable<Target> Oopifs => Context.Targets().Where(target => target.TargetInfo.Type == TargetType.iFrame);
}
}
| 34.157895 | 125 | 0.651002 | [
"MIT"
] | R2D221/puppeteer-sharp | lib/PuppeteerSharp.Tests/OOPIFTests/OOPIFTests.cs | 1,300 | C# |
// Copyright (c) 2019 Lykke Corp.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using JetBrains.Annotations;
using Lykke.Job.CandlesProducer.Contract;
using Lykke.Job.CandlesHistoryWriter.Core.Domain.Candles;
using Lykke.Job.CandlesHistoryWriter.Core.Services.HistoryMigration;
namespace Lykke.Job.CandlesHistoryWriter.Services.HistoryMigration
{
[UsedImplicitly]
public class CandlesesHistoryMigrationService : ICandlesHistoryMigrationService
{
private readonly ICandlesHistoryRepository _candlesHistoryRepository;
public CandlesesHistoryMigrationService(ICandlesHistoryRepository candlesHistoryRepository)
{
_candlesHistoryRepository = candlesHistoryRepository;
}
public async Task<ICandle> GetFirstCandleOfHistoryAsync(string assetPair, CandlePriceType priceType)
{
var candle = await _candlesHistoryRepository.TryGetFirstCandleAsync(assetPair, CandleTimeInterval.Sec, priceType);
return candle;
}
}
}
| 35.9 | 126 | 0.763231 | [
"MIT-0"
] | LykkeBusiness/Lykke.Job.CandlesHistoryWriter | src/Lykke.Job.CandlesHistoryWriter.Services/HistoryMigration/CandlesMigrationService.cs | 1,079 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Limxc.Tools.Common
{
public class TaskFlow
{
private readonly Queue<TaskNode> _queue;
public TaskFlow(object inputs)
{
Inputs = inputs;
_queue = new Queue<TaskNode>();
Nodes = new List<TaskNode>();
History = new List<TaskNodeHistory>();
}
public object Inputs { get; set; }
public object Outputs { get; set; }
/// <summary>All Nodes</summary>
public List<TaskNode> Nodes { get; }
/// <summary>Execution History</summary>
public List<TaskNodeHistory> History { get; }
/// <summary>Waiting For Execution</summary>
public IEnumerable<TaskNode> PendingNodes => _queue.AsEnumerable();
private void BuildOnce()
{
if (Nodes.Count > 0 && History.Count == 0 && _queue.Count == 0)
Build();
}
/// <summary>Build Nodes</summary>
public void Build()
{
History.Clear();
_queue.Clear();
Nodes.ForEach(task => _queue.Enqueue(task));
}
/// <summary>Clear TaskFlow</summary>
public void Clear()
{
Nodes.Clear();
History.Clear();
_queue.Clear();
}
/// <summary>
/// Add Task
/// </summary>
/// <param name="task">Task Func</param>
/// <param name="retryCount">Execution times = RetryCount + 1</param>
/// <param name="id">Task Id</param>
public void Add(Func<object, CancellationToken, Task<object>> task, int retryCount = 0, string id = null)
{
Nodes.Add(new TaskNode(task, retryCount, id));
}
public Task Exec()
{
return Exec(CancellationToken.None);
}
public Task Exec(double timeoutSeconds)
{
return Exec(new CancellationTokenSource((int)(timeoutSeconds * 1000)).Token);
}
public async Task Exec(CancellationToken token)
{
BuildOnce();
while (_queue.Count > 0)
{
Outputs = null;
var item = _queue.Peek();
var remainingAttempts = 1 + (item.RetryCount < 0 ? 0 : item.RetryCount);
var pass = false;
string error = null;
while (!pass && remainingAttempts > 0)
try
{
error = null;
token.ThrowIfCancellationRequested();
remainingAttempts--;
Outputs = await item.Task(Inputs, token);
pass = true;
}
catch (OperationCanceledException)
{
error = "OperationCanceled";
throw;
}
catch (Exception ex)
{
error = $"Exception({ex.Message})";
pass = false;
if (remainingAttempts == 0)
throw;
}
finally
{
History.Add(new TaskNodeHistory(DateTime.Now, item.Id,
$"RemainingAttempts:{remainingAttempts} State:{(pass ? "Success" : error ?? "Exception")} Progress:{Nodes.Count - PendingNodes.Count() + 1}/{Nodes.Count}"
, Inputs, Outputs));
}
if (!pass)
return;
_queue.Dequeue();
if (_queue.Count > 0)
Inputs = Outputs;
}
}
/// <summary>
/// Combine TaskFlows
/// </summary>
/// <param name="queues"></param>
/// <returns></returns>
public TaskFlow Combine(params TaskFlow[] queues)
{
foreach (var queue in queues) Nodes.AddRange(queue.Nodes);
return this;
}
}
public class TaskNode
{
public TaskNode(Func<object, CancellationToken, Task<object>> task, int retryCount, string id)
{
Task = task;
RetryCount = retryCount;
Id = id;
}
public Func<object, CancellationToken, Task<object>> Task { get; }
/// <summary>
/// Execution times = RetryCount + 1
/// </summary>
public int RetryCount { get; }
public string Id { get; }
}
public class TaskNodeHistory
{
public TaskNodeHistory(DateTime execTime, string id, string message, object inputs, object outputs)
{
ExecTime = execTime;
Id = id;
Message = message;
Inputs = inputs;
Outputs = outputs;
}
public DateTime ExecTime { get; }
public string Id { get; }
public object Inputs { get; }
public object Outputs { get; }
public string Message { get; }
public override string ToString()
{
return $"@{ExecTime} {Id}: {Message}";
}
}
} | 29.622222 | 182 | 0.477494 | [
"MIT"
] | limxc/Limxc.Tools | src/Limxc.Tools/Common/TaskFlow.cs | 5,334 | C# |
using LtiLibrary.NetCore.Lis.v2;
using Microsoft.AspNetCore.Http;
namespace LtiLibrary.AspNetCore.Outcomes.v2
{
/// <summary>
/// Represents a GetLineItem DTO.
/// </summary>
public class GetLineItemDto
{
/// <summary>
/// Initialize a new instance of the class.
/// </summary>
public GetLineItemDto(string contextId, string id)
{
ContextId = contextId;
Id = id;
StatusCode = StatusCodes.Status200OK;
}
/// <summary>
/// Get or set the ContextId.
/// </summary>
public string ContextId { get; set; }
/// <summary>
/// Get or set the Id.
/// </summary>
public string Id { get; }
/// <summary>
/// Get or set the LineItem.
/// </summary>
public LineItem LineItem { get; set; }
/// <summary>
/// Get or set the HTTP StatusCode.
/// </summary>
public int StatusCode { get; set; }
}
}
| 24.333333 | 58 | 0.519569 | [
"Apache-2.0"
] | Copyleaks/LtiLibrary | src/LtiLibrary.AspNetCore/Outcomes/v2/GetLineItemDto.cs | 1,024 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SageMaker.Model
{
/// <summary>
/// A collection of settings used for an AutoML job.
/// </summary>
public partial class AutoMLJobConfig
{
private AutoMLJobCompletionCriteria _completionCriteria;
private AutoMLDataSplitConfig _dataSplitConfig;
private AutoMLSecurityConfig _securityConfig;
/// <summary>
/// Gets and sets the property CompletionCriteria.
/// <para>
/// How long an AutoML job is allowed to run, or how many candidates a job is allowed
/// to generate.
/// </para>
/// </summary>
public AutoMLJobCompletionCriteria CompletionCriteria
{
get { return this._completionCriteria; }
set { this._completionCriteria = value; }
}
// Check to see if CompletionCriteria property is set
internal bool IsSetCompletionCriteria()
{
return this._completionCriteria != null;
}
/// <summary>
/// Gets and sets the property DataSplitConfig.
/// <para>
/// The configuration for splitting the input training dataset.
/// </para>
///
/// <para>
/// Type: AutoMLDataSplitConfig
/// </para>
/// </summary>
public AutoMLDataSplitConfig DataSplitConfig
{
get { return this._dataSplitConfig; }
set { this._dataSplitConfig = value; }
}
// Check to see if DataSplitConfig property is set
internal bool IsSetDataSplitConfig()
{
return this._dataSplitConfig != null;
}
/// <summary>
/// Gets and sets the property SecurityConfig.
/// <para>
/// The security configuration for traffic encryption or Amazon VPC settings.
/// </para>
/// </summary>
public AutoMLSecurityConfig SecurityConfig
{
get { return this._securityConfig; }
set { this._securityConfig = value; }
}
// Check to see if SecurityConfig property is set
internal bool IsSetSecurityConfig()
{
return this._securityConfig != null;
}
}
} | 31.04 | 107 | 0.622423 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/SageMaker/Generated/Model/AutoMLJobConfig.cs | 3,104 | C# |
using System;
namespace _01.Recursive_Array_Sum
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 1, 2, 3 };
int sum = FindSum(arr, 0);
Console.WriteLine(sum);
}
static int FindSum(int[] arr, int index)
{
if(index == arr.Length)
{
return 0;
}
int currentNumber = arr[index];
return currentNumber + FindSum(arr, ++index);
}
}
}
| 19.62963 | 57 | 0.45283 | [
"MIT"
] | Aleksandyr/Algorithms | 01.Lab-Recursion/01.Recursive-Array-Sum/Program.cs | 532 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GlobalGeobits.ChatApp.web.ErrorsLog
{
public class LogFilterExceptions : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception == null) return;
File.AppendAllText(actionExecutedContext.HttpContext.Server.MapPath("~/Errors/logfilter.text"), "<EXP>" + Environment.NewLine + actionExecutedContext.Exception.ToString() + Environment.NewLine + "</EXP>" + Environment.NewLine);
}
}
} | 30.409091 | 239 | 0.729447 | [
"MIT"
] | hamed1m54/SignalR-RealTime-Chat-System | GlobalGeobits.ChatApp.web/ErrorsLog/LogFilterExceptions.cs | 671 | C# |
//-----------------------------------------------------------------------------
// (c) 2021 Ruzsinszki Gábor
// This code is licensed under MIT license (see LICENSE for details)
//-----------------------------------------------------------------------------
using System;
using System.Runtime.Serialization;
namespace ExpressionEngine.Renderer
{
public class CommandException : Exception
{
public CommandException()
{
}
public CommandException(string format, params string[] arguments) : base(string.Format(format, arguments))
{
}
public CommandException(string? message) : base(message)
{
}
public CommandException(string? message, Exception? innerException) : base(message, innerException)
{
}
protected CommandException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
| 26.942857 | 114 | 0.535525 | [
"MIT"
] | webmaster442/ExpressionEngine | ExpressionEngine.Renderer/CommandException.cs | 946 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace BasickStackOperation
{
class BasicStack
{
static void Main()
{
var stackInformation = Console.ReadLine()
.Split(' ')
.ToArray();
var numbersToPushInStack = int.Parse(stackInformation[0]);
var numbersToPopFromStack = int.Parse(stackInformation[1]);
var numbersToLookForInStack = int.Parse(stackInformation[2]);
var numbersToBeStacked = Console.ReadLine()
.Split(' ')
.Select(x => int.Parse(x))
.ToArray();
var stack = new Stack<int>();
for (int i = 0; i < numbersToPushInStack; i++)
{
stack.Push(numbersToBeStacked[i]);
}
for (int i = 0; i < numbersToPopFromStack; i++)
{
stack.Pop();
}
if (stack.Count==0)
{
Console.WriteLine(0);
return;
}
else
{
var minInStack = stack.Peek();
while (stack.Count>0)
{
var stackCurrentValue = stack.Pop();
if (stackCurrentValue== numbersToLookForInStack)
{
Console.WriteLine("true");
return;
}
if (stackCurrentValue< minInStack)
{
minInStack = stackCurrentValue;
}
}
Console.WriteLine(minInStack);
}
}
}
}
| 28.966102 | 73 | 0.434757 | [
"MIT"
] | LuGeorgiev/CSharpSelfLearning | SoftUniCSAdvanced/StackAndQueue/BasickStackOperation/BasicStack.cs | 1,711 | C# |
// Copyright (c) 2014 Daniel Grunwald
//
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Threading;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.IL
{
class BlockBuilder
{
readonly MethodBodyBlock body;
readonly Dictionary<ExceptionRegion, ILVariable> variableByExceptionHandler;
/// <summary>
/// Gets/Sets whether to create extended basic blocks instead of basic blocks.
/// The default is <c>false</c>.
/// </summary>
public bool CreateExtendedBlocks;
internal BlockBuilder(MethodBodyBlock body,
Dictionary<ExceptionRegion, ILVariable> variableByExceptionHandler)
{
Debug.Assert(body != null);
Debug.Assert(variableByExceptionHandler != null);
this.body = body;
this.variableByExceptionHandler = variableByExceptionHandler;
}
List<TryInstruction> tryInstructionList = new List<TryInstruction>();
Dictionary<int, BlockContainer> handlerContainers = new Dictionary<int, BlockContainer>();
void CreateContainerStructure()
{
List<TryCatch> tryCatchList = new List<TryCatch>();
foreach (var eh in body.ExceptionRegions) {
var tryRange = new Interval(eh.TryOffset, eh.TryOffset + eh.TryLength);
var handlerBlock = new BlockContainer();
handlerBlock.AddILRange(new Interval(eh.HandlerOffset, eh.HandlerOffset + eh.HandlerLength));
handlerBlock.Blocks.Add(new Block());
handlerContainers.Add(handlerBlock.StartILOffset, handlerBlock);
if (eh.Kind == ExceptionRegionKind.Fault || eh.Kind == ExceptionRegionKind.Finally) {
var tryBlock = new BlockContainer();
tryBlock.AddILRange(tryRange);
if (eh.Kind == ExceptionRegionKind.Finally)
tryInstructionList.Add(new TryFinally(tryBlock, handlerBlock).WithILRange(tryRange));
else
tryInstructionList.Add(new TryFault(tryBlock, handlerBlock).WithILRange(tryRange));
continue;
}
//
var tryCatch = tryCatchList.FirstOrDefault(tc => tc.TryBlock.ILRanges.SingleOrDefault() == tryRange);
if (tryCatch == null) {
var tryBlock = new BlockContainer();
tryBlock.AddILRange(tryRange);
tryCatch = new TryCatch(tryBlock);
tryCatch.AddILRange(tryRange);
tryCatchList.Add(tryCatch);
tryInstructionList.Add(tryCatch);
}
ILInstruction filter;
if (eh.Kind == System.Reflection.Metadata.ExceptionRegionKind.Filter) {
var filterBlock = new BlockContainer(expectedResultType: StackType.I4);
filterBlock.AddILRange(new Interval(eh.FilterOffset, eh.HandlerOffset));
filterBlock.Blocks.Add(new Block());
handlerContainers.Add(filterBlock.StartILOffset, filterBlock);
filter = filterBlock;
} else {
filter = new LdcI4(1);
}
var handler = new TryCatchHandler(filter, handlerBlock, variableByExceptionHandler[eh]);
handler.AddILRange(filter);
handler.AddILRange(handlerBlock);
tryCatch.Handlers.Add(handler);
tryCatch.AddILRange(handler);
}
if (tryInstructionList.Count > 0) {
tryInstructionList = tryInstructionList.OrderBy(tc => tc.TryBlock.StartILOffset).ThenByDescending(tc => tc.TryBlock.EndILOffset).ToList();
nextTry = tryInstructionList[0];
}
}
int currentTryIndex;
TryInstruction nextTry;
BlockContainer currentContainer;
Block currentBlock;
Stack<BlockContainer> containerStack = new Stack<BlockContainer>();
public void CreateBlocks(BlockContainer mainContainer, List<ILInstruction> instructions, BitArray incomingBranches, CancellationToken cancellationToken)
{
CreateContainerStructure();
mainContainer.SetILRange(new Interval(0, body.GetCodeSize()));
currentContainer = mainContainer;
if (instructions.Count == 0) {
currentContainer.Blocks.Add(new Block {
Instructions = {
new InvalidBranch("Empty body found. Decompiled assembly might be a reference assembly.")
}
});
return;
}
foreach (var inst in instructions) {
cancellationToken.ThrowIfCancellationRequested();
int start = inst.StartILOffset;
if (currentBlock == null || (incomingBranches[start] && !IsStackAdjustment(inst))) {
// Finish up the previous block
FinalizeCurrentBlock(start, fallthrough: true);
// Leave nested containers if necessary
while (start >= currentContainer.EndILOffset) {
currentContainer = containerStack.Pop();
currentBlock = currentContainer.Blocks.Last();
// this container is skipped (i.e. the loop will execute again)
// set ILRange to the last instruction offset inside the block.
if (start >= currentContainer.EndILOffset) {
Debug.Assert(currentBlock.HasILRange);
currentBlock.AddILRange(new Interval(currentBlock.StartILOffset, start));
}
}
// Enter a handler if necessary
BlockContainer handlerContainer;
if (handlerContainers.TryGetValue(start, out handlerContainer)) {
containerStack.Push(currentContainer);
currentContainer = handlerContainer;
currentBlock = handlerContainer.EntryPoint;
} else {
FinalizeCurrentBlock(start, fallthrough: false);
// Create the new block
currentBlock = new Block();
currentContainer.Blocks.Add(currentBlock);
}
currentBlock.SetILRange(new Interval(start, start));
}
while (nextTry != null && start == nextTry.TryBlock.StartILOffset) {
currentBlock.Instructions.Add(nextTry);
containerStack.Push(currentContainer);
currentContainer = (BlockContainer)nextTry.TryBlock;
currentBlock = new Block();
currentContainer.Blocks.Add(currentBlock);
currentBlock.SetILRange(new Interval(start, start));
nextTry = tryInstructionList.ElementAtOrDefault(++currentTryIndex);
}
currentBlock.Instructions.Add(inst);
if (inst.HasFlag(InstructionFlags.EndPointUnreachable))
FinalizeCurrentBlock(inst.EndILOffset, fallthrough: false);
else if (!CreateExtendedBlocks && inst.HasFlag(InstructionFlags.MayBranch))
FinalizeCurrentBlock(inst.EndILOffset, fallthrough: true);
}
FinalizeCurrentBlock(mainContainer.EndILOffset, fallthrough: false);
// Finish up all containers
while (containerStack.Count > 0) {
currentContainer = containerStack.Pop();
currentBlock = currentContainer.Blocks.Last();
FinalizeCurrentBlock(mainContainer.EndILOffset, fallthrough: false);
}
ConnectBranches(mainContainer, cancellationToken);
}
static bool IsStackAdjustment(ILInstruction inst)
{
return inst is StLoc stloc && stloc.IsStackAdjustment;
}
private void FinalizeCurrentBlock(int currentILOffset, bool fallthrough)
{
if (currentBlock == null)
return;
Debug.Assert(currentBlock.HasILRange);
currentBlock.SetILRange(new Interval(currentBlock.StartILOffset, currentILOffset));
if (fallthrough) {
if (currentBlock.Instructions.LastOrDefault() is SwitchInstruction switchInst && switchInst.Sections.Last().Body.MatchNop()) {
// Instead of putting the default branch after the switch instruction
switchInst.Sections.Last().Body = new Branch(currentILOffset);
Debug.Assert(switchInst.HasFlag(InstructionFlags.EndPointUnreachable));
} else {
currentBlock.Instructions.Add(new Branch(currentILOffset));
}
}
currentBlock = null;
}
void ConnectBranches(ILInstruction inst, CancellationToken cancellationToken)
{
switch (inst) {
case Branch branch:
cancellationToken.ThrowIfCancellationRequested();
Debug.Assert(branch.TargetBlock == null);
branch.TargetBlock = FindBranchTarget(branch.TargetILOffset);
if (branch.TargetBlock == null) {
branch.ReplaceWith(new InvalidBranch("Could not find block for branch target "
+ Disassembler.DisassemblerHelpers.OffsetToString(branch.TargetILOffset)).WithILRange(branch));
}
break;
case Leave leave:
// ret (in void method) = leave(mainContainer)
// endfinally = leave(null)
if (leave.TargetContainer == null) {
// assign the finally/filter container
leave.TargetContainer = containerStack.Peek();
leave.Value = ILReader.Cast(leave.Value, leave.TargetContainer.ExpectedResultType, null, leave.StartILOffset);
}
break;
case BlockContainer container:
containerStack.Push(container);
foreach (var block in container.Blocks) {
cancellationToken.ThrowIfCancellationRequested();
ConnectBranches(block, cancellationToken);
if (block.Instructions.Count == 0 || !block.Instructions.Last().HasFlag(InstructionFlags.EndPointUnreachable)) {
block.Instructions.Add(new InvalidBranch("Unexpected end of block"));
}
}
containerStack.Pop();
break;
default:
foreach (var child in inst.Children)
ConnectBranches(child, cancellationToken);
break;
}
}
Block FindBranchTarget(int targetILOffset)
{
foreach (var container in containerStack) {
foreach (var block in container.Blocks) {
if (block.StartILOffset == targetILOffset)
return block;
}
}
return null;
}
}
}
| 39.569767 | 154 | 0.727985 | [
"MIT"
] | 164306530/ILSpy | ICSharpCode.Decompiler/IL/BlockBuilder.cs | 10,211 | C# |
using System;
using System.Collections.Concurrent;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Gybs.Logic.Operations.ServiceProvider
{
/// <summary>
/// Represents a bus handling operation via handlers resolved from a service provider.
/// </summary>
public class ServiceProviderOperationBus : IOperationBus
{
private static readonly Type OperationHandlerType = typeof(IOperationHandler<>);
private static readonly Type DataOperationHandlerType = typeof(IOperationHandler<,>);
private static readonly ConcurrentDictionary<Type, (Type type, MethodInfo method)> HandlerDefinitions = new ConcurrentDictionary<Type, (Type, MethodInfo)>();
private readonly ILogger<ServiceProviderOperationBus> _logger;
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Creates an instance of the bus.
/// </summary>
/// <param name="logger">Logger.</param>
/// <param name="serviceProvider">Service provider used to resolve the handlers.</param>
public ServiceProviderOperationBus(
ILogger<ServiceProviderOperationBus> logger,
IServiceProvider serviceProvider)
{
_logger = logger;
_serviceProvider = serviceProvider;
}
/// <summary>
/// Handles the operation.
/// </summary>
/// <param name="operation">The operation to handle.</param>
/// <returns>The result.</returns>
public Task<IResult> HandleAsync(IOperation operation)
{
return (Task<IResult>)Handle(operation, OperationHandlerType, null);
}
/// <summary>
/// Handles the operation.
/// </summary>
/// <param name="operation">The operation to handle.</param>
/// <returns>The result with data.</returns>
public Task<IResult<TData>> HandleAsync<TData>(IOperation<TData> operation)
{
return (Task<IResult<TData>>)Handle(operation, DataOperationHandlerType, typeof(TData));
}
private object Handle(IOperationBase operation, Type operationHandlerType, Type? dataType)
{
var operationType = operation.GetType();
var operationHandlerDefinition = HandlerDefinitions.GetOrAdd(operationType, _ => CreateHandler(operationHandlerType, operationType, dataType));
var operationHandler = _serviceProvider.GetService(operationHandlerDefinition.type);
if (operationHandler is null) throw new InvalidOperationException($"No handler for operation of type {operationType.FullName}.");
_logger.LogDebug($"Invoking {operationHandler.GetType().FullName} for {operationType.FullName}.");
return operationHandlerDefinition.method.Invoke(operationHandler, new[] { operation });
}
private (Type, MethodInfo) CreateHandler(Type handlerType, Type operationType, Type? dataType)
{
var type = dataType is { }
? handlerType.MakeGenericType(operationType, dataType)
: handlerType.MakeGenericType(operationType);
_logger.LogDebug($"Generated handler {type.FullName} for {operationType.FullName}.");
return (type, type.GetMethod("HandleAsync"));
}
}
}
| 43.61039 | 165 | 0.666468 | [
"MIT"
] | wk0w/gybs | src/Gybs.Logic.Operations/ServiceProvider/ServiceProviderOperationBus.cs | 3,360 | C# |
using System;
namespace Teste
{
internal class Program
{
static void Main(string[] args)
{
/*
* Escreva um programa que imprima as estações do ano por escolhas de numericas
*/
int estacao = 2;
switch (estacao)
{
case 1:
Console.WriteLine("Primavera - De 23 de Setembro à 21 de Dezembro");
break;
case 2:
Console.WriteLine("Verão - De 21 de Dezembro à 21 de Março");
break;
case 3:
Console.WriteLine("Outono - De 21 de Março à 21 de Junho");
break;
case 4:
Console.WriteLine("Inverno - De 21 de Junho à 23 de Setembro ");
break;
default:
Console.WriteLine("Estação Invalida");
break;
}
Console.ReadLine();
}
}
}
| 26.410256 | 91 | 0.429126 | [
"MIT"
] | AleLucasG/Teste-de-Programa--o | teste5.cs | 1,043 | C# |
namespace WFCore.MultiTenancy
{
public static class MultiTenancyConsts
{
/* Enable/disable multi-tenancy easily in a single point.
* If you will never need to multi-tenancy, you can remove
* related modules and code parts, including this file.
*/
public const bool IsEnabled = true;
}
}
| 28.583333 | 66 | 0.64723 | [
"Apache-2.0"
] | amro93/WFCore | aspnet-core/src/WFCore.Domain.Shared/MultiTenancy/MultiTenancyConsts.cs | 345 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace JTfy
{
public class Vec<T> : DataArray<T>
{
public Int32 Count { get { return data.Length; } }
public override Int32 ByteCount { get { return 4 + base.ByteCount; } }
public override Byte[] Bytes
{
get
{
var bytesList = new List<Byte>(ByteCount);
bytesList.AddRange(StreamUtils.ToBytes(Count));
for (int i = 0; i < Count; ++i)
{
bytesList.AddRange(StreamUtils.ToBytes(data[i]));
}
return bytesList.ToArray();
}
}
public Vec(Stream stream)
{
data = new T[StreamUtils.ReadInt32(stream)];
for (int i = 0, c = data.Length; i < c; ++i)
{
data[i] = StreamUtils.Read<T>(stream);
}
}
public Vec(T[] data)
{
this.data = data;
}
}
public class VecI32 : Vec<Int32>
{
public VecI32(Stream stream) : base(stream) { }
public VecI32(int[] data) : base(data) { }
public VecI32() : this(new int[0]) { }
}
public class VecU32 : Vec<UInt32>
{
public VecU32(Stream stream) : base(stream) { }
public VecU32(uint[] data) : base(data) { }
public VecU32() : this(new uint[0]) { }
}
public class VecF32 : Vec<Single>
{
public VecF32(Stream stream) : base(stream) { }
public VecF32(float[] data) : base(data) { }
public VecF32() : this(new float[0]) { }
}
public class MbString : Vec<UInt16>
{
public string Value
{
get
{
/*var chars = new char[data.Length];
Buffer.BlockCopy(data, 0, chars, 0, chars.Length * 2);*/
var chars = data.Select(d => BitConverter.ToChar(BitConverter.GetBytes(d), 0)).ToArray();
return new String(chars);
}
}
public override string ToString()
{
return Value;
}
public MbString(Stream stream) : base(stream) { }
public MbString(UInt16[] data) : base(data) { }
public MbString() : base(new ushort[0]) { }
public MbString(string value)
: base(new UInt16[0])
{
var chars = value.ToCharArray();
/*data = new UInt16[chars.Length];
Buffer.BlockCopy(chars, 0, data, 0, data.Length * 2);*/
data = chars.Select(c => BitConverter.ToUInt16(BitConverter.GetBytes(c), 0)).ToArray();
}
}
} | 26.262136 | 105 | 0.500185 | [
"MIT"
] | MazvydasT/JSJT | CS2JSTest/JT File Data Model/Common Data Structures/Vec.cs | 2,707 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TA_Monde.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
| 19.230769 | 53 | 0.666 | [
"MIT"
] | FCrescent/ta_monde | TA_Monde/Pages/Index.cshtml.cs | 502 | C# |
using DependencyInjection.House;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DependencyInjection.Controllers
{
[ApiController]
[Route("[controller]")]
public class HouseController : ControllerBase
{
private readonly House.House house;
public HouseController(ILogger<HouseController> logger)
{
house = new House.House(
new House.ElectricityService(logger),
new House.WaterService(logger),
new House.InternetService(logger),
new House.CleaningService(logger),
new House.SanitationService(logger));
}
[HttpGet]
[Route("live")]
public IActionResult LiveInHouse()
{
house.LiveInHouse();
return Ok();
}
[HttpGet]
[Route("use")]
public IActionResult UseHouseService(HouseService service)
{
house.UseService(service);
return Ok();
}
}
}
| 26.022727 | 66 | 0.599127 | [
"Apache-2.0"
] | newteq/DevelopmentFundamentals | Practical/DependencyInjection/Controllers/HouseController.cs | 1,147 | C# |
using System.Threading.Tasks;
using Project.IntegrationTests.Configuration;
using Xunit;
namespace Project.IntegrationTests.Orders
{
public class FinishOrderTests
: IClassFixture<ApiWebApplicationFactory>
{
private readonly ApiWebApplicationFactory factory;
public FinishOrderTests(ApiWebApplicationFactory factory)
{
this.factory = factory;
}
[Fact]
public async Task Anonymous_user_cannot_finish_orders()
{
var client = factory.CreateAnonymous();
var response = await client.PostAsync("api/orders/123/finish", null);
response.EnsureUnauthenticated();
}
[Fact]
public async Task Client_user_cannot_finish_orders()
{
var client = factory.CreateClientUser();
var response = await client.PostAsync("api/orders/123/finish", null);
response.EnsureUnauthorized();
}
[Fact]
public async Task Admin_user_can_finish_orders()
{
var client = factory.CreateClientUser();
var order = await client.MakeSimpleOrderAndGetDetails();
var admin = factory.CreateAdminUser();
var response = await admin.PostAsync($"api/orders/{order.Id}/finish", null);
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task When_there_is_no_order_with_provided_id_Then_return_404_with_error_response()
{
var client = factory.CreateAdminUser();
var response = await client.PostAsync("api/orders/123/finish", null);
await response.EnsureNotFound();
}
[Fact]
public async Task When_finish_order_twice_Then_return_bad_request()
{
var client = factory.CreateClientUser();
var order = await client.MakeSimpleOrderAndGetDetails();
var admin = factory.CreateAdminUser();
await admin.PostAsync($"api/orders/{order.Id}/finish", null);
var response = await admin.PostAsync($"api/orders/{order.Id}/finish", null);
await response.EnsureBadRequest();
}
}
} | 30.082192 | 103 | 0.627049 | [
"MIT"
] | office-14/Drinks | web-api/src/Project.IntegrationTests/Orders/FinishOrderTests.cs | 2,196 | C# |
using DICOMcloud.DataAccess.Database.Schema;
using System;
using System.Collections.Generic;
using System.Linq;
using Dicom;
namespace DICOMcloud.DataAccess.Database
{
public partial class QueryResponseBuilder : IQueryResponseBuilder
{
private EntityReadData CurrentData = null ;
private KeyToDataSetCollection CurrentResultSet = null ;
private ResultSetCollection ResultSets = new ResultSetCollection ( ) ;
private string CurrentResultSetName = "" ;
public string QueryLevelTableName { get; set; }
public DbSchemaProvider SchemaProvider
{
get;
protected set;
}
public QueryResponseBuilder ( DbSchemaProvider schemaProvider, string queryLevel )
{
SchemaProvider = schemaProvider ;
QueryLevelTableName = schemaProvider.GetQueryTable ( queryLevel ) ;
}
public virtual void BeginResultSet( string name )
{
if ( !ResultSets.TryGetValue ( name, out CurrentResultSet ) )
{
CurrentResultSet = new KeyToDataSetCollection ( ) ;
}
CurrentResultSetName = name ;
}
public virtual void EndResultSet ( )
{
if ( !ResultSets.ContainsKey ( CurrentResultSetName ) )
{
ResultSets[CurrentResultSetName] = CurrentResultSet ;
}
}
public virtual void BeginRead( )
{
CurrentData = new EntityReadData ( ) ;
}
public virtual void EndRead ( )
{
if ( !string.IsNullOrEmpty (CurrentData.KeyValue))
{
UpdateDsPersonName ( ) ;
CurrentResultSet[CurrentData.KeyValue] = CurrentData.CurrentDs ;
}
CurrentData = null ;
}
public virtual bool ResultExists ( string table, object keyValue )
{
KeyToDataSetCollection resultSet ;
if ( ResultSets.TryGetValue ( table, out resultSet ) )
{
return resultSet.Contains ( keyValue.ToString ( ) ) ;
}
return false ;
}
public virtual void ReadData ( string tableName, string columnName, object value )
{
var column = SchemaProvider.GetColumn( tableName, columnName ) ;
var dicomTags = column.Tags ;
if ( IsDBNullValue ( value ))
{
return ;
}
if ( column.IsKey )
{
CurrentData.KeyValue = value.ToString ( ) ;
}
if ( column.IsForeign )
{
string keyString = value.ToString ( ) ;
KeyToDataSetCollection resultSet;
if ( ResultSets.TryGetValue ( column.Table.Parent, out resultSet ) )
{
DicomDataset foreignDs = (DicomDataset) resultSet[keyString] ;
if ( QueryLevelTableName == column.Table.Name )
{
foreignDs.Merge ( CurrentData.CurrentDs ) ;
//resultSet[keyString] = CurrentData.CurrentDs ;
}
else
{
if ( column.Table.IsSequence )
{
DicomSequence sq = (DicomSequence) CurrentData.ForeignDs.GetSequence (CurrentData.ForeignTagValue) ;
DicomDataset item = new DicomDataset ( ) { AutoValidate = false };
sq.Items.Add ( item ) ;
CurrentData.CurrentDs.Merge ( item ) ;
CurrentData.CurrentDs = item ;
}
else if ( column.Table.IsMultiValue )
{
CurrentData.CurrentDs = foreignDs ;
}
else
{
CurrentData.CurrentDs.Merge ( foreignDs ) ;
foreignDs.CopyTo ( CurrentData.CurrentDs ) ; //TODO: check if above merge is still necessary with this new CopyTo method
}
}
}
}
if (null == dicomTags) { return;}
ReadTags(columnName, value, dicomTags);
}
private void ReadTags(string columnName, object value, uint[] dicomTags)
{
foreach ( var dicomTag in dicomTags )
{
DicomDictionaryEntry dicEntry = DicomDictionary.Default[dicomTag];
var vr = dicEntry.ValueRepresentations.First() ;
Type valueType = value.GetType ( ) ;
if ( vr == DicomVR.PN )
{
PersonNameParts currentPart = SchemaProvider.GetPNColumnPart ( columnName ) ;
if ( CurrentData.CurrentPersonNameData == null )
{
CurrentData.CurrentPersonNameData = new PersonNameData ( ) ;
CurrentData.CurrentPersonNameTagValue = (uint) dicEntry.Tag ;
CurrentData.CurrentPersonNames.Add ( CurrentData.CurrentPersonNameTagValue , CurrentData.CurrentPersonNameData ) ;
}
else
{
if ( dicEntry.Tag != CurrentData.CurrentPersonNameTagValue )
{
if ( CurrentData.CurrentPersonNames.TryGetValue ( (uint)dicEntry.Tag, out CurrentData.CurrentPersonNameData ) )
{
CurrentData.CurrentPersonNameTagValue = (uint) dicEntry.Tag ;
}
else
{
CurrentData.CurrentPersonNameData = new PersonNameData ( ) ;
CurrentData.CurrentPersonNameTagValue = (uint) dicEntry.Tag ;
CurrentData.CurrentPersonNames.Add ( CurrentData.CurrentPersonNameTagValue , CurrentData.CurrentPersonNameData ) ;
}
}
}
CurrentData.CurrentPersonNameData.SetPart ( currentPart, (string) value ) ;
}
if (valueType == typeof(String)) //shortcut
{
CurrentData.CurrentDs.AddOrUpdate<string>(dicomTag, System.Text.Encoding.Default , (string) value);
}
else if (valueType == typeof(DateTime))
{
CurrentData.CurrentDs.AddOrUpdate<DateTime>(dicomTag, (DateTime) value);
}
else if (valueType == typeof(Int32))
{
DicomTag tag = (DicomTag) dicomTag;
var VR = tag.DictionaryEntry.ValueRepresentations.First();
// Unsigned String must be stored as Int in SQL DB
// https://social.msdn.microsoft.com/Forums/en-US/ff08c190-a981-4896-9542-3f64b95a84a2/sql-server-data-type-for-signedunsigned-integral-c-types?forum=adodotnetdataproviders
if (VR == DicomVR.US )
{
CurrentData.CurrentDs.AddOrUpdate<UInt16>(dicomTag, Convert.ToUInt16 (value));
}
else
{
CurrentData.CurrentDs.AddOrUpdate<Int32>(dicomTag, (Int32)value);
}
}
else if (valueType == typeof(Int64))
{
CurrentData.CurrentDs.AddOrUpdate<Int64>(dicomTag, (Int64)value);
}
else
{
CurrentData.CurrentDs.AddOrUpdate<string>(dicomTag, value as string);
System.Diagnostics.Debug.Assert(false, "Unknown element db value");
}
}
}
public virtual IEnumerable<DicomDataset> GetResponse ( )
{
return GetQueryResults (QueryLevelTableName);
}
public virtual IEnumerable<DicomDataset> GetResults (string queryLevel)
{
var queryLevelTableName = SchemaProvider.GetQueryTable(queryLevel);
return GetQueryResults (queryLevelTableName);
}
private IEnumerable<DicomDataset> GetQueryResults (string queryLevelTableName)
{
if ( !ResultSets.ContainsKey (queryLevelTableName) )
{
return new KeyToDataSetCollection ( ).Values.OfType<DicomDataset>() ;
}
return ResultSets[queryLevelTableName].Values.OfType<DicomDataset>() ;
}
private void UpdateDsPersonName()
{
if (null != CurrentData.CurrentPersonNames)
{
foreach (var personName in CurrentData.CurrentPersonNames)
{
CurrentData.CurrentDs.AddOrUpdate( personName.Key,System.Text.Encoding.Default , personName.Value.ToString());
}
}
CurrentData.CurrentPersonNames.Clear();
CurrentData.CurrentPersonNames = new Dictionary<uint, PersonNameData>();
CurrentData.CurrentPersonNameData = null ;
}
private bool IsDBNullValue ( object value )
{
return DBNull.Value == value || value == null ;
}
}
}
| 37.236641 | 192 | 0.504203 | [
"Apache-2.0"
] | 3833430/DICOMcloud | DICOMcloud.DataAccess.Database/QueryResponseBuilder/QueryResponseBuilder.cs | 9,758 | 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("TestProject1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestProject1")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("73340be7-9af4-4962-af8f-68fcc33fd9da")]
// 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.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.694444 | 84 | 0.74871 | [
"MIT"
] | DovetailSoftware/Amazing-Cloud-Search | AmazingCloudSearch.Test/Properties/AssemblyInfo.cs | 1,360 | C# |
using System;
using System.Collections.Generic;
using WebbShopEmil.Models;
using WebbShopFE.Helper;
namespace WebbShopFE.Views
{
/// <summary>
/// Methods that prints out info concerning books.
/// </summary>
public static class BookView
{
/// <summary>
/// Prints out earned money.
/// </summary>
/// <param name="money"></param>
public static void DisplayMoney(int money)
{
Console.WriteLine($"Earned money: {money}");
}
/// <summary>
/// Prints out new book amount.
/// </summary>
/// <param name="amount"></param>
public static void NewAmount(int amount)
{
HelpMethods.GreenTextWL($"New book amount is: {amount}");
}
/// <summary>
/// Takes in a list of books
/// and prints out info about books in list.
/// </summary>
/// <param name="books"></param>
public static void ShowBooks(List<Book> books)
{
foreach (var book in books)
{
Console.WriteLine(
$"(Id: {book.Id}.)" +
$" (Title: {book.Title})" +
$" (Author: {book.Author})" +
$" (Price: {book.Price})" +
$" (Amount: {book.Amount})"
);
}
}
/// <summary>
/// Takes in a list of sold books
/// and prints out the titles of sold books.
/// </summary>
/// <param name="soldItems"></param>
public static void ShowSoldItems(List<SoldBook> soldItems)
{
foreach (var sold in soldItems)
{
Console.WriteLine($"Title: {sold.Title}");
}
}
}
} | 28.539683 | 69 | 0.480534 | [
"MIT"
] | marcusjobb/NET20D | OOPA/WebbshopProjekt/Emil/WebbShopFE/WebbShopFE/Views/BookView.cs | 1,800 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Model\MethodRequestBody.cs.tt
namespace Microsoft.Graph
{
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
/// <summary>
/// The type DeviceManagementIntentAssignRequestBody.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class DeviceManagementIntentAssignRequestBody
{
/// <summary>
/// Gets or sets Assignments.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "assignments", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<DeviceManagementIntentAssignment> Assignments { get; set; }
}
}
| 37.242424 | 153 | 0.616762 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Models/Generated/DeviceManagementIntentAssignRequestBody.cs | 1,229 | C# |
using System;
using System.Reflection;
using AmplaData.Binding.MetaData;
namespace AmplaData.Binding.ModelData
{
public static class Property<TModel>
{
public static T GetValue<T>(TModel model, string property)
{
if (!string.IsNullOrEmpty(property))
{
PropertyInfo propertyInfo;
if (ReflectionHelper.TryGetPropertyByName(model.GetType(), property, StringComparison.CurrentCulture, out propertyInfo))
{
return (T)propertyInfo.GetValue(model, null);
}
}
return default(T);
}
public static void SetValue<T>(TModel model, string property, T value)
{
if (!string.IsNullOrEmpty(property))
{
PropertyInfo propertyInfo;
if (ReflectionHelper.TryGetPropertyByName(model.GetType(), property, StringComparison.CurrentCulture, out propertyInfo))
{
propertyInfo.SetValue(model, value, null);
}
}
}
}
} | 31.514286 | 136 | 0.566636 | [
"MIT"
] | Ampla/Ampla-Data | src/AmplaData/Binding/ModelData/Property.cs | 1,105 | C# |
using System;
using Newtonsoft.Json;
namespace API_Football.SDK.Models
{
public class Season
{
[JsonProperty("year")]
public ushort Year { get; set; }
[JsonProperty("start")]
public DateTime? Start { get; set; }
[JsonProperty("end")]
public DateTime? End { get; set; }
[JsonProperty("current")]
public bool Current { get; set; }
[JsonProperty("coverage")]
public Coverage Coverage { get; set; }
}
} | 23.130435 | 46 | 0.535714 | [
"MIT"
] | fabricatorsltd/api-sports | src/API-Football.SDK/Models/Season.cs | 534 | C# |
using System;
using System.IO;
using System.Collections.Generic;
namespace Crash
{
public class OldFrame
{
public static OldFrame Load(byte[] data)
{
if (data == null)
throw new ArgumentNullException("data");
if (data.Length < 56)
{
ErrorManager.SignalError("OldFrame: Data is too short");
}
int vertexcount = BitConv.FromInt32(data,0);
if (vertexcount < 0 || vertexcount > Chunk.Length / 6)
{
ErrorManager.SignalError("OldFrame: Vertex count is invalid");
}
if (data.Length < 56 + vertexcount * 6 + 2)
{
ErrorManager.SignalError("OldFrame: Data is too short");
}
int modeleid = BitConv.FromInt32(data,4);
int xoffset = BitConv.FromInt32(data,8);
int yoffset = BitConv.FromInt32(data,12);
int zoffset = BitConv.FromInt32(data,16);
int x1 = BitConv.FromInt32(data,20);
int y1 = BitConv.FromInt32(data,24);
int z1 = BitConv.FromInt32(data,28);
int x2 = BitConv.FromInt32(data,32);
int y2 = BitConv.FromInt32(data,36);
int z2 = BitConv.FromInt32(data,40);
int xglobal = BitConv.FromInt32(data,44);
int yglobal = BitConv.FromInt32(data,48);
int zglobal = BitConv.FromInt32(data,52);
OldFrameVertex[] vertices = new OldFrameVertex [vertexcount];
for (int i = 0;i < vertexcount;i++)
{
vertices[i] = new OldFrameVertex(data[56+i*6+0],data[56+i*6+1],data[56+i*6+2],data[56+i*6+3],data[56+i*6+4],data[56+i*6+5]);
}
short unknown = BitConv.FromInt16(data,56 + vertexcount * 6);
short? unknown2 = null;
if (data.Length >= 56 + vertexcount * 6 + 4)
{
unknown2 = BitConv.FromInt16(data,58 + vertexcount * 6);
}
return new OldFrame(modeleid,xoffset,yoffset,zoffset,x1,y1,z1,x2,y2,z2,xglobal,yglobal,zglobal,vertices,unknown,unknown2);
}
private List<OldFrameVertex> vertices;
public OldFrame(int modeleid,int xoffset,int yoffset,int zoffset,int x1,int y1,int z1,int x2,int y2,int z2,int xglobal,int yglobal,int zglobal,IEnumerable<OldFrameVertex> vertices,short unknown,short? unknown2)
{
this.vertices = new List<OldFrameVertex>(vertices);
ModelEID = modeleid;
XOffset = xoffset;
YOffset = yoffset;
ZOffset = zoffset;
X1 = x1;
Y1 = y1;
Z1 = z1;
X2 = x2;
Y2 = y2;
Z2 = z2;
XGlobal = xglobal;
YGlobal = yglobal;
ZGlobal = zglobal;
Unknown = unknown;
Unknown2 = unknown2;
}
public int ModelEID { get; }
public int XOffset { get; set; }
public int YOffset { get; set; }
public int ZOffset { get; set; }
public int X1 { get; set; }
public int Y1 { get; set; }
public int Z1 { get; set; }
public int X2 { get; set; }
public int Y2 { get; set; }
public int Z2 { get; set; }
public int XGlobal { get; set; }
public int YGlobal { get; set; }
public int ZGlobal { get; set; }
public IList<OldFrameVertex> Vertices => vertices;
public short Unknown { get; set; }
public short? Unknown2 { get; set; }
public byte[] Save()
{
byte[] data = new byte [56 + vertices.Count * 6 + 2 + (Unknown2.HasValue? 2:0)];
BitConv.ToInt32(data,0,vertices.Count);
BitConv.ToInt32(data,4,ModelEID);
BitConv.ToInt32(data,8,XOffset);
BitConv.ToInt32(data,12,YOffset);
BitConv.ToInt32(data,16,ZOffset);
BitConv.ToInt32(data,20,X1);
BitConv.ToInt32(data,24,Y1);
BitConv.ToInt32(data,28,Z1);
BitConv.ToInt32(data,32,X2);
BitConv.ToInt32(data,36,Y2);
BitConv.ToInt32(data,40,Z2);
BitConv.ToInt32(data,44,XGlobal);
BitConv.ToInt32(data,48,YGlobal);
BitConv.ToInt32(data,52,ZGlobal);
for (int i = 0;i < vertices.Count;i++)
{
vertices[i].Save().CopyTo(data,56 + i * 6);
}
BitConv.ToInt16(data,56 + vertices.Count * 6,Unknown);
if (Unknown2.HasValue)
{
BitConv.ToInt16(data,58 + vertices.Count * 6,Unknown2.Value);
}
return data;
}
public byte[] ToOBJ(OldModelEntry model)
{
long xorigin = 0;
long yorigin = 0;
long zorigin = 0;
//foreach (OldFrameVertex vertex in vertices)
//{
// xorigin += vertex.X;
// yorigin += vertex.Y;
// zorigin += vertex.Z;
//}
//xorigin /= vertices.Count;
//yorigin /= vertices.Count;
//zorigin /= vertices.Count;
xorigin -= XOffset;
yorigin -= YOffset;
zorigin -= ZOffset;
using (MemoryStream stream = new MemoryStream())
{
using (StreamWriter obj = new StreamWriter(stream))
{
obj.WriteLine("# Vertices");
foreach (OldFrameVertex vertex in vertices)
{
obj.WriteLine("v {0} {1} {2}",vertex.X - xorigin,vertex.Y - yorigin,vertex.Z - zorigin);
}
obj.WriteLine();
obj.WriteLine("# Polygons");
foreach (OldModelPolygon polygon in model.Polygons)
{
obj.WriteLine("f {0} {1} {2}",polygon.VertexA / 6 + 1,polygon.VertexB / 6 + 1,polygon.VertexC / 6 + 1);
}
}
return stream.ToArray();
}
}
}
}
| 39.080745 | 219 | 0.495073 | [
"MIT",
"BSD-3-Clause"
] | wurlyfox/CrashEdit | Crash/Formats/Crash Formats/Animation/OldFrame.cs | 6,292 | C# |
// ***********************************************************************
// <copyright file="MatterProvisionHelper.cs" company="Microsoft">
// Copyright (c) . All rights reserved.
// </copyright>
// <summary>This file provides meta data related information for matter provision.</summary>
// ***********************************************************************
// Assembly : Microsoft.Legal.MatterCenter.CreateSampleData
// Author : MAQ Software
// Created : 04-27-2015
//
// ***********************************************************************
namespace Microsoft.Legal.MatterCenter.CreateSampleData
{
#region using
using Microsoft.SharePoint.Client;
using SharePoint.Client.WebParts;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
#endregion
/// <summary>
/// This class provides meta data related information for matter provision.
/// </summary>
public static class MatterProvisionHelper
{
/// <summary>
/// Creates the OneNote.
/// </summary>
/// <param name="clientContext">The client context.</param>
/// <param name="clientUrl">The client URL.</param>
/// <param name="matter">Matter object containing Matter data</param>
/// <returns>Returns the URL of the OneNote</returns>
internal static string CreateOneNote(ClientContext clientContext, Uri clientUrl, Matter matter)
{
string returnValue = string.Empty;
try
{
byte[] oneNoteFile = System.IO.File.ReadAllBytes("./Open Notebook.onetoc2");
Microsoft.SharePoint.Client.Web web = clientContext.Web;
Microsoft.SharePoint.Client.File file = web.GetFolderByServerRelativeUrl(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", clientUrl.AbsolutePath, Constants.Backslash, matter.MatterGuid + ConfigurationManager.AppSettings["OneNoteLibrarySuffix"], Constants.Backslash, matter.MatterGuid)).Files.Add(new FileCreationInformation()
{
Url = string.Format(CultureInfo.InvariantCulture, "{0}{1}", matter.MatterGuid, ConfigurationManager.AppSettings["ExtensionOneNoteTableOfContent"]),
Overwrite = true,
ContentStream = new MemoryStream(oneNoteFile)
});
web.Update();
clientContext.Load(file);
clientContext.ExecuteQuery();
ListItem oneNote = file.ListItemAllFields;
oneNote["Title"] = matter.MatterName;
oneNote.Update();
returnValue = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}{5}{6}", clientUrl.Scheme, Constants.COLON, Constants.Backslash, Constants.Backslash, clientUrl.Authority, file.ServerRelativeUrl, "?Web=1");
}
catch (Exception exception)
{
Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + "Matter name: " + matter.MatterName + "\n" + exception.Message + "\nStacktrace: " + exception.StackTrace);
throw;
}
return returnValue;
}
/// <summary>
/// Deletes Matter if exception occur post creation
/// </summary>
/// <param name="clientContext">Client context object for SharePoint</param>
/// <param name="matter">Matter object containing Matter data</param>
internal static void DeleteMatter(ClientContext clientContext, Matter matter)
{
//Delete matter library
DeleteMatterObject(clientContext, matter.MatterName, true);
//Delete Task List
DeleteMatterObject(clientContext, matter.MatterName + ConfigurationManager.AppSettings["TaskListSuffix"], true);
//Delete OneNote library
DeleteMatterObject(clientContext, matter.MatterName + ConfigurationManager.AppSettings["OneNoteLibrarySuffix"], true);
//Delete Calendar list
DeleteMatterObject(clientContext, matter.MatterName + ConfigurationManager.AppSettings["CalendarNameSuffix"], true);
//Delete Matter landing page
DeleteMatterObject(clientContext, matter.MatterGuid, false);
Console.WriteLine(ConfigurationManager.AppSettings["dashedLine"]);
}
/// <summary>
/// Creates Matter Landing Page on matter creation
/// </summary>
/// <param name="clientContext">Client Context</param>
/// <param name="client">Client object containing Client data</param>
/// <param name="matter">Matter object containing Matter data</param>
/// <returns>true if success else false</returns>
internal static string CreateMatterLandingPage(ClientContext clientContext, Client client, Matter matter)
{
string response = string.Empty;
if (null != clientContext && null != client && null != matter)
{
try
{
using (clientContext)
{
Uri uri = new Uri(client.ClientUrl);
Web web = clientContext.Web;
FileCreationInformation objFileInfo = new FileCreationInformation();
List sitePageLib = null;
//// Create Matter Landing Web Part Page
objFileInfo.Url = string.Format(CultureInfo.InvariantCulture, "{0}{1}", matter.MatterGuid, Constants.AspxExtension);
response = CreateWebPartPage(sitePageLib, clientContext, objFileInfo, matter, web);
if (Constants.TRUE == response)
{
//// Configure All Web Parts
string[] webParts = ConfigureXMLCodeOfWebParts(client, matter, clientContext, sitePageLib, objFileInfo, uri, web);
Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", uri.AbsolutePath, Constants.Backslash, ConfigurationManager.AppSettings["MatterLandingPageRepository"].Replace(Constants.SPACE, string.Empty), Constants.Backslash, objFileInfo.Url));
clientContext.Load(file);
clientContext.ExecuteQuery();
LimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
WebPartDefinition webPartDefinition = null;
string[] zones = { Constants.HeaderZone, Constants.TopZone, Constants.RightZone, Constants.TopZone, Constants.RightZone, Constants.RightZone, Constants.FooterZone, Constants.RightZone, Constants.RightZone };
AddWebPart(clientContext, limitedWebPartManager, webPartDefinition, webParts, zones);
}
else
{
response = Constants.FALSE;
}
}
}
catch (Exception ex)
{
////Generic Exception
Utility.DisplayAndLogError(Utility.ErrorFilePath, string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["ErrorMessage"], "creating Matter Landing page"));
Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + ex.Message + "\nStacktrace: " + ex.StackTrace);
throw;
}
return response;
}
else
{
return string.Format(CultureInfo.InvariantCulture, Constants.ServiceResponse, string.Empty, Constants.MessageNoInputs);
}
}
/// <summary>
/// Adding All Web Parts on Matter Landing Page
/// </summary>
/// <param name="clientContext">SharePoint Client Context</param>
/// <param name="limitedWebPartManager">LimitedWebPartManager object to import web parts</param>
/// <param name="webPartDefinition">WebPartDefinition object to add web parts on page.</param>
/// <param name="webParts">Array of web parts that should be added on Matter Landing Page</param>
/// <param name="zones">Array of Zone IDs</param>
/// <returns>true if success else false</returns>
internal static string AddWebPart(ClientContext clientContext, LimitedWebPartManager limitedWebPartManager, WebPartDefinition webPartDefinition, string[] webParts, string[] zones)
{
int index = 0;
int ZoneIndex = 1;
for (index = 0; index < webParts.Length; index++)
{
if (!string.IsNullOrWhiteSpace(webParts[index]))
{
webPartDefinition = limitedWebPartManager.ImportWebPart(webParts[index]);
limitedWebPartManager.AddWebPart(webPartDefinition.WebPart, zones[index], ZoneIndex);
clientContext.ExecuteQuery();
}
}
return Constants.TRUE;
}
/// <summary>
/// Configure XML Code of List View Web Part
/// </summary>
/// <param name="sitePageLib">SharePoint List of matter library</param>
/// <param name="clientContext">SharePoint Client Context</param>
/// <param name="objFileInfo">Object of FileCreationInformation</param>
/// <param name="client">Client object containing Client data</param>
/// <param name="matter">Matter object containing Matter data</param>
/// <param name="titleUrl">Segment of URL</param>
/// <returns>Configured ListView Web Part</returns>
internal static string ConfigureListViewWebPart(List sitePageLib, ClientContext clientContext, FileCreationInformation objFileInfo, Client client, Matter matter, string titleUrl)
{
string listViewWebPart = Constants.ListviewWebpart;
Uri uri = new Uri(client.ClientUrl);
ViewCollection viewColl = sitePageLib.Views;
clientContext.Load(
viewColl,
views => views.Include(
view => view.Title,
view => view.Id));
clientContext.ExecuteQuery();
string viewName = string.Empty;
foreach (View view in viewColl)
{
viewName = view.Id.ToString();
break;
}
viewName = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", Constants.OpeningCurlyBrace, viewName, Constants.ClosingCurlyBrace);
listViewWebPart = string.Format(CultureInfo.InvariantCulture, listViewWebPart, sitePageLib.Id.ToString(), titleUrl, string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", Constants.OpeningCurlyBrace, sitePageLib.Id.ToString(), Constants.ClosingCurlyBrace), viewName, string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", uri.AbsolutePath, Constants.Backslash, matter.MatterName, Constants.Backslash, objFileInfo.Url));
return listViewWebPart;
}
/// <summary>
/// Function is used to Configure XML of web parts
/// </summary>
/// <param name="client">Client object containing Client data</param>
/// <param name="matter">Matter object containing Matter data</param>
/// <param name="clientContext">SharePoint Client Context</param>
/// <param name="sitePageLib">SharePoint List of matter library</param>
/// <param name="objFileInfo">Object of FileCreationInformation</param>
/// <param name="uri">To get URL segments</param>
/// <param name="web">Web object of the current context</param>
/// <returns>List of Web Parts</returns>
internal static string[] ConfigureXMLCodeOfWebParts(Client client, Matter matter, ClientContext clientContext, List sitePageLib, FileCreationInformation objFileInfo, Uri uri, Web web)
{
string[] result = null;
try
{
sitePageLib = web.Lists.GetByTitle(matter.MatterName);
clientContext.Load(sitePageLib);
clientContext.ExecuteQuery();
////Configure list View Web Part XML
string listViewWebPart = ConfigureListViewWebPart(sitePageLib, clientContext, objFileInfo, client, matter, string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", uri.AbsolutePath, Constants.Backslash, matter.MatterName, Constants.Backslash, objFileInfo.Url));
string[] contentEditorSectionIds = ConfigurationManager.AppSettings["MatterLandingPageSections"].Split(',');
////Configure content Editor Web Part of user information XML
string contentEditorWebPartTasks = string.Empty;
if (Convert.ToBoolean(ConfigurationManager.AppSettings["TaskListCreationEnabled"], CultureInfo.InvariantCulture))
{
contentEditorWebPartTasks = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.TaskPanel, CultureInfo.InvariantCulture)]));
}
string calendarWebpart = string.Empty, rssFeedWebPart = string.Empty, rssTitleWebPart = string.Empty;
if (Convert.ToBoolean(ConfigurationManager.AppSettings["TaskListCreationEnabled"], CultureInfo.InvariantCulture))
{
rssFeedWebPart = string.Format(CultureInfo.InvariantCulture, Constants.RssFeedWebpart, HttpUtility.UrlEncode(matter.MatterName));
rssTitleWebPart = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.RSSTitlePanel, CultureInfo.InvariantCulture)]));
}
////Configure calendar Web Part XML
if (Convert.ToBoolean(ConfigurationManager.AppSettings["TaskListCreationEnabled"], CultureInfo.InvariantCulture))
{
////If create calendar is enabled configure calendar Web Part XML; else don't configure
calendarWebpart = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.CalendarPanel, CultureInfo.InvariantCulture)]));
}
string matterInformationSection = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.InformationPanel, CultureInfo.InvariantCulture)]));
string cssLink = string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["MatterLandingCSSFileName"], ConfigurationManager.AppSettings["MatterLandingFolderName"]);
string cssLinkCommon = string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["CommonCSSFileName"], ConfigurationManager.AppSettings["CommonFolderName"]);
string jsLinkMatterLandingPage = string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["MatterLandingJSFileName"], ConfigurationManager.AppSettings["MatterLandingFolderName"]);
string jsLinkJQuery = string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["JQueryFileName"], ConfigurationManager.AppSettings["CommonFolderName"]);
string jsCommonLink = string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["CommonJSFileName"], ConfigurationManager.AppSettings["CommonFolderName"]);
string headerWebPartSection = string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.HeaderPanel, CultureInfo.InvariantCulture)]);
string footerWebPartSection = string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.FooterPanel, CultureInfo.InvariantCulture)]);
headerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, Constants.StyleTag, cssLink), headerWebPartSection);
headerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, Constants.StyleTag, cssLinkCommon), headerWebPartSection);
headerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, Constants.ScriptTagWithContents, string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingStampProperties, matter.MatterName, matter.MatterGuid)), headerWebPartSection);
footerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, Constants.ScriptTag, jsLinkMatterLandingPage), footerWebPartSection);
footerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, Constants.ScriptTag, jsCommonLink), footerWebPartSection);
footerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, Constants.ScriptTag, jsLinkJQuery), footerWebPartSection);
string headerWebPart = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, headerWebPartSection);
string footerWebPart = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, footerWebPartSection);
string oneNoteWebPart = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.OneNotePanel, CultureInfo.InvariantCulture)]));
string[] webParts = { headerWebPart, matterInformationSection, oneNoteWebPart, listViewWebPart, rssFeedWebPart, rssTitleWebPart, footerWebPart, calendarWebpart, contentEditorWebPartTasks };
result = webParts;
}
catch (Exception exception)
{
MatterProvisionHelper.DeleteMatter(clientContext, matter);
Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
}
return result;
}
/// <summary>
/// Breaks, assigns user permission and create Web Parts layout in Matter Landing Page
/// </summary>
/// <param name="sitePageLib">SharePoint List of matter library</param>
/// <param name="clientContext">SharePoint Client Context</param>
/// <param name="objFileInfo">Object of FileCreationInformation</param>
/// <param name="matter">Matter object containing Matter data</param>
/// <param name="web">Web object containing Web data</param>
/// <param name="collection">ListItemCollection object consist of items in Master Page Library</param>
/// <returns>true or exception value</returns>
internal static string WebPartsCreation(List sitePageLib, ClientContext clientContext, FileCreationInformation objFileInfo, Matter matter, Web web, ListItemCollection collection)
{
ListItem fileName = null;
foreach (ListItem findLayout in collection)
{
if (findLayout.DisplayName.Equals(Constants.DefaultLayout, StringComparison.OrdinalIgnoreCase))
{
fileName = findLayout;
break;
}
}
Microsoft.SharePoint.Client.File fileLayout = fileName.File;
clientContext.Load(fileLayout);
clientContext.ExecuteQuery();
ClientResult<Stream> filedata = fileLayout.OpenBinaryStream();
sitePageLib = web.Lists.GetByTitle(ConfigurationManager.AppSettings["MatterLandingPageRepository"]);
clientContext.Load(sitePageLib);
clientContext.ExecuteQuery();
StreamReader reader = new StreamReader(filedata.Value);
objFileInfo.Content = System.Text.Encoding.ASCII.GetBytes(reader.ReadToEnd());
int matterLandingPageId = AddMatterLandingPageFile(sitePageLib, clientContext, objFileInfo, matter.MatterName);
BreakItemPermission(clientContext, ConfigurationManager.AppSettings["MatterLandingPageRepository"], matter.CopyPermissionsFromParent, matterLandingPageId);
List<string> responsibleAttorneyList = matter.TeamInfo.ResponsibleAttorneys.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
List<string> attorneyList = matter.TeamInfo.Attorneys.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
List<string> blockedUserList = matter.TeamInfo.BlockedUploadUsers.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
if (0 < responsibleAttorneyList.Count)
{
AssignUserPermissionsToItem(clientContext, ConfigurationManager.AppSettings["MatterLandingPageRepository"], responsibleAttorneyList, ConfigurationManager.AppSettings["FullControl"], matterLandingPageId);
}
if (0 < attorneyList.Count)
{
AssignUserPermissionsToItem(clientContext, ConfigurationManager.AppSettings["MatterLandingPageRepository"], attorneyList, ConfigurationManager.AppSettings["Contribute"], matterLandingPageId);
}
if (0 < blockedUserList.Count)
{
AssignUserPermissionsToItem(clientContext, ConfigurationManager.AppSettings["MatterLandingPageRepository"], blockedUserList, ConfigurationManager.AppSettings["Read"], matterLandingPageId);
}
return Constants.TRUE;
}
/// <summary>
/// Adds the matter landing page to the site pages library of client site collection and returns the unique list item Id.
/// </summary>
/// <param name="sitePageLib">Site pages library</param>
/// <param name="clientContext">Client context object</param>
/// <param name="objFileInfo">Matter landing page file</param>
/// <param name="matterName">Name of the Matter</param>
/// <returns>Unique list item id from site pages library for the matter landing page file uploaded.</returns>
internal static int AddMatterLandingPageFile(List sitePageLib, ClientContext clientContext, FileCreationInformation objFileInfo, string matterName)
{
Microsoft.SharePoint.Client.File matterLandingPage = sitePageLib.RootFolder.Files.Add(objFileInfo);
ListItem matterLandingPageDetails = matterLandingPage.ListItemAllFields;
matterLandingPageDetails["Title"] = matterName;
matterLandingPageDetails.Update();
clientContext.Load(matterLandingPageDetails, matterLandingPageProperties => matterLandingPageProperties.Id);
clientContext.ExecuteQuery();
return matterLandingPageDetails.Id;
}
/// <summary>
/// Assigns permissions to users on the specified list item.
/// </summary>
/// <param name="clientcontext">Client context object</param>
/// <param name="listName">Site pages library</param>
/// <param name="users">List of users</param>
/// <param name="permission">Permission to grant</param>
/// <param name="listItemId">Unique list item Id for permissions assignment</param>
/// <returns>Status of permission assignment</returns>
internal static string AssignUserPermissionsToItem(ClientContext clientcontext, string listName, List<string> users, string permission, int listItemId)
{
{
string returnvalue = "false";
try
{
List<string> permissions = new List<string>();
permissions.Add(permission);
Web web = clientcontext.Web;
clientcontext.Load(web.RoleDefinitions);
ListItem listItem = web.Lists.GetByTitle(listName).GetItemById(listItemId);
clientcontext.Load(listItem, item => item.HasUniqueRoleAssignments);
clientcontext.ExecuteQuery();
if (listItem.HasUniqueRoleAssignments)
{
if (null != permissions && null != users) //matter.permissions=read/limited access/contribute/ full control/ view only
{
foreach (string rolename in permissions)
{
try
{
RoleDefinitionCollection roleDefinitions = clientcontext.Web.RoleDefinitions;
RoleDefinition role = (from roleDef in roleDefinitions
where roleDef.Name == rolename
select roleDef).First();
foreach (string user in users)
{
//get the user object
Principal userprincipal = clientcontext.Web.EnsureUser(user);
//create the role definition binding collection
RoleDefinitionBindingCollection roledefinitionbindingcollection = new RoleDefinitionBindingCollection(clientcontext);
//add the role definition to the collection
roledefinitionbindingcollection.Add(role);
//create a role assignment with the user and role definition
listItem.RoleAssignments.Add(userprincipal, roledefinitionbindingcollection);
}
//execute the query to add everything
clientcontext.ExecuteQuery();
}
catch (Exception exception)
{
Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
throw; // Check
}
}
}
// success. return a success code
returnvalue = "true";
}
}
catch (Exception exception)
{
Utility.DisplayAndLogError(Utility.ErrorFilePath, string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["ErrorMessage"], "assigning Permission"));
Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
throw;
}
return returnvalue;
}
}
/// <summary>
/// Breaks item level permission.
/// </summary>
/// <param name="clientContext">Client context object</param>
/// <param name="listName">Site pages library</param>
/// <param name="copyPermissionsFromParent">Copy parent permissions</param>
/// <param name="listItemId">List item Id to break permission</param>
/// <returns>Boolean flag value</returns>
internal static bool BreakItemPermission(ClientContext clientContext, string listName, bool copyPermissionsFromParent, int listItemId)
{
bool flag = false;
try
{
Web web = clientContext.Web;
ListItem listItem = web.Lists.GetByTitle(listName).GetItemById(listItemId);
clientContext.Load(listItem, item => item.HasUniqueRoleAssignments);
clientContext.ExecuteQuery();
if (!listItem.HasUniqueRoleAssignments)
{
listItem.BreakRoleInheritance(copyPermissionsFromParent, true);
listItem.Update();
clientContext.ExecuteQuery();
flag = true;
}
}
catch (Exception exception)
{
Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
throw;
}
return flag;
}
/// <summary>
/// Create a Web Part page of matter in its document library
/// </summary>
/// <param name="sitePageLib">SharePoint List of matter library</param>
/// <param name="clientContext">SharePoint Client Context</param>
/// <param name="objFileInfo">Object of FileCreationInformation</param>
/// <param name="matter">Matter object containing Matter data</param>
/// <param name="web">Web object containing Web data</param>
/// <returns>true if success else false</returns>
internal static string CreateWebPartPage(List sitePageLib, ClientContext clientContext, FileCreationInformation objFileInfo, Matter matter, Web web)
{
string response = string.Empty;
//// Find Default Layout from Master Page Gallery to create Web Part Page
sitePageLib = web.Lists.GetByTitle(Constants.MasterPageGallery);
clientContext.Load(sitePageLib);
clientContext.ExecuteQuery();
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = Constants.DMSRoleQuery;
ListItemCollection collection = sitePageLib.GetItems(camlQuery);
clientContext.Load(
collection,
items => items.Include(
item => item.DisplayName,
item => item.Id));
clientContext.ExecuteQuery();
response = WebPartsCreation(sitePageLib, clientContext, objFileInfo, matter, web, collection);
return response;
}
/// <summary>
/// Deletes the list
/// </summary>
/// <param name="clientContext">Client context</param>
/// <param name="objectName">Object name</param>
/// <param name="isList">Flag to specify is matter object is list</param>
internal static void DeleteMatterObject(ClientContext clientContext, string objectName, bool isList)
{
try
{
if (isList)
{
List list = clientContext.Web.Lists.GetByTitle(objectName);
list.DeleteObject();
clientContext.ExecuteQuery();
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["Deleted"], objectName));
}
else
{
clientContext.Load(clientContext.Web, webDetails => webDetails.ServerRelativeUrl);
clientContext.ExecuteQuery();
string matterLandingPageUrl = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}{5}", clientContext.Web.ServerRelativeUrl, Constants.Backslash, ConfigurationManager.AppSettings["MatterLandingPageRepository"].Replace(Constants.SPACE, string.Empty), Constants.Backslash, objectName, Constants.AspxExtension);
Microsoft.SharePoint.Client.File clientFile = clientContext.Web.GetFileByServerRelativeUrl(matterLandingPageUrl);
clientFile.DeleteObject();
clientContext.ExecuteQuery();
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["DeletedMatter"], objectName));
}
}
catch (Exception exception)
{
Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
}
}
/// <summary>
/// Fetches matter details from excel sheet
/// </summary>
/// <param name="dataValue">Data value</param>
/// <returns>List of data storage</returns>
internal static List<DataStorage> FetchMatterData(Collection<Collection<string>> dataValue)
{
List<DataStorage> kvp = new List<DataStorage>();
int xlRange = dataValue.Count;
if (0 != xlRange)
{
int rowCount;
for (rowCount = 1; rowCount <= xlRange - 1; rowCount++)
{
if (!string.IsNullOrWhiteSpace(dataValue[rowCount][0]))
{
DataStorage tuple = new DataStorage();
tuple.ClientName = Convert.ToString(dataValue[rowCount][0], CultureInfo.InvariantCulture).Trim();
tuple.MatterPrefix = Convert.ToString(dataValue[rowCount][1], CultureInfo.InvariantCulture).Trim();
tuple.MatterDescription = Convert.ToString(dataValue[rowCount][2], CultureInfo.InvariantCulture).Trim();
tuple.MatterIdPrefix = Convert.ToString(dataValue[rowCount][3], CultureInfo.InvariantCulture).Trim();
tuple.PracticeGroup = Convert.ToString(dataValue[rowCount][4], CultureInfo.InvariantCulture).Trim();
tuple.AreaOfLaw = Convert.ToString(dataValue[rowCount][5], CultureInfo.InvariantCulture).Trim();
tuple.SubAreaOfLaw = Convert.ToString(dataValue[rowCount][6], CultureInfo.InvariantCulture).Trim();
tuple.ConflictCheckConductedBy = Convert.ToString(dataValue[rowCount][7], CultureInfo.InvariantCulture).Trim();
tuple.ConflictDate = Convert.ToString(dataValue[rowCount][8], CultureInfo.InvariantCulture).Trim();
tuple.BlockedUser = Convert.ToString(dataValue[rowCount][9], CultureInfo.InvariantCulture).Trim();
tuple.ResponsibleAttorneys = Convert.ToString(dataValue[rowCount][10], CultureInfo.InvariantCulture).Trim();
tuple.Attorneys = Convert.ToString(dataValue[rowCount][11], CultureInfo.InvariantCulture).Trim();
tuple.BlockedUploadUsers = Convert.ToString(dataValue[rowCount][12], CultureInfo.InvariantCulture).Trim();
tuple.ConflictIdentified = Convert.ToString(dataValue[rowCount][14], CultureInfo.InvariantCulture).Trim();
tuple.CopyPermissionsFromParent = Convert.ToBoolean(tuple.ConflictIdentified, CultureInfo.InvariantCulture) ? Constants.FALSE.ToUpperInvariant() : Convert.ToString(dataValue[rowCount][13], CultureInfo.InvariantCulture).Trim();
kvp.Add(tuple);
}
}
}
return kvp;
}
/// <summary>
/// Creates matter
/// </summary>
/// <param name="clientContext">Client context object for sharePoint</param>
/// <param name="url">URL of tenant</param>
/// <param name="matterData">Matter data</param>
/// <param name="folders">Folder name</param>
/// <returns>String result</returns>
internal static string CreateMatter(ClientContext clientContext, string url, Matter matterData, string folders)
{
string result = string.Empty;
string oneNoteLibraryName = matterData.MatterName + ConfigurationManager.AppSettings["OneNoteLibrarySuffix"];
try
{
Microsoft.SharePoint.Client.Web web = clientContext.Web;
clientContext.Load(web.Lists);
clientContext.ExecuteQuery();
List matterLibrary = (from list in web.Lists where list.Title.ToString().ToUpper() == matterData.MatterName.ToUpper() select list).FirstOrDefault();
List oneNoteLibrary = (from list in web.Lists where list.Title.ToString().ToUpper() == oneNoteLibraryName.ToUpper() select list).FirstOrDefault();
Uri clientUri = new Uri(url);
string requestedUrl = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}{5}", clientUri.AbsolutePath, Constants.Backslash, ConfigurationManager.AppSettings["MatterLandingPageRepository"].Replace(Constants.SPACE, string.Empty), Constants.Backslash, matterData.MatterName, Constants.AspxExtension);
bool isMatterLandingPageExists = Utility.PageExists(requestedUrl, clientContext);
// Matter exists
if (null != matterLibrary || null != oneNoteLibrary || isMatterLandingPageExists)
{
if (null != matterLibrary)
{
result = Constants.MatterLibraryExists; // return if matter library exists
}
else if (null != oneNoteLibrary)
{
result = Constants.OneNoteLibraryExists; // return if OneNote library exists
}
else if (isMatterLandingPageExists)
{
result = Constants.MatterLandingPageExists; // return if matter landing page exists
}
}
else
{
//Create Document library
MatterProvisionHelper.CreateDocumentLibrary(matterData.MatterName, clientContext, folders, false, matterData);
//Create OneNote library
MatterProvisionHelper.CreateDocumentLibrary(oneNoteLibraryName, clientContext, folders, true, matterData);
if (Convert.ToBoolean(ConfigurationManager.AppSettings["CalendarCreationEnabled"], CultureInfo.InvariantCulture))
{
Utility.AddCalendarList(clientContext, matterData);
}
MatterProvisionHelper.CreateOneNote(clientContext, new Uri(url), matterData);
if (Convert.ToBoolean(ConfigurationManager.AppSettings["TaskListCreationEnabled"], CultureInfo.InvariantCulture))
{
ListOperations.CreateTaskList(clientContext, matterData);
}
result = Constants.MatterProvisionPrerequisitesSuccess;
}
}
catch (Exception exception)
{
MatterProvisionHelper.DeleteMatter(clientContext, matterData);
Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + exception.Message + "Matter name: " + matterData.MatterName + "\nStacktrace: " + exception.StackTrace);
}
return result;
}
/// <summary>
/// Creates a new view for the document library (Matter)
/// </summary>
/// <param name="clientContext">SP client context</param>
/// <param name="matterList">Name of the list</param>
/// <returns>True if success else False</returns>
internal static void CreateView(ClientContext clientContext, List matterList)
{
try
{
string viewName = ConfigurationManager.AppSettings["ViewName"];
string[] viewColumnList = ConfigurationManager.AppSettings["ViewColumnList"].Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(listEntry => listEntry.Trim()).ToArray();
View outlookView = matterList.Views.Add(new ViewCreationInformation
{
Title = viewName,
ViewTypeKind = ViewType.Html,
ViewFields = viewColumnList,
Paged = true
});
string strQuery = string.Format(CultureInfo.InvariantCulture, Constants.ViewOrderByQuery, ConfigurationManager.AppSettings["ViewOrderByColumn"]);
outlookView.ViewQuery = strQuery;
outlookView.Update();
clientContext.ExecuteQuery();
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Created {0}", viewName));
}
catch (Exception exception)
{
Utility.DisplayAndLogError(Utility.ErrorFilePath, string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["ErrorMessage"], "creating Outlook View"));
Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
}
}
/// <summary>
/// Function to create document library for Matter and OneNote
/// </summary>
/// <param name="libraryName">Matter library name</param>
/// <param name="clientContext">client context information</param>
/// <param name="folders">folders to create in document library</param>
/// <param name="isOneNoteLibrary">Flag to determine OneNote library or Matter Library</param>
/// <param name="matter">Matter object containing Matter data</param>
internal static void CreateDocumentLibrary(string libraryName, ClientContext clientContext, string folders, bool isOneNoteLibrary, Matter matter)
{
IList<string> folderNames = new List<string>();
Microsoft.SharePoint.Client.Web web = clientContext.Web;
ListCreationInformation creationInfo = new ListCreationInformation();
creationInfo.Title = libraryName;
creationInfo.Description = matter.MatterDescription;
creationInfo.TemplateType = (int)ListTemplateType.DocumentLibrary;
// Added library GUID for URL consolidation changes
creationInfo.Url = matter.MatterGuid + (isOneNoteLibrary ? ConfigurationManager.AppSettings["OneNoteLibrarySuffix"] : string.Empty);
List list = web.Lists.Add(creationInfo);
list.ContentTypesEnabled = true;
// Version setting for OneNote document library
if (isOneNoteLibrary)
{
list.EnableVersioning = false;
string oneNoteFolderName = string.Empty;
oneNoteFolderName = matter.MatterGuid;
// create folder
folderNames = new List<string>() { oneNoteFolderName };
}
else
{
list.EnableVersioning = true;
list.EnableMinorVersions = false;
list.ForceCheckout = false;
//Addition of Email folder
folderNames = folders.Split(';').Where(folder => !string.IsNullOrWhiteSpace(folder.Trim())).ToList();
}
list.Update();
clientContext.ExecuteQuery();
Utility.AddFolders(clientContext, list, folderNames);
MatterProvisionHelperUtility.BreakPermission(clientContext, libraryName, matter.CopyPermissionsFromParent);
}
/// <summary>
/// Assign field values for specified content types to the specified matter (document library)
/// </summary>
/// <param name="matterMetadata">Object containing metadata for Matter</param>
/// <param name="fields">Field Collection object</param>
internal static void SetFieldValues(MatterMetadata matterMetadata, FieldCollection fields)
{
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientId"]).DefaultValue = matterMetadata.Client.ClientId;
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientId"]).ReadOnlyField = true;
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientId"]).SetShowInDisplayForm(true);
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientId"]).Update();
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientName"]).ReadOnlyField = true;
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientName"]).SetShowInDisplayForm(true);
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientName"]).DefaultValue = matterMetadata.Client.ClientName;
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnClientName"]).Update();
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterId"]).DefaultValue = matterMetadata.Matter.MatterId;
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterId"]).ReadOnlyField = true;
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterId"]).SetShowInDisplayForm(true);
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterId"]).Update();
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterName"]).DefaultValue = matterMetadata.Matter.MatterName;
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterName"]).ReadOnlyField = true;
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterName"]).SetShowInDisplayForm(true);
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnMatterName"]).Update();
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnPracticeGroup"]).DefaultValue = string.Format(CultureInfo.InvariantCulture, Constants.MetadataDefaultValue, matterMetadata.PracticeGroupTerm.WssId, matterMetadata.PracticeGroupTerm.TermName, matterMetadata.PracticeGroupTerm.Id);
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnPracticeGroup"]).SetShowInDisplayForm(true);
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnPracticeGroup"]).Update();
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnAreaOfLaw"]).DefaultValue = string.Format(CultureInfo.InvariantCulture, Constants.MetadataDefaultValue, matterMetadata.AreaTerm.WssId, matterMetadata.AreaTerm.TermName, matterMetadata.AreaTerm.Id);
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnAreaOfLaw"]).SetShowInDisplayForm(true);
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnAreaOfLaw"]).Update();
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnSubareaOfLaw"]).DefaultValue = string.Format(CultureInfo.InvariantCulture, Constants.MetadataDefaultValue, matterMetadata.SubareaTerm.WssId, matterMetadata.SubareaTerm.TermName, matterMetadata.SubareaTerm.Id);
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnSubareaOfLaw"]).SetShowInDisplayForm(true);
fields.GetByInternalNameOrTitle(ConfigurationManager.AppSettings["ContentTypeColumnSubareaOfLaw"]).Update();
}
/// <summary>
/// Inserts details into LegalDMSMatters list
/// </summary>
/// <param name="configVal">Dictionary object</param>
/// <param name="title">Title of matter</param>
/// <param name="matter">Matter object</param>
/// <param name="client">client object</param>
/// <returns>Boolen value</returns>
internal static string InsertIntoMatterCenterMatters(Dictionary<string, string> configVal, string title, Matter matter, Client client)
{
try
{
using (ClientContext clientContext = MatterProvisionHelperUtility.GetClientContext(configVal["CatalogSiteURL"], configVal))
{
bool isConflict = Convert.ToBoolean(matter.Conflict.ConflictIdentified, CultureInfo.InvariantCulture);
List<FieldUserValue> conflictByUsers = MatterProvisionHelperUtility.ResolveUserNames(configVal, matter.Conflict.ConflictCheckBy).ToList<FieldUserValue>(),
blockedUsers = !string.IsNullOrEmpty(matter.TeamInfo.BlockedUsers.Trim()) ? MatterProvisionHelperUtility.ResolveUserNames(configVal, matter.TeamInfo.BlockedUsers).ToList<FieldUserValue>() : null,
managingUsers = MatterProvisionHelperUtility.ResolveUserNames(configVal, matter.TeamInfo.ResponsibleAttorneys).ToList<FieldUserValue>(),
supportUsers = !string.IsNullOrEmpty(matter.TeamInfo.Attorneys.Trim()) ? MatterProvisionHelperUtility.ResolveUserNames(configVal, matter.TeamInfo.Attorneys).ToList<FieldUserValue>() : null;
List list = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["MatterCenterList"]);
ListItemCreationInformation listCreationInformation = new ListItemCreationInformation();
ListItem listItem = list.AddItem(listCreationInformation);
listItem["Title"] = title; // "MyTitle";
listItem["ClientName"] = client.ClientName;
listItem["ClientID"] = client.ClientId; // "MyID";
listItem["MatterName"] = matter.MatterName;
listItem["MatterID"] = matter.MatterId;
listItem["ConflictCheckBy"] = conflictByUsers;
listItem["ConflictCheckOn"] = matter.Conflict.ConflictCheckOn;
listItem["ConflictIdentified"] = isConflict;
if (isConflict)
{
listItem["BlockUsers"] = blockedUsers;
}
listItem["ManagingAttorney"] = managingUsers;
listItem["Support"] = supportUsers;
listItem.Update();
clientContext.ExecuteQuery();
}
return "true";
}
catch (Exception exception)
{
Utility.DisplayAndLogError(Utility.ErrorFilePath, string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["ErrorMessage"], "while updating Metadata"));
Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + exception.Message + "Matter name: " + matter.MatterName + "\nStacktrace: " + exception.StackTrace);
throw;
}
}
}
} | 65.729352 | 441 | 0.637321 | [
"MIT"
] | nirmalpavan/MatterTest | tree/master/cloud/src/Helper Utilities/Microsoft.Legal.MatterCenter.HelperUtilities/Microsoft.Legal.MatterCenter.CreateSampleData/MatterProvisionHelper.cs | 51,731 | C# |
using System;
using System.CodeDom;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using EnvDTE;
namespace Microsoft.Samples.VisualStudio.CodeDomCodeModel {
[ComVisible(true)]
public abstract class CodeDomCodeType<CodeTypeType> : CodeDomCodeElement<CodeTypeType>, CodeType
where CodeTypeType : CodeTypeDeclaration {
private CodeElement parent;
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "0#dte")]
protected CodeDomCodeType(DTE dte, CodeElement parent, string name)
: base(dte, name) {
this.parent = parent;
}
protected void Initialize(object bases, object interfaces, vsCMAccess access) {
if (bases == System.Reflection.Missing.Value) {
CodeObject.BaseTypes.Add(new CodeTypeReference("System.Object"));
} else {
object[] baseClasses = bases as object[];
foreach (object baseCls in baseClasses) {
CodeObject.BaseTypes.Add(new CodeTypeReference(ObjectToClassName(baseCls)));
}
}
if (interfaces != System.Reflection.Missing.Value) {
object[] interfaceClasses = interfaces as object[];
foreach (object baseCls in interfaceClasses) {
CodeObject.BaseTypes.Add(new CodeTypeReference(ObjectToClassName(baseCls)));
}
}
CodeObject.Attributes = VSAccessToMemberAccess(access);
}
public override CodeElements Collection {
get { return parent.Children; }
}
public override CodeElements Children {
get {
//!!! and bases?
return Members;
}
}
#region CodeType Members
public vsCMAccess Access {
get { return MemberAccessToVSAccess(CodeObject.Attributes); }
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
set { CodeObject.Attributes = VSAccessToMemberAccess(value); }
}
public CodeAttribute AddAttribute(string Name, string Value, object Position) {
return AddCustomAttribute(CodeObject.CustomAttributes, Name, Value, Position);
}
public CodeElement AddBase(object Base, object Position) {
string clsName = ObjectToClassName(Base);
CodeDomCodeTypeRef ctr = new CodeDomCodeTypeRef(DTE, clsName);
CodeObject.BaseTypes.Insert(PositionToBaseIndex(Position), ctr.CodeObject);
return ctr;
}
public CodeElements Attributes {
get { return GetCustomAttributes(CodeObject.CustomAttributes); }
}
public CodeElements DerivedTypes {
get { throw new NotImplementedException(); }
}
public EnvDTE.CodeNamespace Namespace {
get {
CodeDomCodeNamespace nsParent = parent as CodeDomCodeNamespace;
if (nsParent != null) return nsParent;
CodeType typeParent = parent as CodeType;
if (typeParent != null) return typeParent.Namespace;
return null;
}
}
public bool get_IsDerivedFrom(string FullName) {
throw new NotImplementedException();
}
public CodeElements Bases {
get {
CodeDomCodeElements res = new CodeDomCodeElements(DTE, this);
foreach (CodeTypeReference baseType in CodeObject.BaseTypes) {
CodeElement ce = (CodeElement)baseType.UserData[CodeKey];
if (!(ce is CodeInterface))
res.Add(ce);
}
return res;
}
}
public CodeElements ImplementedInterfaces {
get {
CodeDomCodeElements res = new CodeDomCodeElements(DTE, this);
foreach (CodeTypeReference baseType in CodeObject.BaseTypes) {
CodeElement ce = (CodeElement)baseType.UserData[CodeKey];
if (ce is CodeInterface)
res.Add(ce);
}
return res;
}
}
public string Comment {
get {
return GetComment(CodeObject.Comments, false);
}
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
set {
ReplaceComment(CodeObject.Comments, value, false);
}
}
public string DocComment {
get {
return GetComment(CodeObject.Comments, true);
}
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
set {
ReplaceComment(CodeObject.Comments, value, true);
}
}
public CodeElements Members {
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
get {
CodeDomCodeElements res = new CodeDomCodeElements(DTE, this);
foreach (CodeTypeMember member in CodeObject.Members) {
if (member.UserData[CodeKey] == null) {
if (member is CodeMemberEvent) {
//member.UserData[CodeKey] = new CodeDomCode
} else if (member is CodeMemberField) {
CodeMemberField cmf = member as CodeMemberField;
member.UserData[CodeKey] = new CodeDomCodeVariable(this, cmf);
} else if (member is CodeMemberMethod) {
CodeMemberMethod cmm = member as CodeMemberMethod;
member.UserData[CodeKey] = new CodeDomCodeFunction(this, cmm);
} else if (member is CodeMemberProperty) {
CodeMemberProperty cmp = member as CodeMemberProperty;
member.UserData[CodeKey] = new CodeDomCodeProperty(this, cmp);
} else if (member is CodeSnippetTypeMember) {
} else if (member is CodeTypeDeclaration) {
}
}
res.Add((CodeElement)member.UserData[CodeKey]);
}
return res;
}
}
public dynamic Parent {
get { return parent; }
}
public void RemoveBase(object Element) {
int index = ((CodeDomCodeElements)Bases).IndexOf((SimpleCodeElement)Element);
CodeObject.BaseTypes.RemoveAt(index);
}
public void RemoveMember(object Element) {
int index = ((CodeDomCodeElements)Members).IndexOf((SimpleCodeElement)Element);
((CodeDomCodeElements)Members).RemoveAt(index);
}
#endregion
protected int PositionToIndex(object position) {
ICodeDomElement icde = position as ICodeDomElement;
if (icde != null) {
return CodeObject.Members.IndexOf((CodeTypeMember)icde.UntypedCodeObject) + 1;
}
if (position == System.Reflection.Missing.Value) {
return CodeObject.Members.Count;
}
int pos = (int)position;
if (pos == -1) {
return CodeObject.Members.Count;
}
return pos;
}
protected int PositionToInterfaceIndex(object position) {
return PositionToInterfaceOrBaseIndex(position, true);
}
protected int PositionToBaseIndex(object position) {
return PositionToInterfaceOrBaseIndex(position, false);
}
private int PositionToInterfaceOrBaseIndex(object Position, bool toInterface) {
ICodeDomElement icde = Position as ICodeDomElement;
int position = Int32.MaxValue;
if (icde == null) {
if (Position != System.Reflection.Missing.Value) {
position = (int)Position;
}
}
int index = 0, realIndex = 0;
foreach (CodeTypeReference baseType in CodeObject.BaseTypes) {
CodeElement ce = (CodeElement)baseType.UserData[CodeKey];
if ((icde != null && ce == icde) || position == index + 1) {
return realIndex;
}
if (ce is CodeInterface == toInterface) index++;
realIndex++;
}
return realIndex;
}
public override object ParentElement {
get { return parent; }
}
public override string FullName {
get {
string parentFullName = string.Empty;
if (null != parent) {
parentFullName = parent.FullName;
}
if (string.IsNullOrEmpty(parentFullName)) {
return CodeObject.Name;
}
return string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}.{1}", parentFullName, CodeObject.Name);
}
}
public override bool IsCodeType {
get {
return true;
}
}
public override ProjectItem ProjectItem {
get { return parent.ProjectItem; }
}
}
}
| 37.007663 | 132 | 0.551299 | [
"MIT"
] | Ranin26/msdn-code-gallery-microsoft | Visual Studio Product Team/IronPython Integration/[C#]-IronPython Integration/C#/integration/IronPython/src/IronPython.Project/FileCodeModel/CodeDomCodeType.cs | 9,659 | C# |
namespace AspnetRun.Services.Products.Core.Entities.Base
{
public abstract class Entity : EntityBase<int>
{
}
}
| 17.857143 | 57 | 0.704 | [
"MIT"
] | nilavanrajamani/ecommerce-microservice | AspnetRun.Services.Products.Core/Entities/Base/Entity.cs | 127 | C# |
using Akka.Actor;
using AkkaPrismDemo.Module.Stocks.ActorModels.Messages;
using AkkaPrismDemo.Module.Stocks.ViewModels;
namespace AkkaPrismDemo.Module.Stocks.ActorModels.Actors.UI {
internal sealed class StockToggleButtonActor : ReceiveActor {
/// <summary>
/// The stocks coordinator.
/// </summary>
private readonly IActorRef _stocksCoordinatorActorRef;
/// <summary>
/// The stock symbol.
/// </summary>
private readonly string _stockSymbol;
/// <summary>
/// The view model.
/// </summary>
private readonly StockToggleButtonViewModel _viewModel;
/// <summary>
/// The constructor.
/// </summary>
/// <param name="stocksCoordinatorActorRef"></param>
/// <param name="viewModel"></param>
/// <param name="stockSymbol"></param>
public StockToggleButtonActor( IActorRef stocksCoordinatorActorRef, StockToggleButtonViewModel viewModel, string stockSymbol ) {
this._stocksCoordinatorActorRef = stocksCoordinatorActorRef;
this._viewModel = viewModel;
this._stockSymbol = stockSymbol;
// Set initial state
this.ToggledOff();
}
/// <summary>
/// The "Off" state.
/// </summary>
private void ToggledOff() {
this.Receive<ToggleStockMessage>( message => {
this._stocksCoordinatorActorRef.Tell( new WatchStockMessage( this._stockSymbol ) );
this._viewModel.UpdateButtonTextToOn();
this.Become( this.ToggledOn );
} );
}
/// <summary>
/// The "On" state.
/// </summary>
private void ToggledOn() {
this.Receive<ToggleStockMessage>( message => {
this._stocksCoordinatorActorRef.Tell( new UnwatchStockMessage( this._stockSymbol ) );
this._viewModel.UpdateButtonTextToOff();
this.Become( this.ToggledOff );
} );
}
}
}
| 28.278689 | 130 | 0.703768 | [
"MIT"
] | mikeruhl/AkkaPrismDemo | AkkaPrismDemo.Module.Stocks/ActorModels/Actors/UI/StockToggleButtonActor.cs | 1,727 | C# |
// <auto-generated />
// This file was generated by a T4 template.
// Don't change it directly as your change would get overwritten. Instead, make changes
// to the .tt file (i.e. the T4 template) and save it to regenerate this file.
// Make sure the compiler doesn't complain about missing Xml comments and CLS compliance
// 0108: suppress "Foo hides inherited member Foo. Use the new keyword if hiding was intended." when a controller and its abstract parent are both processed
// 0114: suppress "Foo.BarController.Baz()' hides inherited member 'Qux.BarController.Baz()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." when an action (with an argument) overrides an action in a parent controller
#pragma warning disable 1591, 3008, 3009, 0108, 0114
#region T4MVC
using System;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using T4MVC;
namespace RaceDay.Controllers
{
public partial class AuthorizeController
{
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public AuthorizeController() { }
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
protected AuthorizeController(Dummy d) { }
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
protected RedirectToRouteResult RedirectToAction(ActionResult result)
{
var callInfo = result.GetT4MVCResult();
return RedirectToRoute(callInfo.RouteValueDictionary);
}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
protected RedirectToRouteResult RedirectToAction(Task<ActionResult> taskResult)
{
return RedirectToAction(taskResult.Result);
}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
protected RedirectToRouteResult RedirectToActionPermanent(ActionResult result)
{
var callInfo = result.GetT4MVCResult();
return RedirectToRoutePermanent(callInfo.RouteValueDictionary);
}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
protected RedirectToRouteResult RedirectToActionPermanent(Task<ActionResult> taskResult)
{
return RedirectToActionPermanent(taskResult.Result);
}
[NonAction]
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public virtual System.Web.Mvc.ActionResult RedirectToActionWithMessage()
{
return new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.RedirectToActionWithMessage);
}
[NonAction]
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public virtual System.Web.Mvc.ActionResult AjaxRedirect()
{
return new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.AjaxRedirect);
}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public AuthorizeController Actions { get { return MVC.Authorize; } }
[GeneratedCode("T4MVC", "2.0")]
public readonly string Area = "";
[GeneratedCode("T4MVC", "2.0")]
public readonly string Name = "Authorize";
[GeneratedCode("T4MVC", "2.0")]
public const string NameConst = "Authorize";
[GeneratedCode("T4MVC", "2.0")]
static readonly ActionNamesClass s_actions = new ActionNamesClass();
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public ActionNamesClass ActionNames { get { return s_actions; } }
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public class ActionNamesClass
{
public readonly string FBApp = "FBApp";
public readonly string Logon = "Logon";
public readonly string RedirectToActionWithMessage = "RedirectToActionWithMessage";
public readonly string AjaxRedirect = "AjaxRedirect";
}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public class ActionNameConstants
{
public const string FBApp = "FBApp";
public const string Logon = "Logon";
public const string RedirectToActionWithMessage = "RedirectToActionWithMessage";
public const string AjaxRedirect = "AjaxRedirect";
}
static readonly ActionParamsClass_RedirectToActionWithMessage s_params_RedirectToActionWithMessage = new ActionParamsClass_RedirectToActionWithMessage();
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public ActionParamsClass_RedirectToActionWithMessage RedirectToActionWithMessageParams { get { return s_params_RedirectToActionWithMessage; } }
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public class ActionParamsClass_RedirectToActionWithMessage
{
public readonly string redirectAction = "redirectAction";
public readonly string model = "model";
}
static readonly ActionParamsClass_AjaxRedirect s_params_AjaxRedirect = new ActionParamsClass_AjaxRedirect();
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public ActionParamsClass_AjaxRedirect AjaxRedirectParams { get { return s_params_AjaxRedirect; } }
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public class ActionParamsClass_AjaxRedirect
{
public readonly string redirectAction = "redirectAction";
}
static readonly ViewsClass s_views = new ViewsClass();
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public ViewsClass Views { get { return s_views; } }
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public class ViewsClass
{
static readonly _ViewNamesClass s_ViewNames = new _ViewNamesClass();
public _ViewNamesClass ViewNames { get { return s_ViewNames; } }
public class _ViewNamesClass
{
public readonly string Denied = "Denied";
public readonly string Error = "Error";
public readonly string FBApp = "FBApp";
public readonly string Logon = "Logon";
}
public readonly string Denied = "~/Views/Authorize/Denied.cshtml";
public readonly string Error = "~/Views/Authorize/Error.cshtml";
public readonly string FBApp = "~/Views/Authorize/FBApp.cshtml";
public readonly string Logon = "~/Views/Authorize/Logon.cshtml";
}
}
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public partial class T4MVC_AuthorizeController : RaceDay.Controllers.AuthorizeController
{
public T4MVC_AuthorizeController() : base(Dummy.Instance) { }
[NonAction]
partial void FBAppOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);
[NonAction]
public override System.Web.Mvc.ActionResult FBApp()
{
var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.FBApp);
FBAppOverride(callInfo);
return callInfo;
}
[NonAction]
partial void LogonOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);
[NonAction]
public override System.Web.Mvc.ActionResult Logon()
{
var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Logon);
LogonOverride(callInfo);
return callInfo;
}
[NonAction]
partial void RedirectToActionWithMessageOverride(T4MVC_System_Web_Mvc_ActionResult callInfo, System.Web.Mvc.ActionResult redirectAction, RaceDay.PageMessageModel model);
[NonAction]
public override System.Web.Mvc.ActionResult RedirectToActionWithMessage(System.Web.Mvc.ActionResult redirectAction, RaceDay.PageMessageModel model)
{
var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.RedirectToActionWithMessage);
ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "redirectAction", redirectAction);
ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "model", model);
RedirectToActionWithMessageOverride(callInfo, redirectAction, model);
return callInfo;
}
[NonAction]
partial void AjaxRedirectOverride(T4MVC_System_Web_Mvc_ActionResult callInfo, System.Web.Mvc.ActionResult redirectAction);
[NonAction]
public override System.Web.Mvc.ActionResult AjaxRedirect(System.Web.Mvc.ActionResult redirectAction)
{
var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.AjaxRedirect);
ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "redirectAction", redirectAction);
AjaxRedirectOverride(callInfo, redirectAction);
return callInfo;
}
}
}
#endregion T4MVC
#pragma warning restore 1591, 3008, 3009, 0108, 0114
| 45.5 | 285 | 0.687738 | [
"MIT"
] | scottaworkman/raceday | RaceDay/T4MVC/AuthorizeController.generated.cs | 9,191 | C# |
using Aguacongas.IdentityServer.Admin.Services;
using Aguacongas.IdentityServer.Store;
using Aguacongas.IdentityServer.Store.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace Aguacongas.IdentityServer.Admin
{
/// <summary>
/// Generic key controller
/// </summary>
/// <typeparam name="T"></typeparam>
/// <seealso cref="Controller" />
[Produces(JsonFileOutputFormatter.SupportedContentType, "application/json")]
[Route("[controller]")]
[GenericControllerNameConvention]
public class GenericKeyController<T> : Controller where T : IAuthenticatedEncryptorDescriptor
{
private readonly KeyManagerWrapper<T> _wrapper;
/// <summary>
/// Initializes a new instance of the <see cref="GenericKeyController{T}"/> class.
/// </summary>
/// <param name="wrapper">The manager.</param>
/// <exception cref="ArgumentNullException">manager</exception>
public GenericKeyController(KeyManagerWrapper<T> wrapper)
{
_wrapper = wrapper ?? throw new ArgumentNullException(nameof(wrapper));
}
/// <summary>
/// Gets all keys.
/// </summary>
/// <returns></returns>
[HttpGet]
[Authorize(Policy = SharedConstants.READER)]
public PageResponse<Key> Get()
=> _wrapper.GetAllKeys();
/// <summary>
/// Revokes a specific key and persists the revocation to the underlying repository.
/// </summary>
/// <param name="id"> The id of the key to revoke.</param>
/// <param name="reason">An optional human-readable reason for revocation.</param>
[HttpDelete("{id}")]
[Authorize(Policy = SharedConstants.WRITER)]
public Task RevokeKey(Guid id, string reason)
=> _wrapper.RevokeKey(id, reason);
}
}
| 37.296296 | 97 | 0.657398 | [
"Apache-2.0"
] | markjohnnah/TheIdServer | src/IdentityServer/Aguacongas.IdentityServer.Admin/GenericKeyController.cs | 2,016 | 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("03PribavyaneNaNulaCyaloIEdno")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03PribavyaneNaNulaCyaloIEdno")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7878b015-befd-4a14-aa59-34fde5098053")]
// 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")]
| 39.594595 | 85 | 0.732423 | [
"MIT"
] | AleikovStudio/Useful-Codes-CSharp | 03PribavyaneNaNulaCyaloIEdno/Properties/AssemblyInfo.cs | 1,468 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace BetfairNG.Data
{
public class VenueResult
{
[JsonProperty(PropertyName = "venue")]
public string Venue { get; set; }
[JsonProperty(PropertyName = "marketCount")]
public int MarketCount { get; set; }
}
}
| 21 | 52 | 0.679198 | [
"MIT"
] | bkw1491/betfairng | Data/VenueResult.cs | 401 | C# |
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SqlServer.Dac;
using Microsoft.SqlServer.Dac.Model;
namespace MSBuild.Sdk.SqlProj.DacpacTool
{
class Program
{
static async Task<int> Main(string[] args)
{
var buildCommand = new Command("build")
{
new Option<string>(new string[] { "--name", "-n" }, "Name of the package"),
new Option<string>(new string[] { "--version", "-v" }, "Version of the package"),
new Option<FileInfo>(new string[] { "--output", "-o" }, "Filename of the output package"),
new Option<SqlServerVersion>(new string[] { "--sqlServerVersion", "-sv" }, () => SqlServerVersion.Sql150, description: "Target version of the model"),
new Option<FileInfo>(new string[] { "--inputfile", "-i" }, "Text file listing all input files"),
new Option<string[]>(new string[] { "--reference", "-r" }, "Reference(s) to include"),
new Option<FileInfo>(new string[] { "--predeploy" }, "Filename of optional pre-deployment script"),
new Option<FileInfo>(new string[] { "--postdeploy" }, "Filename of optional post-deployment script"),
new Option<FileInfo>(new string[] { "--refactorlog" }, "Filename of optional refactor log script"),
new Option<string[]>(new string[] { "--property", "-p" }, "Properties to be set on the model"),
new Option<string[]>(new string[] { "--sqlcmdvar", "-sc" }, "SqlCmdVariable(s) to include"),
new Option<bool>(new string[] { "--warnaserror" }, "Treat T-SQL Warnings As Errors"),
new Option<string>(new string[] { "--suppresswarnings", "-spw" }, "Warning(s) to suppress"),
new Option<FileInfo>(new string[] { "--suppresswarningslistfile", "-spl" }, "Filename for warning(s) to suppress for particular files"),
#if DEBUG
new Option<bool>(new string[] { "--debug" }, "Waits for a debugger to attach")
#endif
};
buildCommand.Handler = CommandHandler.Create<BuildOptions>(BuildDacpac);
var collectIncludesCommand = new Command("collect-includes")
{
new Option<FileInfo>(new string[] { "--predeploy" }, "Filename of optional pre-deployment script"),
new Option<FileInfo>(new string[] { "--postdeploy" }, "Filename of optional post-deployment script"),
#if DEBUG
new Option<bool>(new string[] { "--debug" }, "Waits for a debugger to attach")
#endif
};
collectIncludesCommand.Handler = CommandHandler.Create<InspectOptions>(InspectIncludes);
var deployCommand = new Command("deploy")
{
new Option<FileInfo>(new string[] { "--input", "-i" }, "Path to the .dacpac package to deploy"),
new Option<string>(new string[] { "--targetServerName", "-tsn" }, "Name of the server to deploy the package to"),
new Option<int>(new string[] { "--targetPort", "-tprt" }, "Port number to connect on (leave blank for default)"),
new Option<string>(new string[] { "--targetDatabaseName", "-tdn" }, "Name of the database to deploy the package to"),
new Option<string>(new string[] { "--targetUser", "-tu" }, "Username used to connect to the target server, using SQL Server authentication"),
new Option<string>(new string[] { "--targetPassword", "-tp" }, "Password used to connect to the target server, using SQL Server authentication"),
new Option<string[]>(new string[] { "--property", "-p" }, "Properties used to control the deployment"),
new Option<string[]>(new string[] { "--sqlcmdvar", "-sc" }, "SqlCmdVariable(s) and their associated values, separated by an equals sign."),
new Option<bool>(new string[] { "--runScriptsFromReferences", "-sff" }, "Whether to run pre- and postdeployment scripts from references"),
#if DEBUG
new Option<bool>(new string[] { "--debug" }, "Waits for a debugger to attach")
#endif
};
deployCommand.Handler = CommandHandler.Create<DeployOptions>(DeployDacpac);
var rootCommand = new RootCommand { buildCommand, collectIncludesCommand, deployCommand };
rootCommand.Description = "Command line tool for generating a SQL Server Data-Tier Application Framework package (dacpac)";
return await rootCommand.InvokeAsync(args);
}
private static int BuildDacpac(BuildOptions options)
{
// Wait for a debugger to attach
WaitForDebuggerToAttach(options);
// Set metadata for the package
using var packageBuilder = new PackageBuilder();
packageBuilder.SetMetadata(options.Name, options.Version);
// Set properties on the model (if defined)
if (options.Property != null)
{
foreach (var propertyValue in options.Property)
{
string[] keyValuePair = propertyValue.Split('=', 2);
packageBuilder.SetProperty(keyValuePair[0], keyValuePair[1]);
}
}
// Build the empty model for the target SQL Server version
packageBuilder.UsingVersion(options.SqlServerVersion);
// Add references to the model
if (options.Reference != null)
{
foreach (var reference in options.Reference)
{
string[] referenceDetails = reference.Split(';', 2, StringSplitOptions.RemoveEmptyEntries);
if (referenceDetails.Length == 1)
{
packageBuilder.AddReference(referenceDetails[0]);
}
else
{
packageBuilder.AddExternalReference(referenceDetails[0], referenceDetails[1]);
}
}
}
// Add SqlCmdVariables to the package (if defined)
if (options.SqlCmdVar != null)
{
packageBuilder.AddSqlCmdVariables(options.SqlCmdVar);
}
// Add input files by iterating through $Project.InputFiles.txt
if (options.InputFile != null)
{
if (options.InputFile.Exists)
{
foreach (var line in File.ReadLines(options.InputFile.FullName))
{
FileInfo inputFile = new FileInfo(line); // Validation occurs in AddInputFile
packageBuilder.AddInputFile(inputFile);
}
}
else
{
throw new ArgumentException($"No input files found, missing {options.InputFile.Name}");
}
}
//Add Warnings options
packageBuilder.TreatTSqlWarningsAsErrors = options.WarnAsError;
if (options.SuppressWarnings != null)
{
packageBuilder.AddWarningsToSuppress(options.SuppressWarnings);
}
// Add warnings suppressions for particular files through $Project.WarningsSuppression.txt
if (options.SuppressWarningsListFile != null)
{
if (options.SuppressWarningsListFile.Exists)
{
foreach (var line in File.ReadLines(options.SuppressWarningsListFile.FullName))
{
//Checks if there are suppression warnings list
var parts = line.Split('|', StringSplitOptions.RemoveEmptyEntries);
var warningList = (parts.Length > 1) ? parts[1] : null;
FileInfo inputFile = new FileInfo(parts[0]); // Validation occurs in AddInputFile
packageBuilder.AddFileWarningsToSuppress(inputFile, warningList);
}
}
}
// Validate the model
if (!packageBuilder.ValidateModel())
{
return 1;
}
// Save the package to disk
packageBuilder.SaveToDisk(options.Output, new PackageOptions() { RefactorLogPath = options.RefactorLog?.FullName });
// Add predeployment and postdeployment scripts (must happen after SaveToDisk)
packageBuilder.AddPreDeploymentScript(options.PreDeploy, options.Output);
packageBuilder.AddPostDeploymentScript(options.PostDeploy, options.Output);
return 0;
}
private static int InspectIncludes(InspectOptions options)
{
var scriptInspector = new ScriptInspector();
// Add predeployment and postdeployment scripts
if (options.PreDeploy != null)
{
scriptInspector.AddPreDeploymentScript(options.PreDeploy);
}
if (options.PostDeploy != null)
{
scriptInspector.AddPostDeploymentScript(options.PostDeploy);
}
// Write all included files to stdout
var includedFiles = scriptInspector.IncludedFiles;
foreach (var file in includedFiles)
{
Console.Out.WriteLine(file);
}
return 0;
}
private static int DeployDacpac(DeployOptions options)
{
// Wait for a debugger to attach
WaitForDebuggerToAttach(options);
try
{
var deployer = new PackageDeployer(new ActualConsole());
if (options.Property != null)
{
foreach (var propertyValue in options.Property)
{
string[] keyValuePair = propertyValue.Split('=', 2);
deployer.SetProperty(keyValuePair[0], keyValuePair[1]);
}
}
if (options.SqlCmdVar != null)
{
foreach (var sqlCmdVar in options.SqlCmdVar)
{
string[] keyValuePair = sqlCmdVar.Split('=', 2);
deployer.SetSqlCmdVariable(keyValuePair[0], keyValuePair[1]);
}
}
if (options.TargetPort.HasValue)
{
deployer.UseTargetServerAndPort(options.TargetServerName, options.TargetPort.Value);
}
else
{
deployer.UseTargetServer(options.TargetServerName);
}
if (!string.IsNullOrWhiteSpace(options.TargetUser))
{
deployer.UseSqlAuthentication(options.TargetUser, options.TargetPassword);
}
else
{
deployer.UseWindowsAuthentication();
}
if (options.RunScriptsFromReferences)
{
deployer.RunPreDeploymentScriptFromReferences(options.Input, options.TargetDatabaseName);
}
deployer.Deploy(options.Input, options.TargetDatabaseName);
if (options.RunScriptsFromReferences)
{
deployer.RunPostDeploymentScriptFromReferences(options.Input, options.TargetDatabaseName);
}
return 0;
}
catch (ArgumentException ex)
{
Console.WriteLine($"ERROR: An error occured while validating arguments: {ex.Message}");
return 1;
}
catch (Exception ex)
{
Console.WriteLine($"ERROR: An error ocurred during deployment: {ex.Message}");
return 1;
}
}
[Conditional("DEBUG")]
private static void WaitForDebuggerToAttach(BaseOptions options)
{
if (options.Debug)
{
Console.WriteLine($"Waiting for debugger to attach ({System.Diagnostics.Process.GetCurrentProcess().Id})");
while (!Debugger.IsAttached)
{
Thread.Sleep(100);
}
Console.WriteLine("Debugger attached");
}
}
}
}
| 44.301754 | 166 | 0.549263 | [
"MIT"
] | markalroberts/MSBuild.Sdk.SqlProj | src/DacpacTool/Program.cs | 12,628 | C# |
using System.Collections.Generic;
namespace Keen.Core.Query
{
/// <summary>
/// Holds information describing the query that is cached within a cached dataset.
/// </summary>
public class QueryDefinition
{
/// <summary>
/// Unique id of the project to analyze.
/// </summary>
public string ProjectId { get; set; }
/// <summary>
/// The type of analysis for this query (e.g. count, count_unique, sum etc.)
/// </summary>
public string AnalysisType { get; set; }
/// <summary>
/// Specifies the name of the event collection to analyze.
/// </summary>
public string EventCollection { get; set; }
/// <summary>
/// Refines the scope of events to be included in the analysis based on event property
/// values.
/// </summary>
public IEnumerable<QueryFilter> Filters { get; set; }
/// <summary>
/// Limits analysis to a specific period of time when the events occurred.
/// </summary>
public string Timeframe { get; set; }
/// <summary>
/// Assigns a timezone offset to relative timeframes.
/// </summary>
public string Timezone { get; set; }
/// <summary>
/// Specifies the size of time interval by which to group results. Using this parameter
/// changes the response format.
/// </summary>
public string Interval { get; set; }
/// <summary>
/// Specifies the names of properties by which to group results. Using this parameter
/// changes the response format.
/// </summary>
public IEnumerable<string> GroupBy { get; set; }
}
}
| 31.6 | 95 | 0.576525 | [
"MIT"
] | IshamMohamed/keen-sdk-net | Keen/Query/QueryDefinition.cs | 1,740 | C# |
using MediatR;
namespace ResourceProvisioning.Abstractions.Events
{
public interface IDomainEventHandler<in TEvent> : IDomainEventHandler, INotificationHandler<TEvent>, IEventHandler<TEvent> where TEvent : IDomainEvent
{
}
public interface IDomainEventHandler
{
}
}
| 19.714286 | 151 | 0.804348 | [
"MIT"
] | dfds/resource-provisioning-poc | src/ResourceProvisioning.Abstractions/Events/IDomainEventHandler.cs | 278 | C# |
using System;
using ClearHl7.Extensions;
using ClearHl7.Helpers;
using ClearHl7.Serialization;
namespace ClearHl7.V270.Types
{
/// <summary>
/// HL7 Version 2 ICD - Insurance Certification Definition.
/// </summary>
public class InsuranceCertificationDefinition : IType
{
/// <summary>
/// Gets or sets a value that indicates whether this instance is a subcomponent of another HL7 component instance.
/// </summary>
public bool IsSubcomponent { get; set; }
/// <summary>
/// ICD.1 - Certification Patient Type.
/// <para>Suggested: 0150 Certification Patient Type -> ClearHl7.Codes.V270.CodeCertificationPatientType</para>
/// </summary>
public CodedWithExceptions CertificationPatientType { get; set; }
/// <summary>
/// ICD.2 - Certification Required.
/// <para>Suggested: 0136 Yes/No Indicator -> ClearHl7.Codes.V270.CodeYesNoIndicator</para>
/// </summary>
public string CertificationRequired { get; set; }
/// <summary>
/// ICD.3 - Date/Time Certification Required.
/// </summary>
public DateTime? DateTimeCertificationRequired { get; set; }
/// <summary>
/// Initializes properties of this instance with values parsed from the given delimited string. Separators defined in the Configuration class are used to split the string.
/// </summary>
/// <param name="delimitedString">A string representation that will be deserialized into the object instance.</param>
public void FromDelimitedString(string delimitedString)
{
FromDelimitedString(delimitedString, null);
}
/// <summary>
/// Initializes properties of this instance with values parsed from the given delimited string. The provided separators are used to split the string.
/// </summary>
/// <param name="delimitedString">A string representation that will be deserialized into the object instance.</param>
/// <param name="separators">The separators to use for splitting the string.</param>
public void FromDelimitedString(string delimitedString, Separators separators)
{
Separators seps = separators ?? new Separators().UsingConfigurationValues();
string[] separator = IsSubcomponent ? seps.SubcomponentSeparator : seps.ComponentSeparator;
string[] segments = delimitedString == null
? Array.Empty<string>()
: delimitedString.Split(separator, StringSplitOptions.None);
CertificationPatientType = segments.Length > 0 && segments[0].Length > 0 ? TypeSerializer.Deserialize<CodedWithExceptions>(segments[0], true, seps) : null;
CertificationRequired = segments.Length > 1 && segments[1].Length > 0 ? segments[1] : null;
DateTimeCertificationRequired = segments.Length > 2 && segments[2].Length > 0 ? segments[2].ToNullableDateTime() : null;
}
/// <summary>
/// Returns a delimited string representation of this instance.
/// </summary>
/// <returns>A string.</returns>
public string ToDelimitedString()
{
System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture;
string separator = IsSubcomponent ? Configuration.SubcomponentSeparator : Configuration.ComponentSeparator;
return string.Format(
culture,
StringHelper.StringFormatSequence(0, 3, separator),
CertificationPatientType?.ToDelimitedString(),
CertificationRequired,
DateTimeCertificationRequired.HasValue ? DateTimeCertificationRequired.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null
).TrimEnd(separator.ToCharArray());
}
}
}
| 49.444444 | 180 | 0.641199 | [
"MIT"
] | davebronson/clear-hl7-net | src/ClearHl7/V270/Types/InsuranceCertificationDefinition.cs | 4,007 | C# |
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bobs.Utilities.Tests
{
[TestFixture]
public class StringFormatter_Tests
{
[Test]
public void StringFormatter_With_All_Parameters()
{
// Arrange
StringFormatter formatter = new StringFormatter(CultureInfo.InvariantCulture, "Hello {0}!", "World");
// Act
string result = formatter.ToString();
// Assert
Assert.That(result, Is.EqualTo("Hello World!"));
}
[Test]
public void StringFormatter_Without_Arguments()
{
// Arrange
StringFormatter formatter = new StringFormatter(CultureInfo.InvariantCulture, "Hello {0}!", null);
// Act
string result = formatter.ToString();
// Assert
Assert.That(result, Is.EqualTo("Hello {0}!"));
}
[Test]
public void StringFormatter_Without_Format()
{
// Arrange
StringFormatter formatter = new StringFormatter(CultureInfo.InvariantCulture, null, "World");
// Act
string result = formatter.ToString();
// Assert
Assert.That(result, Is.Null);
}
}
}
| 25.703704 | 113 | 0.582133 | [
"MIT"
] | BobsFriends/Bobs.Utilities | tests/Bobs.Utilities.Tests/StringFormatter_Tests.cs | 1,390 | C# |
using System;
namespace Tolitech.CodeGenerator.Domain.Queries
{
public interface IQuery
{
}
}
| 10.9 | 47 | 0.688073 | [
"MIT"
] | Tolitech/Domain | src/Domain/Queries/IQuery.cs | 111 | C# |
namespace SKIT.FlurlHttpClient.Wechat.Api.Models
{
/// <summary>
/// <para>表示 [POST] /shop/order/getpaymentparams 接口的响应。</para>
/// </summary>
public class ShopOrderGetPaymentParametersResponse : WechatApiResponse
{
public static class Types
{
public class PaymentParameters
{
/// <summary>
/// 获取或设置时间戳。
/// </summary>
[Newtonsoft.Json.JsonProperty("timeStamp")]
[System.Text.Json.Serialization.JsonPropertyName("timeStamp")]
[System.Text.Json.Serialization.JsonNumberHandling(System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString)]
public long Timestamp { get; set; }
/// <summary>
/// 获取或设置随机字符串。
/// </summary>
[Newtonsoft.Json.JsonProperty("nonceStr")]
[System.Text.Json.Serialization.JsonPropertyName("nonceStr")]
public string Nonce { get; set; } = default!;
/// <summary>
/// 获取或设置下单参数。
/// </summary>
[Newtonsoft.Json.JsonProperty("package")]
[System.Text.Json.Serialization.JsonPropertyName("package")]
public string Package { get; set; } = default!;
/// <summary>
/// 获取或设置签名。
/// </summary>
[Newtonsoft.Json.JsonProperty("paySign")]
[System.Text.Json.Serialization.JsonPropertyName("paySign")]
public string PaySign { get; set; } = default!;
/// <summary>
/// 获取或设置签名方式。
/// </summary>
[Newtonsoft.Json.JsonProperty("signType")]
[System.Text.Json.Serialization.JsonPropertyName("signType")]
public string SignType { get; set; } = default!;
}
}
/// <summary>
/// 获取或设置支付参数。
/// </summary>
[Newtonsoft.Json.JsonProperty("payment_params")]
[System.Text.Json.Serialization.JsonPropertyName("payment_params")]
public Types.PaymentParameters PaymentParameters { get; set; } = default!;
}
}
| 38.775862 | 141 | 0.530903 | [
"MIT"
] | OrchesAdam/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.Api/Models/Shop/Order/ShopOrderGetPaymentParametersResponse.cs | 2,383 | C# |
using SoulsFormats;
using System.Collections.Generic;
using System.Numerics;
namespace HKX2
{
public partial class hkbComputeRotationToTargetModifier : hkbModifier
{
public override uint Signature { get => 4275496900; }
public Quaternion m_rotationOut;
public Vector4 m_targetPosition;
public Vector4 m_currentPosition;
public Quaternion m_currentRotation;
public Vector4 m_localAxisOfRotation;
public Vector4 m_localFacingDirection;
public bool m_resultIsDelta;
public override void Read(PackFileDeserializer des, BinaryReaderEx br)
{
base.Read(des, br);
br.ReadUInt64();
m_rotationOut = des.ReadQuaternion(br);
m_targetPosition = des.ReadVector4(br);
m_currentPosition = des.ReadVector4(br);
m_currentRotation = des.ReadQuaternion(br);
m_localAxisOfRotation = des.ReadVector4(br);
m_localFacingDirection = des.ReadVector4(br);
m_resultIsDelta = br.ReadBoolean();
br.ReadUInt64();
br.ReadUInt32();
br.ReadUInt16();
br.ReadByte();
}
public override void Write(PackFileSerializer s, BinaryWriterEx bw)
{
base.Write(s, bw);
bw.WriteUInt64(0);
s.WriteQuaternion(bw, m_rotationOut);
s.WriteVector4(bw, m_targetPosition);
s.WriteVector4(bw, m_currentPosition);
s.WriteQuaternion(bw, m_currentRotation);
s.WriteVector4(bw, m_localAxisOfRotation);
s.WriteVector4(bw, m_localFacingDirection);
bw.WriteBoolean(m_resultIsDelta);
bw.WriteUInt64(0);
bw.WriteUInt32(0);
bw.WriteUInt16(0);
bw.WriteByte(0);
}
}
}
| 34.5 | 78 | 0.608159 | [
"MIT"
] | SyllabusGames/DSMapStudio | HKX2/Autogen/hkbComputeRotationToTargetModifier.cs | 1,863 | C# |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2018
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// This file was automatically generated and should not be edited directly.
namespace SharpVk
{
/// <summary>
///
/// </summary>
[System.Flags]
public enum PeerMemoryFeatureFlags
{
/// <summary>
///
/// </summary>
None = 0,
/// <summary>
///
/// </summary>
CopySource = 1 << 0,
/// <summary>
///
/// </summary>
CopyDestination = 1 << 1,
/// <summary>
///
/// </summary>
GenericSource = 1 << 2,
/// <summary>
///
/// </summary>
GenericDestination = 1 << 3,
}
}
| 31.457627 | 81 | 0.622845 | [
"MIT"
] | sebastianulm/SharpVk | src/SharpVk/PeerMemoryFeatureFlags.gen.cs | 1,856 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.