text stringlengths 13 6.01M |
|---|
using FluentAssertions;
using NUnit.Framework;
using System;
using System.Globalization;
using System.Net;
using System.Net.Mail;
using System.Threading;
namespace EasyConsoleNG.Tests
{
[TestFixture]
public class EasyConsoleInputTest_Email
{
private TestEasyConsole console;
[SetUp]
public void SetUp()
{
console = new TestEasyConsole();
}
[Test]
public void GivenInput_WhenReadingEmail_ShouldReturnEnteredValue()
{
console.SetupInput("test@example.com\n");
var value = console.Input.ReadEmail("Value");
value.Should().Be(new MailAddress("test@example.com"));
console.CapturedOutput.Should().Be("Value: ");
}
[Test]
public void GivenInput_WhenReadingEmail_ShouldIgnoreWhitespaces()
{
console.SetupInput(" test@example.com \n");
var value = console.Input.ReadEmail("Value");
value.Should().Be(new MailAddress("test@example.com"));
}
[Test]
public void GivenNoInput_WhenReadingEmail_ShouldReturnDefaultValue()
{
console.SetupInput("\n");
var value = console.Input.ReadEmail("Value", defaultValue: new MailAddress("test@example.com"));
value.Should().Be(new MailAddress("test@example.com"));
console.CapturedOutput.Should().Be("Value (default: test@example.com): ");
}
[Test]
public void GivenInvalidEmail_WhenReadingEmail_ShouldReturnError()
{
console.SetupInput("$*(&(#&@^\ntest@example.com\n");
var value = console.Input.ReadEmail("Value");
value.Should().Be(new MailAddress("test@example.com"));
console.CapturedOutput.Should().Be("Value: Please enter a valid email address.\nValue: ");
}
}
}
|
namespace ServiceQuotes.Application.Helpers
{
public class AppSettings
{
public string Secret { get; set; }
public string PaynowApiUrl { get; set; }
public string PaynowApiKey { get; set; }
public string PaynowApiSignatureKey { get; set; }
}
}
|
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using System.Collections.Generic;
using System.Linq;
using Toope_Varastonhallinta.Mallit;
namespace Toope_Varastonhallinta
{
public partial class MainWindow : Window
{
public ListBox Tuotelista = new ListBox();
public ListBox Varastosaldot = new ListBox();
public TextBox txtVarasto = new TextBox();
public Button btnLuoVarasto = new Button();
public TextBox txtTuote = new TextBox();
public Button btnLuoTuote = new Button();
public ComboBox cbVarastot = new ComboBox();
public ComboBox cbTuotteet = new ComboBox();
public TextBox txtMaara = new TextBox();
public Button btnLisaaVarastoon = new Button();
public MainWindow()
{
InitializeComponent();
#if DEBUG
this.AttachDevTools();
#endif
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
Tuotelista = this.FindControl<ListBox>("Tuotelista");
Varastosaldot = this.FindControl<ListBox>("Varastosaldot");
Tuotelista.Items = App.DB.Tuotteet.ToList();
Tuotelista.Tapped += Tuotelista_Tapped;
txtVarasto = this.FindControl<TextBox>("txtVarasto");
btnLuoVarasto = this.FindControl<Button>("btnLuoVarasto");
btnLuoVarasto.Click += BtnLuoVarasto_Click;
txtTuote = this.FindControl<TextBox>("txtTuote");
btnLuoTuote = this.FindControl<Button>("btnLuoTuote");
btnLuoTuote.Click += BtnLuoTuote_Click;
cbVarastot = this.FindControl<ComboBox>("cbVarastot");
cbTuotteet = this.FindControl<ComboBox>("cbTuotteet");
txtMaara = this.FindControl<TextBox>("txtMaara");
btnLisaaVarastoon = this.FindControl<Button>("btnLisaaVarastoon");
btnLisaaVarastoon.Click += BtnLisaaVarastoon_Click;
cbTuotteet.Items = App.DB.Tuotteet.ToList();
cbVarastot.Items = App.DB.Varastot.ToList();
}
private void BtnLisaaVarastoon_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if(cbVarastot.SelectedItem != null && cbTuotteet.SelectedItem != null)
{
double.TryParse(txtMaara.Text, out double maara);
Kirjaus uusi = new Kirjaus();
uusi.maara = maara;
uusi.Varasto = (Varasto)cbVarastot.SelectedItem;
uusi.Tuote = (Tuote)cbTuotteet.SelectedItem;
App.DB.Kirjaukset.Add(uusi);
App.DB.SaveChanges();
cbTuotteet.SelectedItem = null;
cbVarastot.SelectedItem = null;
txtMaara.Text = "";
cbVarastot.Items = App.DB.Varastot.ToList();
Tuotelista.Items = App.DB.Tuotteet.ToList();
cbTuotteet.Items = App.DB.Tuotteet.ToList();
if(Tuotelista.SelectedItem != null)
{
Tuotelista_Tapped(sender, e);
}
}
}
private void BtnLuoTuote_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (txtTuote.Text != "")
{
Tuote uusi = new Tuote();
uusi.TuotteenNimi = txtTuote.Text;
App.DB.Tuotteet.Add(uusi);
App.DB.SaveChanges();
txtTuote.Text = "";
Tuotelista.Items = App.DB.Tuotteet.ToList();
cbTuotteet.Items = App.DB.Tuotteet.ToList();
}
}
private void BtnLuoVarasto_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if(txtVarasto.Text != "")
{
Varasto uusiVarasto = new Varasto();
uusiVarasto.VarastonNimi = txtVarasto.Text;
App.DB.Varastot.Add(uusiVarasto);
App.DB.SaveChanges();
txtVarasto.Text = "";
cbVarastot.Items = App.DB.Varastot.ToList();
}
}
private void Tuotelista_Tapped(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
var valittu = (Tuote)Tuotelista.SelectedItem;
if (valittu != null)
{
List<VarastoViewModel> lista = new List<VarastoViewModel>();
var varastot = App.DB.Kirjaukset.Where(o => o.Tuote == valittu).AsEnumerable().GroupBy(o => o.Varasto);
foreach (var item in varastot)
{
lista.Add(new VarastoViewModel { VarastonNimi = item.Key.VarastonNimi, Saldo = item.Sum(o => o.maara) });
}
Varastosaldot.Items = lista.ToList();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace BassClefStudio.GameModel.Graphics.Commands.Turtle
{
/// <summary>
/// An enum defining the types of fills a <see cref="IGraphicsCommand"/> shape can have.
/// </summary>
[Flags]
public enum FillMode
{
/// <summary>
/// The shape is not filled or outlined.
/// </summary>
None = 0,
/// <summary>
/// The shape is outlined using the defined line-drawing properties.
/// </summary>
Outline = 0b01,
/// <summary>
/// The inside of the shape is filled in.
/// </summary>
Fill = 0b10,
/// <summary>
/// The shape is both outlined (<see cref="Outline"/>) and filled in (<see cref="Fill"/>).
/// </summary>
Both = Outline | Fill
}
}
|
using Discord.WebSocket;
using JhinBot.DiscordObjects;
using JhinBot.Utils;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace JhinBot.Services
{
public class GreetService : IGreetService
{
private const string pattern = "%user%";
private readonly DiscordSocketClient _client;
private readonly IDbService _dbService;
private readonly IOwnerLogger _ownerLogger;
private readonly IEmbedService _embedService;
private readonly IBotConfig _botConfig;
public GreetService(DiscordSocketClient client, IDbService dbService, IOwnerLogger ownerLogger,
IEmbedService embedService, IBotConfig botConfig)
{
_client = client;
_dbService = dbService;
_ownerLogger = ownerLogger;
_embedService = embedService;
_botConfig = botConfig;
_client.UserJoined += UserJoinedGuild;
}
private async Task UserJoinedGuild(SocketGuildUser arg)
{
using (var uow = _dbService.UnitOfWork)
{
var guildConfig = uow.GuildConfigRepo.For(arg.Guild.Id, set => set);
if (guildConfig.SendGreetMessageOnJoin)
{
var greetChannelId = guildConfig.GreetMessageChannelId;
if (greetChannelId == 0)
await _ownerLogger.LogMissingGuildConfigParameter("GreetChannelId", ToString(), arg.Guild.Name);
else
{
Regex rgx = new Regex(pattern);
string message = rgx.Replace(guildConfig.GreetMessage, arg.Mention);
var channel = arg.Guild.GetTextChannel(greetChannelId);
var embed = _embedService.CreateEmbed("Welcome!", _botConfig.EventColor, arg, message);
var toDelete = await channel.SendMessageAsync(arg.Mention, false, embed);
if (guildConfig.AutoDeleteGreet)
toDelete.DeleteAfter(30);
}
}
}
}
}
} |
using System.Threading.Tasks;
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.ProviderCommitments.Web.Models;
namespace SFA.DAS.ProviderCommitments.Web.Mappers;
public class BaseDraftApprenticeshipRequestFromChoosePilotStatusViewModelMapper : IMapper<ChoosePilotStatusViewModel, BaseDraftApprenticeshipRequest>
{
public Task<BaseDraftApprenticeshipRequest> Map(ChoosePilotStatusViewModel source)
{
return Task.FromResult(new BaseDraftApprenticeshipRequest
{
ProviderId = source.ProviderId,
CohortReference = source.CohortReference,
DraftApprenticeshipHashedId = source.DraftApprenticeshipHashedId
});
}
} |
namespace Assets
{
using UnityEngine;
public class PlayerInput : MonoBehaviour
{
public RectTransform Limits;
public float Speed = 10f;
// Update is called once per frame
protected virtual void LateUpdate()
{
var dx = Input.GetAxis("Horizontal") * Speed;
var dy = Input.GetAxis("Vertical") * Speed;
var delta = (new Vector3(dx, dy)).normalized * Speed * Time.deltaTime;
transform.position = transform.position + delta;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManagerScript : MonoBehaviour
{
void Update ()
{
if (Input.GetKeyDown(KeyCode.F1)) //Debug key to restart
{
Restart();
}
}
public void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
|
using ClearBank.DeveloperTest.Services;
using ClearBank.DeveloperTest.Types;
using FluentAssertions;
using Xunit;
namespace ClearBank.DeveloperTest.Tests
{
public class BacsPaymentValidationShould
{
private readonly Account _account;
private readonly MakePaymentRequest _makePaymentRequest;
private readonly BacsPaymentValidation _validator;
public BacsPaymentValidationShould()
{
_account = new Account();
_makePaymentRequest = new MakePaymentRequest();
_validator = new BacsPaymentValidation();
}
[Theory]
[InlineData(AllowedPaymentSchemes.Chaps)]
[InlineData(AllowedPaymentSchemes.FasterPayments)]
public void NotBeValid_GivenNotBacsPaymentSchemes(AllowedPaymentSchemes allowedPaymentSchemes)
{
_account.AllowedPaymentSchemes = allowedPaymentSchemes;
var isValid = _validator.IsPaymentValid(_account, _makePaymentRequest.Amount);
isValid.Should().BeFalse();
}
[Fact]
public void BeValid_GivenBacsPaymentSchemes()
{
_account.AllowedPaymentSchemes = AllowedPaymentSchemes.Bacs;
var isValid = _validator.IsPaymentValid(_account, _makePaymentRequest.Amount);
isValid.Should().BeTrue();
}
}
} |
using System;
delegate void newdelegate ();
namespace _06.委托 {
class Program {
public static void todosomething () {
System.Console.WriteLine ("我是委托");
}
static void Main (string[] args) {
newdelegate dosomething = new newdelegate (todosomething);
dosomething ();
}
}
}
|
namespace _13._MagicExchangeableWords
{
using System;
using System.Collections.Generic;
public class Startup
{
public static void Main()
{
string[] words = Console.ReadLine().Split(' ');
HashSet<char> firstWord = new HashSet<char>(words[0]);
HashSet<char> secondWord = new HashSet<char>(words[1]);
Console.WriteLine((firstWord.Count == secondWord.Count) ? "true" : "false");
}
}
} |
using Newtonsoft.Json.Linq;
using Tomelt.Layouts.Elements;
using Tomelt.Layouts.Framework.Elements;
namespace Tomelt.Layouts.Services {
public interface IElementSerializer : IDependency {
Element Deserialize(string data, DescribeElementsContext describeContext);
string Serialize(Element element);
object ToDto(Element element, int index = 0);
Element ParseNode(JToken node, Container parent, int index, DescribeElementsContext describeContext);
}
} |
using System;
using System.Collections;
using System.Management;
namespace gView.Framework.Sys.UI
{
internal class SystemInfo
{
#region -> Private Variables
public bool UseProcessorID;
public bool UseBaseBoardProduct;
public bool UseBaseBoardManufacturer;
public bool UseDiskDriveSignature;
public bool UseVideoControllerCaption;
public bool UsePhysicalMediaSerialNumber;
public bool UseBiosVersion;
public bool UseBiosManufacturer;
public bool UseWindowsSerialNumber;
public bool UseMashineName = false;
#endregion
public string GetSystemInfo(string SoftwareName)
{
//return GetSystemInfo2(SoftwareName);
if (UseMashineName)
{
SoftwareName += MashineName;
}
if (UseProcessorID == true)
{
SoftwareName += RunQuery("Processor", "ProcessorId");
}
if (UseBaseBoardProduct == true)
{
SoftwareName += RunQuery("BaseBoard", "Product");
}
if (UseBaseBoardManufacturer == true)
{
SoftwareName += RunQuery("BaseBoard", "Manufacturer");
}
if (UseDiskDriveSignature == true)
{
SoftwareName += RunQuery("DiskDrive", "Signature");
}
if (UseVideoControllerCaption == true)
{
SoftwareName += RunQuery("VideoController", "Caption");
}
if (UsePhysicalMediaSerialNumber == true)
{
SoftwareName += RunQuery("PhysicalMedia", "SerialNumber");
}
if (UseBiosVersion == true)
{
SoftwareName += RunQuery("BIOS", "Version");
}
if (UseWindowsSerialNumber == true)
{
SoftwareName += RunQuery("OperatingSystem", "SerialNumber");
}
SoftwareName = RemoveUseLess(SoftwareName);
if (SoftwareName.Length < 25)
{
return GetSystemInfo(SoftwareName);
}
return SoftwareName.Substring(0, 25).ToUpper();
}
internal static string MashineName
{
get
{
try
{
return global::System.Net.Dns.GetHostName().Split('.')[0];
}
catch
{
try
{
return global::System.Environment.MachineName.Split('.')[0];
}
catch { }
}
return String.Empty;
}
}
private static string RemoveUseLess(string st)
{
char ch;
for (int i = st.Length - 1; i >= 0; i--)
{
ch = char.ToUpper(st[i]);
if ((ch < 'A' || ch > 'Z') &&
(ch < '0' || ch > '9'))
{
st = st.Remove(i, 1);
}
}
return st;
}
private static string RunQuery(string TableName, string MethodName)
{
ManagementObjectSearcher MOS = new ManagementObjectSearcher("Select * from Win32_" + TableName);
foreach (ManagementObject MO in MOS.Get())
{
try
{
return TrimString(MO[MethodName].ToString());
}
catch/*(Exception ex)*/
{
//System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
return "";
}
private static string TrimString(string str)
{
if (str == null)
{
return "";
}
str = str.Trim();
while (str.IndexOf("0") == 0)
{
str = str.Substring(1, str.Length - 1);
}
return str;
}
public static string GetSystemInfo2(string SoftwareName)
{
ArrayList hdCollection = new ArrayList();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject wmi_HD in searcher.Get())
{
HardDrive hd = new HardDrive();
hd.Model = wmi_HD["Model"].ToString();
hd.Type = wmi_HD["InterfaceType"].ToString();
hdCollection.Add(hd);
}
searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
int i = 0;
foreach (ManagementObject wmi_HD in searcher.Get())
{
// get the hard drive from collection
// using index
HardDrive hd = (HardDrive)hdCollection[i];
// get the hardware serial no.
if (wmi_HD["SerialNumber"] == null)
{
hd.SerialNo = "None";
}
else
{
hd.SerialNo = wmi_HD["SerialNumber"].ToString();
}
++i;
}
return String.Empty;
}
#region HelperClasses
class HardDrive
{
private string model = null;
private string type = null;
private string serialNo = null;
public string Model
{
get { return model; }
set { model = value; }
}
public string Type
{
get { return type; }
set { type = value; }
}
public string SerialNo
{
get { return serialNo; }
set { serialNo = value; }
}
}
#endregion
}
}
|
// Copyright 2013-2020 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Serilog.Core.Sinks;
sealed class RestrictedSink : ILogEventSink, IDisposable
#if FEATURE_ASYNCDISPOSABLE
, IAsyncDisposable
#endif
{
readonly ILogEventSink _sink;
readonly LoggingLevelSwitch _levelSwitch;
public RestrictedSink(ILogEventSink sink, LoggingLevelSwitch levelSwitch)
{
_sink = Guard.AgainstNull(sink);
_levelSwitch = Guard.AgainstNull(levelSwitch);
}
public void Emit(LogEvent logEvent)
{
Guard.AgainstNull(logEvent);
if (logEvent.Level < _levelSwitch.MinimumLevel)
return;
_sink.Emit(logEvent);
}
public void Dispose()
{
(_sink as IDisposable)?.Dispose();
}
#if FEATURE_ASYNCDISPOSABLE
public ValueTask DisposeAsync()
{
if (_sink is IAsyncDisposable asyncDisposable)
return asyncDisposable.DisposeAsync();
Dispose();
return default;
}
#endif
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace Kingdee.CAPP.Model
{
[Serializable]
public class ImageObject
{
/// <summary>
/// 图片路径
/// </summary>
[XmlAttribute("ImagePath")]
public string ImagePath { get; set; }
/// <summary>
/// 图片宽度
/// </summary>
[XmlAttribute("Width")]
public int Width { get; set; }
/// <summary>
/// 图片高度
/// </summary>
[XmlAttribute("Height")]
public int Height { get; set; }
/// <summary>
/// X坐标
/// </summary>
[XmlAttribute("LocationX")]
public int LocationX { get; set; }
/// <summary>
/// Y坐标
/// </summary>
[XmlAttribute("LocationY")]
public int LocationY { get; set; }
}
}
|
using Library.DataTransferObjects.Enum;
using System;
using System.Collections.Generic;
using System.Text;
namespace Library.DataTransferObjects.Filters
{
public class UserFilterDto
{
public int? UserId { get; set; }
public string PartialName { get; set; }
public AppRoleCode? RoleCode { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OcenaKlientow.Model.Models
{
public class Platnosc
{
[Required]
public string DataWymag { get; set; }
public string DataZaplaty { get; set; }
[Required]
public double Kwota { get; set; }
[Key]
[Required]
public int PlatnoscId { get; set; }
[Required]
public int ZamowienieId { get; set; }
//public virtual Zamowienie Zamowienie { get; set; }
}
}
|
namespace Domain.Models.Query
{
public class UserDetailsModel
{
public string FName { get; set; }
public string LName { get; set; }
public string DOB { get; set; }
public string PhotoName { get; set; }
public string PhotoPath { get; set; }
public string DocName { get; set; }
public string DocPath { get; set; }
}
}
|
using System.Collections.Generic;
namespace SortAlgorithm
{
/// <summary>
/// 【归并排序】
/// 归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,
/// 每个子序列是有序的。然后再把有序子序列合并为整体有序序列。
/// 稳定 时间复杂度 O(nlogn) 空间复杂度 O(n)
/// </summary>
public class MergeSort : SortBase
{
public override void Sort(List<int> nums)
{
Sort(nums, 0, nums.Count - 1);
}
public void Sort(List<int> nums, int f, int e)
{
if (f < e)
{
int mid = (f + e) / 2;
Sort(nums, f, mid);
Sort(nums, mid + 1, e);
MergeMethod(nums, f, mid, e);
}
}
private void MergeMethod(List<int> nums, int f, int mid, int e)
{
int[] t = new int[e - f + 1];
int m = f, n = mid + 1, k = 0;
while (n <= e && m <= mid)
{
if (nums[m] > nums[n]) t[k++] = nums[n++];
else t[k++] = nums[m++];
}
while (n < e + 1) t[k++] = nums[n++];
while (m < mid + 1) t[k++] = nums[m++];
for (k = 0, m = f; m < e + 1; k++, m++) nums[m] = t[k];
}
}
}
|
using System;
using System.Collections.Generic;
namespace CrossRoads
{
class Program
{
static void Main(string[] args)
{
Queue<string> queueOfCars = new Queue<string>();
int greenLightDuration = int.Parse(Console.ReadLine());
int freeWindowDuration = int.Parse(Console.ReadLine());
string input = Console.ReadLine();
bool isHit = false;
string hittedCarName = "";
char hittedSymbol = '\0';
int totalCars = 0;
while(input != "END")
{
if(input != "green")
{
queueOfCars.Enqueue(input);
input = Console.ReadLine();
continue;
}
int currentGreenLightDuration = greenLightDuration;
while(currentGreenLightDuration > 0 && queueOfCars.Count > 0)
{
string carName = queueOfCars.Dequeue();
int carLength = carName.Length;
if(currentGreenLightDuration - carLength >= 0)
{
currentGreenLightDuration -= carLength;
totalCars++;
}
else
{
currentGreenLightDuration += freeWindowDuration;
if(currentGreenLightDuration - carLength >= 0)
{
totalCars++;
break;
}
else
{
isHit = true;
hittedCarName = carName;
hittedSymbol = carName[currentGreenLightDuration];
break;
}
}
}
if(isHit)
{
break;
}
input = Console.ReadLine();
}
if(isHit)
{
Console.WriteLine("A crash happened!");
Console.WriteLine($"{hittedCarName} was hit at {hittedSymbol}.");
}
else
{
Console.WriteLine("Everyone is safe.");
Console.WriteLine($"{totalCars} total cars passed the crossroads.");
}
}
}
}
|
namespace CustomAppender
{
public interface INamedDocument
{
string Id { get; set; }
}
}
|
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace ProyectoSCA_Navigation.Clases
{
public class Aportacion
{
float[] interes_;
public float[] Interes_
{
get { return interes_; }
set { interes_ = value; }
}
String descripcion_;
public String Descripcion
{
get { return descripcion_; }
set { descripcion_ = value; }
}
float monto_;
public float Monto
{
get { return monto_; }
set { monto_ = value; }
}
int IDAportacion_;
public int IDAportacion
{
get { return IDAportacion_; }
set { IDAportacion_ = value; }
}
String fechaRealizacion_;
public String FechaRealizacion
{
get { return fechaRealizacion_; }
set { fechaRealizacion_ = value; }
}
int IDAfiliado_;
public int IDAfiliado
{
get { return IDAfiliado_; }
set { IDAfiliado_ = value; }
}
}
}
|
using Alabo.Data.People.Counties.Domain.Entities;
using Alabo.Domains.Repositories;
using MongoDB.Bson;
namespace Alabo.Data.People.Counties.Domain.Repositories
{
public interface ICountyRepository : IRepository<County, ObjectId>
{
}
} |
using System;
using System.Collections.Generic;
using Kattis.IO;
public class Program
{
struct frameSpan{
public frameSpan(int n, int x){
this.n = n;
this.x = x;
}
public int n;
public int x;
}
static public void Main ()
{
Scanner scanner = new Scanner();
BufferedStdoutWriter writer = new BufferedStdoutWriter();
Dictionary<int, frameSpan> frameSpans = new Dictionary<int, frameSpan>();
while(scanner.HasNext()){
int D = scanner.NextInt();
frameSpan n;
bool found = false;
if(frameSpans.ContainsKey(D)){
n = frameSpans[D];
found = true;
} else {
n = new frameSpan(0, 1);
int sqrD = (int) Math.Ceiling(Math.Sqrt(D));
for(; n.n < D ; n.n++){
for(n.x = 1; n.x <= sqrD; n.x++){
if(2 * n.x * n.n + (n.x * n.x) == D){
found = true;
frameSpans.Add(D, n);
break;
}
}
if(found){ break; }
}
}
if(found){
writer.Write(n.n);
writer.Write(" ");
writer.Write(n.n + n.x);
writer.Write("\n");
} else {
writer.WriteLine("impossible");
}
}
writer.Flush();
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.ProjectWindowCallback;
using System.Text;
using System.IO;
public class DoCreateScriptAsset : EndNameEditAction
{
public override void Action(int instanceId, string pathName, string resourceFile)
{
var text = File.ReadAllText(resourceFile);
var className = Path.GetFileNameWithoutExtension(pathName);
//去掉半角空间
className = className.Replace(" ", "");
text = text.Replace("#SCRIPTNAME#", className);
text += "\n//添加代码!";
//UTF8 の BOM 付きで保存
var encoding = new UTF8Encoding(true, false);
File.WriteAllText(pathName, text, encoding);
AssetDatabase.ImportAsset(pathName);
var asset = AssetDatabase.LoadAssetAtPath<MonoScript>(pathName);
ProjectWindowUtil.ShowCreatedAsset(asset);
}
}
|
using Microsoft.Extensions.DependencyInjection;
using SimplySqlSchema.MySql;
namespace SimplySqlSchema
{
public static class MySqlExtensions
{
public static IServiceCollection AddMySqlSupport(this IServiceCollection services)
{
return services
.AddScoped<IConnectionFactory, MySqlConnectionFactory>()
.AddScoped<ISchemaManager, MySqlSchemaManager>()
.AddScoped<ISchemaQuerier, MySqlQuerier>();
}
}
}
|
using AbiokaScrum.Api.IoC;
using System;
using System.Web;
using System.Web.Http;
using System.Web.Http.Dispatcher;
namespace AbiokaScrum.Api
{
public class Global : HttpApplication
{
protected void Application_Start(object sender, EventArgs e) {
GlobalConfiguration.Configure(WebApiConfig.Register);
Bootstrapper.Initialise();
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new DIControllerActivator());
}
public override void Dispose() {
//DependencyContainer.Container.Dispose();
base.Dispose();
}
}
} |
namespace CheckIt.Tests.CheckAssembly
{
using Xunit;
public class CheckInterfaceName
{
public CheckInterfaceName()
{
AssemblySetup.Initialize();
}
[Fact]
public void Should_check_name_for_all_interface()
{
Check.Interfaces().FromAssembly("CheckIt.dll").Have().Name().Match("^I[A-Z]+");
}
[Fact]
public void Should_check_name_when_type_is_interface()
{
Check.Interfaces().FromAssembly("CheckIt.dll").Have().Name().Match("^I[A-Z]+");
}
[Fact]
public void Should_check_name_when_type_is_interface_and_pattern_is_wrong()
{
var e = Assert.Throws<MatchException>(
() => Check.Interfaces("ErrorInterface").Have().Name().Match("^C[A-Z]+"));
Assert.Equal("The folowing interface doesn't respect pattern '^C[A-Z]+' :\nErrorInterface on line 2 from file ErrorInterface.cs", e.Message);
}
}
}
|
namespace HotelBookingSystem.Data
{
using Interfaces;
public class HotelBookingSystemData : IHotelBookingSystemData
{
public HotelBookingSystemData()
{
this.RepositoryWithUsers = new UserRepository();
this.RepositoryWithVenues = new Repository<IVenue>();
this.RepositoryWithRooms = new Repository<IRoom>();
this.RepositoryWithBookings = new Repository<IBooking>();
}
public IUserRepository RepositoryWithUsers { get; }
public IRepository<IVenue> RepositoryWithVenues { get; }
public IRepository<IRoom> RepositoryWithRooms { get; }
public IRepository<IBooking> RepositoryWithBookings { get; }
}
} |
using HtmlAgilityPack;
using SDU.ObsApi.Client.Core;
using SDU.ObsApi.Client.Entities;
using SDU.ObsApi.Client.Exceptions;
using SDU.ObsApi.Client.Helpers;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
namespace SDU.ObsApi.Client.Managers
{
public static class AuthenticationManager
{
internal static bool IsLogged { get; private set; }
public async static Task<Student> Login(string id, string password)
{
Student retVal = null;
try
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/index.aspx");
request.Content = new StringContent(string.Format(await GetMockRequestBody(), id, password));
request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage response = await ObsHttpClient.GetInstance().SendAsync(request);
if (response.IsSuccessStatusCode)
{
string htmlResponseContent = WebUtility.HtmlDecode(await response.Content.ReadAsStringAsync());
if (htmlResponseContent.Contains(id))
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlResponseContent);
retVal = new Student();
retVal.Id = doc.DocumentNode.SelectSingleNode(@"//*[@id=""ctl00_ContentPlaceHolder1_OgrenciTemelBilgiler1_textOgrenciNo""]").InnerText;
retVal.Name = doc.DocumentNode.SelectSingleNode(@"//*[@id=""ctl00_ContentPlaceHolder1_OgrenciTemelBilgiler1_textAdi""]").InnerText;
retVal.Surname = doc.DocumentNode.SelectSingleNode(@"//*[@id=""ctl00_ContentPlaceHolder1_OgrenciTemelBilgiler1_textSoyadi""]").InnerText;
retVal.TC = doc.DocumentNode.SelectSingleNode(@"//*[@id=""ctl00_ContentPlaceHolder1_OgrenciTemelBilgiler1_textTC""]").InnerText;
retVal.Faculty = doc.DocumentNode.SelectSingleNode(@"//*[@id=""ctl00_ContentPlaceHolder1_OgrenciTemelBilgiler1_textFakulte""]").InnerText;
retVal.Department = doc.DocumentNode.SelectSingleNode(@"//*[@id=""ctl00_ContentPlaceHolder1_OgrenciTemelBilgiler1_textBolum""]").InnerText.ToReplacedWithRegex(@"\([\s\S]*\)", string.Empty);
IsLogged = true;
}
else
{
throw new ObsApiException("Unable to login. Given login parameters is incorrect.");
}
}
else
{
throw new ObsApiException("Unable to login. HTTP status code should be 200 OK. An error occured while sending/receiving data.");
}
}
catch (Exception e)
{
throw new ObsApiException("An error occured while login operation is executing.", e);
}
return retVal;
}
public static async Task Logoff()
{
if (IsLogged)
{
HttpResponseMessage response = await ObsHttpClient.GetInstance().GetAsync("/Birimler/Ogrenci/Cikis.aspx");
if (response.IsSuccessStatusCode)
{
IsLogged = false;
}
else
{
throw new ObsApiException("Unable to logoff. HTTP status code should be 200 OK. An error occured while sending/receiving data.");
}
}
else
{
throw new ObsApiException("Should be logged before calling this method.");
}
}
private static Task<string> GetMockRequestBody()
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
using (Stream resourceStream = executingAssembly.GetManifestResourceStream("SDU.ObsApi.Client.Assets.MockRequestBody.txt"))
{
using (TextReader reader = new StreamReader(resourceStream))
{
return reader.ReadToEndAsync();
}
}
}
}
}
|
namespace DatabaseManagement.EnvDte
{
internal class ProjKinds
{
internal const string vsProjectKindSolutionFolder = "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}";
}
} |
using System;
using System.Collections.Generic;
using Kattis.IO;
public class Program
{
static readonly string[] code = {"apa", "epe", "ipi", "opo", "upu"};
static string decode(string s){
for(int i = 0; i < code.Length; i++){
s = s.Replace(code[i], (string)code[i].Substring(0, 1));
}
return s;
}
static public void Main ()
{
Scanner scanner = new Scanner();
BufferedStdoutWriter writer = new BufferedStdoutWriter();
while(scanner.HasNext()){
writer.Write(decode(scanner.Next()));
writer.Write(" ");
}
writer.Write("\n");
writer.Flush();
}
} |
using System;
using System.Text;
using TcpLib;
namespace SimpleServer
{
class MyServiceProvider : TcpServiceProvider
{
private FileRecordHandler _recordHandler = null;
public override object Clone()
{
return new MyServiceProvider();
}
public override void OnAcceptConnection(ConnectionState state)
{
Console.WriteLine("New connection from " + state.RemoteEndPoint.ToString());
_recordHandler = new FileRecordHandler(state);
}
public override void OnReceiveData(ConnectionState state)
{
if (_recordHandler != null)
{
int data_size = state.AvailableData;
byte[] data = new byte[data_size];
int bytesRead = state.Read(data, 0, data_size);
//use a file handler to process the new data
if (bytesRead > 0)
{
_recordHandler.Write(data, bytesRead);
}
}
}
public override void OnDropConnection(ConnectionState state)
{
Console.WriteLine("Session ended for " + state.RemoteEndPoint.ToString());
if (_recordHandler != null)
{
_recordHandler.Destroy();
}
}
}
}
|
using Microsoft.AspNetCore.Blazor.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.JSInterop;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace JSRuntimeRepro
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.TryConsole();
}
public void Configure(IBlazorApplicationBuilder app)
{
app.AddComponent<App>("app");
}
}
public static class ServiceCollectionExtensions
{
public static IServiceCollection TryConsole(this IServiceCollection serviceCollection)
{
Console.WriteLine("Write to the console from the .net");
Task t = LogFromJS();
t.RunSynchronously();
return serviceCollection;
}
public static Task<bool> LogFromJS()
{
return Interop.Log();
}
}
public class Interop
{
public static Task<bool> Log()
{
Console.WriteLine("Is JSRuntime.Current null?");
Console.WriteLine(JSRuntime.Current == null);
return JSRuntime.Current.InvokeAsync<bool>("TryConsole.log");
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace SupplianceStore.Domain.Entities
{
public class Review
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Display(Name = "Описание")]
[Required(ErrorMessage = "Пожалуйста, введите ваш отзыв")]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Display(Name = "Отценка")]
[Required(ErrorMessage = "Пожалуйста, поставьте отценку")]
[Range(0, 5, ErrorMessage = "Значение должно быть от 1 до 5")]
public int Stars { get; set; }
[HiddenInput(DisplayValue = false)]
public DateTime Date { get; set; }
[HiddenInput(DisplayValue = false)]
public int? ProductId { get; set; }
}
}
|
using NBatch.Main.Readers.FileReader;
namespace NBatch.ConsoleDemo
{
public class ProductMapper : IFieldSetMapper<Product>
{
public Product MapFieldSet(FieldSet fieldSet)
{
return new Product
{
ProductId = fieldSet.GetInt("ProductId"),
Name = fieldSet.GetString("Name"),
Description = fieldSet.GetString("Description"),
Price = fieldSet.GetDecimal("Price")
};
}
}
} |
using FirstFollowParser;
using System;
namespace LL1Parser
{
class Program
{
static void Main(string[] args)
{
GrammarParser grammar = new GrammarParser(@"C:\Users\darkshot\source\repos\LL1Parser\ParserTests\Sample5.in");
grammar.parse();
var table = new ParseTable(grammar);
table.printTable();
InputLexer n = new InputLexer(@"C:\Users\darkshot\source\repos\LL1\FirstAndFollow\Input2.in", grammar);
Console.WriteLine("__________________________________________________________");
Console.WriteLine(string.Join(",", n.elements));
var output=Parser.parser(grammar, n.elements);
Parser.printOutput(output);
Console.WriteLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserStore.DAL.EF;
using UserStore.DAL.Entities;
using UserStore.DAL.Interfaces;
namespace UserStore.DAL.Repositories
{
public class ArticleRepository:IRepository<Article>
{
private ApplicationContext _context;
public ArticleRepository(ApplicationContext context)
{
_context = context;
}
public void Create(Article item)
{
_context.Articles.Add(item);
}
public void Delete(int id)
{
Article article = _context.Articles.Find(id);
if (article != null)
{
_context.Articles.Remove(article);
}
}
public IEnumerable<Article> Find(Func<Article, bool> predicate)
{
return _context.Articles.Where(predicate).ToList();
}
public Article Get(int id)
{
return _context.Articles.Find(id);
}
public IEnumerable<Article> GetAll()
{
return _context.Articles;
}
public void Update(Article item)
{
_context.Entry(item).State=EntityState.Modified;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorldBusinessLayer
{
public class HelloWorldBusinessLayer
{
public string getHelloWorld()
{
HelloWorldDataLayer.HelloWorldDataLayer database = new HelloWorldDataLayer.HelloWorldDataLayer();
string HelloWorldText = database.GetHelloWorld();
return HelloWorldText;
}
}
}
|
using System.Xml.Linq;
namespace EngageNet.Data
{
public class ContactEmailAddress
{
public string Type { get; private set; }
public string EmailAddress { get; private set; }
public static ContactEmailAddress FromXElement(XElement xElement)
{
return new ContactEmailAddress
{
Type = xElement.Element("type") == null ? null : xElement.Element("type").Value,
EmailAddress = xElement.Element("value") == null ? null : xElement.Element("value").Value
};
}
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
namespace Democlass
{
public class ePAHelpers
{
/// <summary>
/// Get X-Authorization Token Methods
/// </summary>
/// <returns></returns>
public static string GetxauthorizationToken()
{
string xauthorization = string.Empty;
TimeSpan pauseBetweenRetry = TimeSpan.FromSeconds(1);
var cclient = new HttpClient();
int attempts = 0;
int MaxRetry = 3;
var response = cclient.GetAsync(Const.baseURL_xauthorization).GetAwaiter().GetResult();
if (response.StatusCode != HttpStatusCode.OK)
{
do
{
attempts++;
response = cclient.GetAsync(Const.baseURL_xauthorization).GetAwaiter().GetResult();
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
break;
}
if (attempts == MaxRetry)
throw new WebException($"The server returned: {xauthorization}");
System.Threading.Thread.Sleep(pauseBetweenRetry);
} while (true);
}
xauthorization = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return xauthorization;
}
/// <summary>
/// Post Authorization Method
/// </summary>
/// <returns></returns>
public static string PostxauthorizationToken()
{
string xauthorization = string.Empty;
TimeSpan pauseBetweenRetry = TimeSpan.FromSeconds(1);
var cclient = new HttpClient();
int attempts = 0;
int MaxRetry = 3;
string payload = JsonConvert.SerializeObject(new
{
app = "rx",
relyingPartyURl = "http://hub.allscripts.com/rx",
tenantId = "HubManagementTenant",
enviroment = "SRT2",
credentials = new { userName = "HubTxTest01", password = "Allscripts#1" }
});
var content = new StringContent(payload, Encoding.UTF8, "application/json");
var response = cclient.PostAsync(Const.baseURL_xauthorization, content).GetAwaiter().GetResult();
if (response.StatusCode != HttpStatusCode.OK)
{
do
{
attempts++;
response = cclient.PostAsync(Const.baseURL_xauthorization, content).GetAwaiter().GetResult();
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
break;
}
if (attempts == MaxRetry)
throw new WebException($"The server returned: {xauthorization}");
System.Threading.Thread.Sleep(pauseBetweenRetry);
} while (true);
}
xauthorization = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return xauthorization;
}
/// <summary>
/// Get (Retrieve) EPA Message List from MailBox
/// </summary>
/// <param name="token"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string getEPAMailBoxList(string token, string url)
{
HttpClient _httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("x-authorization", token);
HttpResponseMessage response = _httpClient.GetAsync(url).GetAwaiter().GetResult();
string resposeMessage = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return resposeMessage;
}
public static int getMailBoxGuidCount(string resposeMessage)
{
int count = 0;
if (!string.IsNullOrEmpty(resposeMessage))
{
DataSet ds;
using (StringReader stringReader = new StringReader(resposeMessage))
{
ds = new DataSet();
ds.ReadXml(stringReader);
}
if (ds != null && ds.Tables.Count > 1)
{
DataTable dt = ds.Tables[1];
count = dt.Rows.Count;
}
}
return count;
}
//public ListOfUsersDTO EPA_RetrieveMailboxList(string URL)
//{
// var user = new API_Helper<ListOfUsersDTO>();
// var url = URL;
// var request = user.CreateGetRequest();
// var response = user.GetResponse(url, request);
// ListOfUsersDTO content = HandleContent.GetContent<ListOfUsersDTO>(response);
// return content;
//}
}
}
|
using System;
using System.Collections.Generic;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;
namespace Karenia.IoLipsync
{
[BepInEx.BepInPlugin(guid, "IOLipsync", "0.1.0")]
public class Hook : BaseUnityPlugin
{
private const string guid = "cc.karenia.iolipsync";
public static LipsyncConfig config = new LipsyncConfig();
public Hook()
{
var harmony = new Harmony(guid);
harmony.PatchAll(typeof(TestHook));
this.AddConfigs();
}
public void AddConfigs()
{
config.DebugMenu = Config.Bind<bool>(new ConfigDefinition("Debug", "Debug Menu"), false);
}
}
public class LipsyncConfig
{
public ConfigEntry<bool> DebugMenu { get; set; }
}
public static class TestHook
{
[HarmonyPatch(typeof(KutiPaku), "Update")]
[HarmonyBefore]
public static bool CheckLip(KutiPaku __instance, Animator ___animator)
{
var animator = ___animator;
if (animator != null)
{
// TODO
}
return false;
}
private struct EnabledToggleKey : IEquatable<EnabledToggleKey>
{
public int id;
public int layer;
#region toggle
public override bool Equals(object obj)
{
return obj is EnabledToggleKey key && Equals(key);
}
public bool Equals(EnabledToggleKey other)
{
return id == other.id &&
layer == other.layer;
}
public override int GetHashCode()
{
int hashCode = 2005647062;
hashCode = hashCode * -1521134295 + id.GetHashCode();
hashCode = hashCode * -1521134295 + layer.GetHashCode();
return hashCode;
}
public static bool operator ==(EnabledToggleKey left, EnabledToggleKey right)
{
return left.Equals(right);
}
public static bool operator !=(EnabledToggleKey left, EnabledToggleKey right)
{
return !(left == right);
}
#endregion toggle
}
private struct EnabledToggleValue
{
public bool enabled;
public float value;
}
private static readonly Dictionary<int, Rect> windows = new Dictionary<int, Rect>();
private static readonly Dictionary<EnabledToggleKey, EnabledToggleValue> enabledKeys = new Dictionary<EnabledToggleKey, EnabledToggleValue>();
[HarmonyPatch(typeof(FaceMotion), "Awake")]
[HarmonyPostfix]
public static void AddDebugGui(FaceMotion __instance, Animator ___animator)
{
var guiComponent = __instance.gameObject.AddComponent<KutiPakuDebugGui>();
guiComponent.target = ___animator;
}
private class KutiPakuDebugGui : MonoBehaviour
{
public Animator target;
public void OnGUI()
{
if (!Hook.config.DebugMenu.Value) return;
var id = target.GetHashCode() + 0x14243;
var animator = target;
string title = string.Format("DEBUG/IOLipsync/{0}", target.gameObject.name);
if (!windows.TryGetValue(id, out var lastWindow))
{
lastWindow = new Rect(20, 20, 480, 480);
}
var window = GUILayout.Window(
id, lastWindow,
(id1) =>
{
GUI.DragWindow();
//GUILayout.BeginArea(new Rect(0, 0, 240, 480));
GUILayout.BeginVertical();
GUILayout.Label(title);
var cnt = animator.layerCount;
for (var i = 0; i < cnt; i++)
{
var toggle = new EnabledToggleKey { id = id, layer = i };
if (!enabledKeys.TryGetValue(toggle, out var value))
{
value = new EnabledToggleValue { enabled = false, value = 0 };
}
GUILayout.BeginHorizontal();
float layerWeight = animator.GetLayerWeight(i);
value.enabled = GUILayout.Toggle(value.enabled, string.Format("{0}", animator.GetLayerName(i), layerWeight), GUILayout.Width(90));
GUILayout.Label(string.Format("{0}", layerWeight), GUILayout.Width(90));
value.value = GUILayout.HorizontalSlider(value.value, 0, 1);
GUILayout.EndHorizontal();
if (value.enabled) animator.SetLayerWeight(i, value.value);
enabledKeys[toggle] = value;
}
GUILayout.EndVertical();
//GUILayout.EndArea();
},
title);
windows[id] = window;
}
}
}
}
|
using UnityEngine;
using UnityEditor;
using Ardunity;
[CustomEditor(typeof(ColliderReactor))]
public class ColliderReactorEditor : ArdunityObjectEditor
{
SerializedProperty script;
void OnEnable()
{
script = serializedObject.FindProperty("m_Script");
}
public override void OnInspectorGUI()
{
this.serializedObject.Update();
//ColliderReactor reactor = (ColliderReactor)target;
GUI.enabled = false;
EditorGUILayout.PropertyField(script, true, new GUILayoutOption[0]);
GUI.enabled = true;
this.serializedObject.ApplyModifiedProperties();
}
static public void AddMenuItem(GenericMenu menu, GenericMenu.MenuFunction2 func)
{
string menuName = "Unity/Add Reactor/Physics/ColliderReactor";
GameObject go = Selection.activeGameObject;
if(go != null && (go.GetComponent<Collider>() != null || go.GetComponent<Collider2D>() != null))
menu.AddItem(new GUIContent(menuName), false, func, typeof(ColliderReactor));
else
menu.AddDisabledItem(new GUIContent(menuName));
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using StartWebSiteEnglish.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using System.Threading.Tasks;
using System.Security.Claims;
using System.Net;
using StartWebSiteEnglish.ApiClasses;
using System.Net.Mail;
using Newtonsoft.Json;
using System.Text;
using Newtonsoft.Json.Linq;
namespace StartWebSiteEnglish.Controlers
{
public class UserController : Controller
{
private ApplicationUserManager UserManager
{
get
{
return HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
}
[Authorize]
public ActionResult UserPage()
{
ApplicationUser user = (ApplicationUser)Session["User"];
var words= LearnWords(user.UserName);
return View(words);
}
private List<Words> LearnWords(string userName)
{
List<Words> words = new List<Words>();
var idwords = SqlQueries.ReadWordDatabase(userName);
using(MaterialContext db = new MaterialContext())
{
foreach(var x in idwords)
{
words.Add(db.Words.FirstOrDefault(s => s.Id == x.Id));
}
}
ViewData["LearnUserWords"] = words;
return words;
}
public ActionResult Setting()
{
return View();
}
public ActionResult Dictionary()
{
//MaterialContext db = new MaterialContext();
//var mattex = from s in db.Words select s;
return View();
}
[HttpGet]
public ActionResult RenameUserName()
{
return View();
}
[HttpPost]
public async Task<ActionResult> EditPassword(EditPassword model, ApplicationUser user=null)
{
//HttpCookie userIdCookie = Request.Cookies["IdCookie"];
if (user == null)
{
user = (ApplicationUser)Session["User"];
}
if (ModelState.IsValid)
{
var BDuser = await this.UserManager.FindByIdAsync(user.Id);
if (BDuser != null)
{
var result = await this.UserManager.ChangePasswordAsync(BDuser.Id, model.Password, model.NewPassword);
if (result.Succeeded)
{
ViewBag.ChangePassword = "Пароль изменён";
return RedirectToAction("Setting");
}
else
{
foreach (string error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
else
{
ModelState.AddModelError(string.Empty, "Пользователь не найден");
}
}
ViewBag.ChangePassword = "Неудалось изменить пароль";
return View("Setting");
}
[HttpPost]
public async Task<ActionResult> EditEmail(string newEmail)
{
ApplicationUser user = (ApplicationUser)Session["User"];
if (user != null)
{
var result = await UserManager.SetEmailAsync(user.Id, newEmail);
if (result.Succeeded)
{
ViewBag.ChangeEmail = "Email изменён";
return RedirectToAction("Setting");
}
else
{
foreach (string error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
else
{
ModelState.AddModelError(string.Empty, "Пользователь не найден");
}
ViewBag.ChangeEmail = "Email не изменён";
return View();
}
[HttpPost]
public ActionResult EditUserName(string newUserName)
{
ApplicationUser user = (ApplicationUser)Session["User"];
if (user != null)
{
SqlQueries.RenameDatabases(user.UserName,newUserName );
user.UserName = newUserName;
var result = UserManager.Update(user);
if (result.Succeeded)
{
ViewBag.ChangeLogin = "Логин изменён";
return RedirectToAction("Setting");
}
else
{
foreach (string error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
else
{
ModelState.AddModelError(string.Empty, "Пользователь не найден");
}
ViewBag.ChangeLogin = "Логие не изменён";
return View();
}
static int appId = 6477544;
static int groupId = 166392001;
static int userId = 487648872;
static string token = "06be11fb31f5a4f68ff3cf1db3f336c03df90b87471cf5a3913b778a4e80ebb3eef6acabb1b72698fc14f";
[HttpPost]
public async Task<ActionResult> Upload(HttpPostedFileBase upload)
{
ApplicationUser user = (ApplicationUser)Session["User"];
if (user != null)
{
string filename = upload.FileName;
var client = new WebClient();
var urlForServer = "https://api.vk.com/method/photos.getWallUploadServer?access_token=" + token + "&v=5.74";
var reqForServer = client.DownloadString(urlForServer);
var jsonForServer = JsonConvert.DeserializeObject(reqForServer) as JObject;
var urlUploadServer = jsonForServer["response"]["upload_url"].ToString();
var reqUploadServer = Encoding.UTF8.GetString(client.UploadFile(urlUploadServer, "POST", filename));
var jsonUploadServer = JsonConvert.DeserializeObject(reqUploadServer) as JObject;
var urlSavePhoto = "https://api.vk.com/method/photos.saveWallPhoto?access_token=" + token
+ "&server=" + jsonUploadServer["server"]
+ "&photo=" + jsonUploadServer["photo"]
+ "&hash=" + jsonUploadServer["hash"]
+ "&v=5.74";
var reqSavePhoto = client.DownloadString(urlSavePhoto);
var jsonSavePhoto = JsonConvert.DeserializeObject(reqSavePhoto) as JObject;
var pictureUrl = jsonSavePhoto["response"][0]["photo_1280"].ToString();
var outUser = await UserManager.FindByIdAsync(user.Id);
outUser.PhotoUrl = pictureUrl;
var result = await UserManager.UpdateAsync(outUser);
if (result.Succeeded)
{
Session["User"] = outUser;
return RedirectToAction("UserPage");
}
else
{
foreach (string error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
return RedirectToAction("UserPage");
}
public ActionResult DeleteWord(int id)
{
var user = (ApplicationUser)Session["User"];
SqlQueries.DeteleWordDatabase(user.UserName, id);
return Json("Delete sucsess", JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult WordTranslate(int[] id)
{
ApplicationUser user = Session["User"] as ApplicationUser;
SetPXLevel(id.Length);
for (int i = 0; i < id.Length; i++)
{
SqlQueries.AddIdToWordDatabase(user.UserName, id[i]);
}
return Json(new { response = "Sucsses" }, JsonRequestBehavior.AllowGet);
}
private void SetPXLevel(int count)
{
ApplicationUser user = Session["User"] as ApplicationUser;
if (user != null)
{
var outUser = UserManager.FindById(user.Id);
outUser.LevelProgress += count;
UserManager.Update(outUser);
Session["User"] = outUser;
}
}
public ActionResult IsReading(int id)
{
ApplicationUser user = Session["User"] as ApplicationUser;
SqlQueries.AddIdToMaterialTextDatabase(user.UserName, id);
var material = (MaterialText)Session["TextReading"];
SetPXLevel(5);
ViewBag.IsReading = true;
return View("TextReading", material);
}
}
} |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TenmoServer.DAO;
using TenmoServer.Models;
namespace TenmoServer.Controllers
{
[Route("[controller]")]
[ApiController]
[Authorize]
public class UserController : ControllerBase
{
private readonly IUserDAO userDAO;
public UserController(IUserDAO userDAO)
{
this.userDAO = userDAO;
}
[HttpGet]
public IActionResult GetAllUsers()
{
List<User> accounts = userDAO.GetUsers();
if (accounts != null)
{
return Ok(accounts);
}
return NotFound();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AdventurousContacts.Models.Repository
{
public class Repository : IRepository
{
private bool _disposed = false;
private AdventureWorksEntities _entities = new AdventureWorksEntities();
#region IDisposable
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_entities.Dispose();
}
}
_disposed = true;
}
#endregion
//Returns all contacts from database
public IQueryable<Contact> FindAllContacts()
{
return _entities.Contacts;
}
//Delete a contact
public void Delete(Contact contact)
{
_entities.uspRemoveContact(contact.ContactID);
}
//Add a contact to the database
public void Add(Contact contact)
{
_entities.uspAddContactEF(contact.FirstName, contact.LastName, contact.EmailAddress);
}
//Returns a single contact from database
public Contact GetContactById(int contactId)
{
var contact = _entities.Contacts.Find(contactId);
return contact;
}
//Returns a list containing an X number of contacts
public List<Contact> GetLastContacts(int count = 20)
{
var contacts = FindAllContacts().ToList();
contacts.Reverse();
return contacts.Take(count).ToList();
}
//Updates a contact
public void Update(Contact contact)
{
_entities.uspUpdateContact(contact.ContactID, contact.FirstName, contact.LastName, contact.EmailAddress);
}
//Save all changes to database
public void Save()
{
_entities.SaveChanges();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Web;
using System.IO;
namespace PROnline.Src
{
public class Config
{
public static String root = "Config\\base\\config.xml";
public static String filePath = "";
public static XDocument GetXml()
{
String rootPath = MvcApplication.ServerPath;
if (filePath == "")
{
filePath = rootPath + root;
}
if (File.Exists(filePath))
{
return XDocument.Load(filePath);
}else{
return null;
}
}
public static int getIntValue(String name){
XElement root = GetXml().Root;
var value = root.Elements("config").Where(r=>r.Attribute("id").Value==name)
.Single().Attribute("value").Value;
return Convert.ToInt32(value);
}
public static void setValue(String name,int value){
XDocument doc = GetXml();
XElement root = doc.Root;
XElement finded = root.Elements("config").Where(r => r.Attribute("id").Value == name).Single();
if (finded != null)
{
finded.SetAttributeValue("value", value);
}
doc.Save(filePath);
}
public static void setValue(String name,String value){
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace GlobalConnectionInApp1.Util
{
class DbHelper
{
public static string connetionString = @"Data Source=TIFALAB\MSSQL16;Initial Catalog=School;Trusted_Connection=true;";
static SqlConnection cnn = new SqlConnection(connetionString);
public static SqlConnection getCon()
{
return cnn;
}
}
}
|
using Tomelt.Templates.Models;
namespace Tomelt.Templates.ViewModels {
public class ShapePartViewModel {
public string Template { get; set; }
public RenderingMode RenderingMode { get; set; }
}
} |
using System;
namespace Reactive.Flowable.Subscriber
{
public interface ISubscriber<in T> : ISubscription, IDisposable
{
//
// Summary:
// Notifies the observer that the provider has finished sending push-based notifications.
void OnComplete();
// Summary:
// Notifies the observer that the provider has experienced an error condition.
//
// Parameters:
// error:
// An object that provides additional information about the error.
void OnError(Exception error);
// Summary:
// Provides the observer with new data.
//
// Parameters:
// value:
// The current notification information.
void OnNext(T value);
void OnSubscribe(ISubscription subscription);
}
} |
using System;
namespace DevFitness.ConsoleApp.Refeicoes
{
public class Refeicao
{
#region Atributos
public string Descricao { get; private set; }
public int Calorias { get; private set; }
public decimal Preco { get; private set; }
#endregion
/// <summary>
/// Construtor da classe vazío.
/// </summary>
public Refeicao() { }
#region Construtores extras
/// <summary>
/// Construtor da classe recebendo descrição e calorias.
/// </summary>
/// <param name="descricao">Descrição da refeição</param>
/// <param name="calorias">Total de calorias fornecidas pela refeição</param>
public Refeicao(string descricao, int calorias)
{
this.Descricao = descricao;
this.Calorias = calorias;
this.Preco = 0;
}
/// <summary>
/// Construtor da classe recebendo descrição, calorias e preço da refeição.
/// </summary>
/// <param name="descricao">Descrição da refeição</param>
/// <param name="calorias">Total de calorias fornecidas pela refeição</param>
/// <param name="preco">Preço da refeição</param>
public Refeicao(string descricao, int calorias, decimal preco)
{
this.Descricao = descricao;
this.Calorias = calorias;
this.Preco = preco;
}
#endregion
#region Métodos setters
/// <summary>
/// Alterar a descrição da refeição.
/// </summary>
/// <param name="descricao">Nova descrição para a refeição</param>
public void SetDescricao(string descricao)
{
this.Descricao = descricao;
}
/// <summary>
/// Alterar a quantidade de calorias da refeição.
/// </summary>
/// <param name="calorias">Nova quantidade de calorias da refeição</param>
public void SetCalorias(int calorias)
{
this.Calorias = calorias;
}
/// <summary>
/// Alterar o preço da refeição.
/// </summary>
/// <param name="preco">Novo preço da refeição</param>
public void SetPreco(decimal preco)
{
this.Preco = preco;
}
#endregion
/// <summary>
/// Obter as informações da refeição.
/// </summary>
/// <returns>String com os detalhes da refeição</returns>
public virtual string ObterInformacoes()
{
return $"Descricao: {this.Descricao}.\n" +
$"Calorias: {this.Calorias}.\n" +
$"Preço: R$ {this.Preco.ToString("F2")}.\n";
}
}
} |
using System.Configuration;
namespace Gibe.CacheBusting.Config
{
public class CacheBustingSection : ConfigurationSection
{
[ConfigurationProperty("manifests", IsRequired = true)]
public ManifestElementCollection Manifests => (ManifestElementCollection) base["manifests"];
}
[ConfigurationCollection(typeof(ManifestElementCollection), CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)]
public class ManifestElementCollection : ConfigurationElementCollection
{
public override ConfigurationElementCollectionType CollectionType => ConfigurationElementCollectionType.AddRemoveClearMap;
protected override ConfigurationElement CreateNewElement()
{
return new ManifestElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ManifestElement) element).File;
}
}
public class ManifestElement : ConfigurationElement
{
[ConfigurationProperty("path", IsRequired = true, IsKey = false)]
public string Path
{
get => (string) this["path"];
set => this["path"] = value;
}
[ConfigurationProperty("file", IsRequired = true, IsKey = true)]
public string File
{
get => (string)this["file"];
set => this["file"] = value;
}
}
}
|
using HTB.v2.intranetx.util;
namespace HTB.v2.intranetx.permissions
{
public class PermissionsADStatistic
{
public bool GrantReports { get; set; }
public PermissionsADStatistic()
{
GrantReports = false;
}
public void LoadPermissions(int userId)
{
GrantReports = GlobalUtilArea.Rolecheck(409, userId);
}
}
} |
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 SongsDB;
namespace MediaInfo
{
//The Event Handler declaration
public delegate void NewSongDel();
public partial class MainForm : Form
{
//event is an instance of delegate
//The Event declaration
public event NewSongDel NewSongStarted = delegate { };
public SDBApplicationClass sDB;
private OrquestraCollection orqs;
private UISettings ui;
MediaInfoSettings mi;
//************************ Genetal settings *********************************
#region
Color formBGColor;// = Color.FromArgb(64, 64, 64); //Main Form BG Color
Color songBGColor;// = Color.FromArgb(15, 15, 15); //Song Info (Top Panel) BG Color
Color orqBGColor;// = Color.FromArgb(50, 50, 50); //Orq Info (Bottom Panel) BG Color
double imgPosition;// = .5; //Image position (.5 - middle)
bool orqInfoVisible;// = true; //Orquestra Info visability
bool nextTandaVisible;// = true; //Next Tanda Visability
int songCountMode;// = 1; //0 - invisible; 1 - three rows; 2 - one row;
string songNumbOf;// = "out of"; //of, out of, empty, "/"
#endregion
//************************ Current Song Info ********************************
#region
//Artist (Orquestra) label
string songArtistFont;// = "Courier";
FontStyle songArtistFontStyle;// = FontStyle.Bold;
Color songArtistColor;// = Color.FromArgb(247, 220, 111);
double csofm;// = .045; //FONT SIZE multiplyer Current song Artist (Orquestra)
double csovl;// = .001; //Vertical Location multiplyer Current song Artist (Orquestra) label
double cswm1;// = 1; //WIDTH multiplyer Current Artist (Orquestra) label
double cshm1;// = .225; //HEIGHT multiplyer Current Artist (Orquestra) label
ContentAlignment songArtistAlignment;// = ContentAlignment.MiddleCenter;
//Title label
string songTitleFont;// = "Arial";
FontStyle songTitleFontStyle;// = FontStyle.Bold;
Color songTitleColor;// = Color.FromArgb(253, 243, 207);
double cstfm;// = .035; //FONT SIZE multiplyer Current song Title
double cstvl;// = .28; //Vertical Location multiplyer Current song Title label
double cswm2;// = 1; //WIDTH multiplyer Current song Title label
double cshm2;// = .225; //HEIGHT multiplyer Current song Title label
ContentAlignment songTitleAlignment;// = ContentAlignment.MiddleCenter;
//Album (Singer) label
string songAlbumFont;// = "Arial";
FontStyle songAlbumFontStyle;// = FontStyle.Bold;
Color songAlbumColor;// = Color.FromArgb(253, 243, 207);
double csafm;// = .030; //FONT SIZE multiplyer Current song Album (Singer)
double csavl;// = .55; //Vertical Location multiplyer Current song Album label
double cswm3;// = 1; //WIDTH multiplyer Current song Album label
double cshm3;// = .225; //HEIGHT multiplyer Current song Album label
ContentAlignment songAlbumAlignment;// = ContentAlignment.MiddleCenter;
//Next Tanda label
string nextFont;// = "Sitka Text";
FontStyle nextFontStyle;// = FontStyle.Regular;
Color nextTandaColor;// = Color.FromArgb(100, 100, 100);
double ntfm;// = .02; //FONT SIZE multiplyer Next Tanda
double ntvl;// = .77; //Vertical Location multiplyer Next Tanda label
double cswm4;// = 1; //WIDTH multiplyer Next Tanda label
double cshm4;// = .225; //HEIGHT multiplyer Next Tanda label
ContentAlignment nextTandaAlignment;// = ContentAlignment.MiddleCenter;
#endregion
//**************************** Orquestra ************************************
#region
//Orquestra Info 1 (Top label)
string orqInfoFont1;// = "Sitka Text";
FontStyle orqInfoFontStyle1;// = FontStyle.Italic;
Color orqInfoColor1;// = Color.FromArgb(95, 158, 160);
double oifm1;// = .04; //FONT SIZE multiplyer Orq Info 1
double oi1vl;// = .15; //Vertical Location multiplyer Orq Info 1 label
double orqwm1;// = 1; //WIDTH multiplyer Orq Info 1 label
double orqhm1;// = .225; //HEIGHT multiplyer Orq Info 1 label
ContentAlignment orqInfoAlignment1;// = ContentAlignment.MiddleLeft;
//Orquestra Info 2 (Middle label)
string orqInfoFont2;// = "Sitka Text";
FontStyle orqInfoFontStyle2;// = FontStyle.Italic;
Color orqInfoColor2;// = Color.FromArgb(95, 158, 160);
double oifm2;// = .04; //FONT SIZE multiplyer Orq Info 2
double oi2vl;// = .38; //Vertical Location multiplyer Orq Info 2 label
double orqwm2;// = 1; //WIDTH multiplyer Orq Info 1 label
double orqhm2;// = .225; //HEIGHT multiplyer Orq Info 1 label
ContentAlignment orqInfoAlignment2;// = ContentAlignment.MiddleLeft;
//Orquestra Info 3 (Bottom label)
string orqInfoFont3;// = "Sitka Text";
FontStyle orqInfoFontStyle3;// = FontStyle.Italic;
Color orqInfoColor3;// = Color.FromArgb(95, 158, 160);
double oifm3;// = .04; //FONT SIZE multiplyer Orq Info 3
double oi3vl;// = .6; //Vertical Location multiplyer Orq Info 3 label
double orqwm3;// = 1; //WIDTH multiplyer Orq Info 1 label
double orqhm3;// = .225; //HEIGHT multiplyer Orq Info 1 label
ContentAlignment orqInfoAlignment3;// = ContentAlignment.MiddleLeft;
double oihl;// = .15; //Horisontal Location multiplyer ORQ Info
#endregion
//************************** Song Numbers ***********************************
#region
string songNumbFont1;// = "Arial";
FontStyle songNumbFontStyle1;// = FontStyle.Bold;
Color songNumbColor1;// = Color.FromArgb(95, 158, 160);
double snfm1;// = .03; //FONT SIZE multiplyer Song Numbers 1
double sncvl;// = .14; //Vertical Location multiplyer Song Number Current label
double snwm1;// = .3; //WIDTH multiplyer Song Numb 1 label
double snhm1;// = .2; //HEIGHT multiplyer Song Numb 1 label
ContentAlignment songNumberAlignment1;// = ContentAlignment.MiddleCenter;
string songNumbFont2;// = "Arial";
FontStyle songNumbFontStyle2;// = FontStyle.Bold;
Color songNumbColor2;// = Color.FromArgb(95, 158, 160);
double snfm2;// = .03; //FONT SIZE multiplyer Song Numbers 2
double snmvl;// = .39; //Vertical Location multiplyer Song Number Middle label
double snwm2;// = .3; //WIDTH multiplyer Song Numb 2 label
double snhm2;// = .2; //HEIGHT multiplyer Song Numb 2 label
ContentAlignment songNumberAlignment2;// = ContentAlignment.MiddleCenter;
string songNumbFont3;// = "Arial";
FontStyle songNumbFontStyle3;// = FontStyle.Bold;
Color songNumbColor3;// = Color.FromArgb(95, 158, 160);
double snfm3;// = .03; //FONT SIZE multiplyer Song Numbers 3
double sntvl;// = .63; //Vertical Location multiplyer Song Number Total label
double snwm3;// = .3; //WIDTH multiplyer Song Numb 3 label
double snhm3;// = .2; //HEIGHT multiplyer Song Numb 3 label
ContentAlignment songNumberAlignment3;// = ContentAlignment.MiddleCenter;
double snhl;// = .25; //Horisontal Location multiplyer Song Numbers
#endregion
public MainForm()
{
InitializeComponent();
// instantiate the delegate and register a method with the new instance.
NewSongDel newSong = new NewSongDel(onNewSongStarted);
sDB = new SDBApplicationClass();
sDB.OnPlay += newSong.Invoke; //OnPlay event from MediaMonkey API
Reader reader = new Reader();
orqs = reader.ReadIni();
//Get UI from Settings Form
if (mi == null)
{
mi = new MediaInfoSettings();
}
ui = mi.ui;
GetStarted();
}
public void UpdateIU(UISettings externalUI)
{
ui = externalUI;
GetStarted();
}
public void GetStarted()
{
InitializeUI();
this.BackColor = formBGColor; //Main Form BG Color
splitContainerBig.Panel1.BackColor = songBGColor; //Song Info (Top Panel) BG Color
splitContainerOrq.BackColor = orqBGColor; //Orq Info (Bottom Panel) BG Color
SetNextTandaVisability();
SetSongNumbVisability();
SetOrqInfoVisability();
ShowInfo();
}
protected virtual void onNewSongStarted()
{
ShowInfo();
}
private void InitializeUI()
{
//************************ Genetal settings *********************************
#region
formBGColor = Color.FromArgb(ui.FormBGColor[0], ui.FormBGColor[1], ui.FormBGColor[2]);
songBGColor = Color.FromArgb(ui.SongBGColor[0], ui.SongBGColor[1], ui.SongBGColor[2]);
orqBGColor = Color.FromArgb(ui.OrqBGColor[0], ui.OrqBGColor[1], ui.OrqBGColor[2]);
imgPosition = ui.ImgPosition; //Image position (.5 - middle)
orqInfoVisible = ui.OrqInfoVisible; //Orquestra Info visability
nextTandaVisible = ui.NextTandaVisible; //Next Tanda Visability
songCountMode = ui.SongCountMode; //0 - invisible; 1 - three rows; 2 - one row;
songNumbOf = ui.SongNumbOf; //of, out of, empty, "/"
#endregion
//*********************** Current Song Info ********************************
#region
//Artist label
songArtistFont = ui.SongArtistFont;
songArtistFontStyle = (FontStyle)Enum.Parse(typeof(FontStyle), ui.SongArtistFontStyle);
songArtistColor = Color.FromArgb(ui.SongArtistColor[0], ui.SongArtistColor[1], ui.SongArtistColor[2]); // Color.FromArgb(247, 220, 111);
csofm = ui.FontSizeArtist; // .045; //FONT SIZE multiplyer Current song Artist (Orquestra)
csovl = ui.VerticalLocationArtist; // .001; //Vertical Location multiplyer Current song Artist (Orquestra) label
cswm1 = ui.WidthArtist; // .1; //WIDTH multiplyer Current Artist (Orquestra) label
cshm1 = ui.HeightArtist; // .225; //HEIGHT multiplyer Current Artist (Orquestra) label
songArtistAlignment = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), ui.SongArtistAlignment); // ContentAlignment.MiddleCenter;
//Title label
songTitleFont = ui.SongTitleFont; // "Arial";
songTitleFontStyle = (FontStyle)Enum.Parse(typeof(FontStyle), ui.SongTitleFontStyle); // FontStyle.Bold;
songTitleColor = Color.FromArgb(ui.SongTitleColor[0], ui.SongTitleColor[1], ui.SongTitleColor[2]); // Color.FromArgb(253, 243, 207);
cstfm = ui.FontSizeTitle; // .035; //FONT SIZE multiplyer Current song Title
cstvl = ui.VerticalLocationTitle; // .28; //Vertical Location multiplyer Current song Title label
cswm2 = ui.WidthTitle; // .1; //WIDTH multiplyer Current song Title label
cshm2 = ui.HeightTitle; // .225; //HEIGHT multiplyer Current song Title label
songTitleAlignment = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), ui.SongTitleAlignment); // ContentAlignment.MiddleCenter;
//Album (Singer) label
songAlbumFont = ui.SongAlbumFont; // "Arial";
songAlbumFontStyle = (FontStyle)Enum.Parse(typeof(FontStyle), ui.SongAlbumFontStyle); // FontStyle.Bold;
songAlbumColor = Color.FromArgb(ui.SongAlbumColor[0], ui.SongAlbumColor[1], ui.SongAlbumColor[2]); // Color.FromArgb(253, 243, 207);
csafm = ui.FontSizeAlbum; // .030; //FONT SIZE multiplyer Current song Album (Singer)
csavl = ui.VerticalLocationAlbum; // .55; //Vertical Location multiplyer Current song Album label
cswm3 = ui.WidthAlbum; // .1; //WIDTH multiplyer Current song Album label
cshm3 = ui.HeightAlbum; // .225; //HEIGHT multiplyer Current song Album label
songAlbumAlignment = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), ui.SongAlbumAlignment); // ContentAlignment.MiddleCenter;
//Next Tanda label
nextFont = ui.NextFont; // "Sitka Text";
nextFontStyle = (FontStyle)Enum.Parse(typeof(FontStyle), ui.NextFontStyle); // FontStyle.Regular;
nextTandaColor = Color.FromArgb(ui.NextTandaColor[0], ui.NextTandaColor[1], ui.NextTandaColor[2]); // Color.FromArgb(100, 100, 100);
ntfm = ui.FontSizeNext; // .02; //FONT SIZE multiplyer Next Tanda
ntvl = ui.VerticalLocationNext; // .77; //Vertical Location multiplyer Next Tanda label
cswm4 = ui.WidthNext; // .1; //WIDTH multiplyer Next Tanda label
cshm4 = ui.HeightNext; // .225; //HEIGHT multiplyer Next Tanda label
nextTandaAlignment = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), ui.NextTandaAlignment); // ContentAlignment.MiddleCenter;
#endregion
//**************************** Orquestra ***********************************
#region
//Orquestra Info 1 (Top label)
orqInfoFont1 = ui.OrqInfoFont1; // "Sitka Text";
orqInfoFontStyle1 = (FontStyle)Enum.Parse(typeof(FontStyle), ui.OrqInfoFontStyle1); // FontStyle.Italic;
orqInfoColor1 = Color.FromArgb(ui.OrqInfoColor1[0], ui.OrqInfoColor1[1], ui.OrqInfoColor1[2]); // Color.FromArgb(95, 158, 160);
oifm1 = ui.FontSizeOrq1; // .04; //FONT SIZE multiplyer Orq Info 1
oi1vl = ui.VerticalLocationOrq1; // .15; //Vertical Location multiplyer Orq Info 1 label
orqwm1 = ui.WidthOrq1; // .1; //WIDTH multiplyer Orq Info 1 label
orqhm1 = ui.HeightOrq1; // .225; //HEIGHT multiplyer Orq Info 1 label
orqInfoAlignment1 = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), ui.OrqInfoAlignment1); // ContentAlignment.MiddleLeft;
//Orquestra Info 2 (Middle label)
orqInfoFont2 = ui.OrqInfoFont2; // "Sitka Text";
orqInfoFontStyle2 = (FontStyle)Enum.Parse(typeof(FontStyle), ui.OrqInfoFontStyle2); // FontStyle.Italic;
orqInfoColor2 = Color.FromArgb(ui.OrqInfoColor2[0], ui.OrqInfoColor2[1], ui.OrqInfoColor2[2]); // Color.FromArgb(95, 158, 160);
oifm2 = ui.FontSizeOrq2; // .04; //FONT SIZE multiplyer Orq Info 2
oi2vl = ui.VerticalLocationOrq2; // .38; //Vertical Location multiplyer Orq Info 2 label
orqwm2 = ui.WidthOrq2; // .1; //WIDTH multiplyer Orq Info 1 label
orqhm2 = ui.HeightOrq2; // .225; //HEIGHT multiplyer Orq Info 1 label
orqInfoAlignment2 = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), ui.OrqInfoAlignment2); // ContentAlignment.MiddleLeft;
//Orquestra Info 3 (Bottom label)
orqInfoFont3 = ui.OrqInfoFont3; // "Sitka Text";
orqInfoFontStyle3 = (FontStyle)Enum.Parse(typeof(FontStyle), ui.OrqInfoFontStyle3); // FontStyle.Italic;
orqInfoColor3 = Color.FromArgb(ui.OrqInfoColor3[0], ui.OrqInfoColor3[1], ui.OrqInfoColor3[2]); // Color.FromArgb(95, 158, 160);
oifm3 = ui.FontSizeOrq3; // .04; //FONT SIZE multiplyer Orq Info 3
oi3vl = ui.VerticalLocationOrq3; // .6; //Vertical Location multiplyer Orq Info 3 label
orqwm3 = ui.WidthOrq3; // .1; //WIDTH multiplyer Orq Info 1 label
orqhm3 = ui.HeightOrq3; // .225; //HEIGHT multiplyer Orq Info 1 label
orqInfoAlignment3 = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), ui.OrqInfoAlignment3); // ContentAlignment.MiddleLeft;
oihl = ui.HorizontalLocationOrq; // .15; //Horisontal Location multiplyer ORQ Info
#endregion
//************************** Song Numbers **********************************
#region
songNumbFont1 = ui.SongNumbFont1; // "Arial";
songNumbFontStyle1 = (FontStyle)Enum.Parse(typeof(FontStyle), ui.SongNumbFontStyle1); // FontStyle.Bold;
songNumbColor1 = Color.FromArgb(ui.SongNumbColor1[0], ui.SongNumbColor1[1], ui.SongNumbColor1[2]); // Color.FromArgb(95, 158, 160);
snfm1 = ui.FontSizeNumb1; // .03; //FONT SIZE multiplyer Song Numbers 1
sncvl = ui.VerticalLocationNumb1; // .14; //Vertical Location multiplyer Song Number Current label
snwm1 = ui.WidthNumb1; // .3; //WIDTH multiplyer Song Numb 1 label
snhm1 = ui.HeightNumb1; // .2; //HEIGHT multiplyer Song Numb 1 label
songNumberAlignment1 = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), ui.SongNumberAlignment1); // ContentAlignment.MiddleCenter;
songNumbFont2 = ui.SongNumbFont2; // "Arial";
songNumbFontStyle2 = (FontStyle)Enum.Parse(typeof(FontStyle), ui.SongNumbFontStyle2); // FontStyle.Bold;
songNumbColor2 = Color.FromArgb(ui.SongNumbColor2[0], ui.SongNumbColor2[1], ui.SongNumbColor2[2]); // Color.FromArgb(95, 158, 160);
snfm2 = ui.FontSizeNumb2; // .03; //FONT SIZE multiplyer Song Numbers 2
snmvl = ui.VerticalLocationNumb2; // .39; //Vertical Location multiplyer Song Number Middle label
snwm2 = ui.WidthNumb2; // .3; //WIDTH multiplyer Song Numb 2 label
snhm2 = ui.HeightNumb2; // .2; //HEIGHT multiplyer Song Numb 2 label
songNumberAlignment2 = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), ui.SongNumberAlignment2); // ContentAlignment.MiddleCenter;
songNumbFont3 = ui.SongNumbFont3; // "Arial";
songNumbFontStyle3 = (FontStyle)Enum.Parse(typeof(FontStyle), ui.SongNumbFontStyle3); // FontStyle.Bold;
songNumbColor3 = Color.FromArgb(ui.SongNumbColor3[0], ui.SongNumbColor3[1], ui.SongNumbColor3[2]); // Color.FromArgb(95, 158, 160);
snfm3 = ui.FontSizeNumb3; // .03; //FONT SIZE multiplyer Song Numbers 3
sntvl = ui.VerticalLocationNumb3; // .63; //Vertical Location multiplyer Song Number Total label
snwm3 = ui.WidthNumb3; // .3; //WIDTH multiplyer Song Numb 3 label
snhm3 = ui.HeightNumb3; // .2; //HEIGHT multiplyer Song Numb 3 label
songNumberAlignment3 = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), ui.SongNumberAlignment3); // ContentAlignment.MiddleCenter;
snhl = ui.HorizontalLocationNumb; // .25; //Horisontal Location multiplyer Song Numbers
#endregion
}
public void ShowInfo()
{
Dig dig = new Dig();
TextBox.CheckForIllegalCrossThreadCalls = false;
Song curSong = new Song();
Song nextTandaSong = new Song();
curSong = dig.CurrentSong(ui.AlbumSource); //Current Song (passing Album label source)
//Required to resize labels
lblCurSongTitle.AutoSize = false;
lblCurSongArtist.AutoSize = false;
lblCurSongAlbum.AutoSize = false;
lblNext.AutoSize = false;
lblSongInTanda.AutoSize = false;
lblOutOf.AutoSize = false;
lblsongsTotal.AutoSize = false;
lblOrqInfo2.AutoSize = false;
lblOrqInfo3.AutoSize = false;
lblOrqInfo1.AutoSize = false;
FormatCurSong();
//PlayList Info
nextTandaSong = dig.NextTanda(); //song
var songOrder = dig.SongCount(); //int array
string songCurrent;
string songTotal;
string songNumbers;
//If all songs in Tanda > 4
if (songOrder[1] > 4)
{
songCurrent = "";
songTotal = "";
songNumbers = "--";
}
else
{
songCurrent = songOrder[0].ToString();
songTotal = songOrder[1].ToString();
switch (songCountMode)
{
case 1:
songNumbers = songNumbOf; //of or out of
break;
case 2:
songNumbers = songCurrent + " " + songNumbOf + " " + songTotal;
break;
default:
songNumbers = songNumbOf; //of or out of
break;
}
}
if (songOrder[0] == 1 && songOrder[1] == 1)
{
songCurrent = "";
songNumbers = "";
songTotal = "";
}
if (songOrder[0] == 0 && songOrder[1] == 0)
{
songCurrent = "";
songNumbers = "";
songTotal = "";
}
//Load current song
lblCurSongArtist.Text = curSong.Artist;// + " " + curSong.Year;
lblCurSongTitle.Text = curSong.Title;// + " " + songNumbers;
lblCurSongAlbum.Text = curSong.Album;
lblNext.Text = "Next Tanda: " + nextTandaSong.Genre + " -- " + nextTandaSong.Artist;
//Load and format song numbers
lblSongInTanda.Text = songCurrent;
lblOutOf.Text = songNumbers;
lblsongsTotal.Text = songTotal;
FormatSongNumbers();
//********************************* Orq Info *********************************
//Load Orq Info
ShowOrqInfo(curSong.Artist);
ResizeOrqSplitPanel();
FormatOrqInfo();
FormatSongNumbers();
}
private void SetSongNumbVisability()
{
switch (songCountMode)
{
case 0:
lblSongInTanda.Visible = false;
lblOutOf.Visible = false;
lblsongsTotal.Visible = false;
break;
case 1:
lblSongInTanda.Visible = true;
lblOutOf.Visible = true;
lblsongsTotal.Visible = true;
break;
case 2:
lblSongInTanda.Visible = false;
lblOutOf.Visible = true;
lblsongsTotal.Visible = false;
break;
default:
break;
}
}
private void SetOrqInfoVisability()
{
if (!orqInfoVisible)
{
lblOrqInfo1.Visible = false;
lblOrqInfo2.Visible = false;
lblOrqInfo3.Visible = false;
}
else
{
lblOrqInfo1.Visible = true;
lblOrqInfo2.Visible = true;
lblOrqInfo3.Visible = true;
}
}
private void SetNextTandaVisability()
{
if (!nextTandaVisible)
{
lblNext.Visible = false;
}
else
{
lblNext.Visible = true;
}
}
//Load Orquestra Info
private void ShowOrqInfo(string artist)
{
bool pic = false;
foreach (Orquestra orq in orqs)
{
if (artist.Contains(orq.OrqName))
{
pictureBox.ImageLocation = orq.ImageFile;
lblOrqInfo1.Text = orq.Info_1;
lblOrqInfo2.Text = orq.Info_2;
lblOrqInfo3.Text = orq.Info_3;
pic = true;
break;
}
}
if (!pic)
{
pictureBox.ImageLocation = "Images\\music001.jpg";
lblOrqInfo1.Text = string.Empty;
lblOrqInfo2.Text = string.Empty;
lblOrqInfo3.Text = string.Empty;
}
}
//Scaleing fonts and positions with container size
private void splitContainer_SizeChanged(object sender, EventArgs e)
{
//Song Info
FormatCurSong();
//Song Numbers
FormatSongNumbers();
//Orq Info
FormatOrqInfo();
//Picture to the center
ResizeOrqSplitPanel();
}
private void FormatCurSong()
{
int fontSizeCurO = (int)(splitContainerBig.Panel1.Width * csofm); //Font size for current song Orquestra
int fontSizeCurT = (int)(splitContainerBig.Panel1.Width * cstfm); //Font size for current song Title
int fontSizeCurA = (int)(splitContainerBig.Panel1.Width * csafm); //Font size for current song Album (Singer)
int fontSizeNextTanda = (int)(splitContainerBig.Panel1.Width * ntfm); //Font size for Netx Tanda
lblCurSongArtist.Font = new Font(songArtistFont, fontSizeCurO, songArtistFontStyle);
lblCurSongTitle.Font = new Font(songTitleFont, fontSizeCurT, songTitleFontStyle);
lblCurSongAlbum.Font = new Font(songAlbumFont, fontSizeCurA, songAlbumFontStyle);
lblNext.Font = new Font(nextFont, fontSizeNextTanda, nextFontStyle);
lblCurSongArtist.ForeColor = songArtistColor;
lblCurSongTitle.ForeColor = songTitleColor;
lblCurSongAlbum.ForeColor = songAlbumColor;
lblNext.ForeColor = nextTandaColor;
//Current song Artist (Orquestra)
lblCurSongArtist.Width = (int)(splitContainerBig.Panel1.Width * cswm1);
lblCurSongArtist.Height = (int)(splitContainerBig.Panel1.Height * cshm1);
lblCurSongArtist.TextAlign = songArtistAlignment;
lblCurSongArtist.Location = new Point(0, (int)(splitContainerBig.Panel1.Height * csovl));
//Current song Title (Song Name)
lblCurSongTitle.Width = (int)(splitContainerBig.Panel1.Width * cswm2);
lblCurSongTitle.Height = (int)(splitContainerBig.Panel1.Height * cshm2);
lblCurSongTitle.TextAlign = songTitleAlignment;
lblCurSongTitle.Location = new Point(0, (int)(splitContainerBig.Panel1.Height * cstvl));
//Current song Album (Singer)
lblCurSongAlbum.Width = (int)(splitContainerBig.Panel1.Width * cswm3);
lblCurSongAlbum.Height = (int)(splitContainerBig.Panel1.Height * cshm3);
lblCurSongAlbum.TextAlign = songAlbumAlignment;
lblCurSongAlbum.Location = new Point(0, (int)(splitContainerBig.Panel1.Height * csavl));
//Next Tanda Info
lblNext.Width = (int)(splitContainerBig.Panel1.Width * cswm4);
lblNext.Height = (int)(splitContainerBig.Panel1.Height * cshm4);
lblNext.TextAlign = nextTandaAlignment;
lblNext.Location = new Point(0, (int)(splitContainerBig.Panel1.Height * ntvl));
}
private void ResizeOrqSplitPanel()
{
splitContainerOrq.SplitterDistance = ((int)(splitContainerBig.Width * imgPosition) + (int)(pictureBox.Width * .5) - 5);
}
private void FormatSongNumbers()
{
int fontSizeSongNumbers1 = (int)(splitContainerOrq.Panel1.Width * snfm1);
int fontSizeSongNumbers2 = (int)(splitContainerOrq.Panel1.Width * snfm2);
int fontSizeSongNumbers3 = (int)(splitContainerOrq.Panel1.Width * snfm3);
int xPosition = (int)(splitContainerOrq.Panel1.Width * snhl);
lblSongInTanda.ForeColor = songNumbColor1;
lblOutOf.ForeColor = songNumbColor2;
lblsongsTotal.ForeColor = songNumbColor3;
//lblSongInTanda.Text = songCurrent;
lblSongInTanda.Font = new Font(songNumbFont1, fontSizeSongNumbers1, songNumbFontStyle1);
lblSongInTanda.Width = (int)(splitContainerOrq.Panel1.Width * snwm1);
lblSongInTanda.Height = (int)(splitContainerOrq.Panel1.Height * snhm1);
lblSongInTanda.TextAlign = songNumberAlignment1;
lblSongInTanda.Location = new Point(xPosition, (int)(splitContainerOrq.Panel1.Height * sncvl)); //Vertical location
//lblOutOf.Text = songNumbers;
lblOutOf.Font = new Font(songNumbFont2, fontSizeSongNumbers2, songNumbFontStyle2);
lblOutOf.Width = (int)(splitContainerOrq.Panel1.Width * snwm2);
lblOutOf.Height = (int)(splitContainerOrq.Panel1.Height * snhm2);
lblOutOf.TextAlign = songNumberAlignment2;
lblOutOf.Location = new Point(xPosition, (int)(splitContainerOrq.Panel1.Height * snmvl)); //Vertical location
//lblsongsTotal.Text = songTotal;
lblsongsTotal.Font = new Font(songNumbFont3, fontSizeSongNumbers3, songNumbFontStyle3);
lblsongsTotal.Width = (int)(splitContainerOrq.Panel1.Width * snwm3);
lblsongsTotal.Height = (int)(splitContainerOrq.Panel1.Height * snhm3);
lblsongsTotal.TextAlign = songNumberAlignment3;
lblsongsTotal.Location = new Point(xPosition, (int)(splitContainerOrq.Panel1.Height * sntvl)); //Vertical location
}
private void FormatOrqInfo()
{
//Orq Info Formating
int fontSizeOrq1 = (int)(splitContainerOrq.Panel2.Width * oifm1) + 1; //Font size for Orq Info 1
int fontSizeOrq2 = (int)(splitContainerOrq.Panel2.Width * oifm2) + 1; //Font size for Orq Info 2
int fontSizeOrq3 = (int)(splitContainerOrq.Panel2.Width * oifm3) + 1; //Font size for Orq Info 3
int xPosition = (int)(splitContainerOrq.Panel2.Width * oihl);
//
pictureBox.Width = pictureBox.Height = (int)(splitContainerOrq.Panel1.Height - 10);
lblOrqInfo1.Location = new Point(xPosition, (int)(splitContainerOrq.Panel2.Height * oi1vl));
lblOrqInfo2.Location = new Point(xPosition, (int)(splitContainerOrq.Panel2.Height * oi2vl));
lblOrqInfo3.Location = new Point(xPosition, (int)(splitContainerOrq.Panel2.Height * oi3vl));
lblOrqInfo1.ForeColor = orqInfoColor1;
lblOrqInfo2.ForeColor = orqInfoColor2;
lblOrqInfo3.ForeColor = orqInfoColor3;
//Orquestro Info 1
lblOrqInfo1.Width = (int)(splitContainerOrq.Panel2.Width * orqwm1);
lblOrqInfo1.Height = (int)(splitContainerOrq.Panel2.Height * orqhm1);
lblOrqInfo1.TextAlign = orqInfoAlignment1;
//Orquestro Info 2
lblOrqInfo2.Width = (int)(splitContainerOrq.Panel2.Width * orqwm2);
lblOrqInfo2.Height = (int)(splitContainerOrq.Panel2.Height * orqhm2);
lblOrqInfo2.TextAlign = orqInfoAlignment2;
//Orquestro Info 3
lblOrqInfo3.Width = (int)(splitContainerOrq.Panel2.Width * orqwm3);
lblOrqInfo3.Height = (int)(splitContainerOrq.Panel2.Height * orqhm3);
lblOrqInfo3.TextAlign = orqInfoAlignment3;
lblOrqInfo1.Font = new Font(orqInfoFont1, fontSizeOrq1, orqInfoFontStyle1);
lblOrqInfo2.Font = new Font(orqInfoFont2, fontSizeOrq2, orqInfoFontStyle2);
lblOrqInfo3.Font = new Font(orqInfoFont3, fontSizeOrq3, orqInfoFontStyle3);
}
public void ResetUI()
{
ui = mi.ui;
}
//Original size and frame when double click on the picture
private void PictureBox_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (this.WindowState == FormWindowState.Maximized)
{
this.WindowState = FormWindowState.Normal;
this.FormBorderStyle = FormBorderStyle.Sizable;
}
}
//Remove frame when maximazed
private void MainForm_SizeChanged(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Maximized)
{
this.FormBorderStyle = FormBorderStyle.None;
//this.Bounds = Screen.PrimaryScreen.Bounds;
}
}
private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
if (this.WindowState == FormWindowState.Maximized)
{
this.WindowState = FormWindowState.Normal;
this.FormBorderStyle = FormBorderStyle.Sizable;
}
}
}
private void PictureBox_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
MediaInfoSettings settingsForm = new MediaInfoSettings(this);
settingsForm.ShowDialog();
//MessageBox.Show("Hi, there this is my contribution for Tango DJ", "Programed by AlexB");
}
}
}
}
|
using Microsoft.Practices.EnterpriseLibrary.Data;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Web;
namespace TestTutorial101
{
public class SqlHelper
{
#region "Variables"
DataSet ds = new DataSet();
DataTable dt = new DataTable();
Database db = DatabaseFactory.CreateDatabase("cn");
private static SqlHelper instance = new SqlHelper();
#endregion
public long SaveRegister(HybridDictionary hyb)
{
try
{
DbCommand dbCom = db.GetStoredProcCommand("usp_IU_Register");
db.AddInParameter(dbCom, "@AutoID", DbType.Int64, hyb["AutoID"]);
db.AddInParameter(dbCom, "@Name", DbType.String, hyb["Name"]);
db.AddInParameter(dbCom, "@Email", DbType.String, hyb["Email"]);
db.AddInParameter(dbCom, "@CountryID", DbType.Int64, Convert.ToInt64(hyb["CountryID"]));
db.AddInParameter(dbCom, "@State", DbType.Int64, Convert.ToInt64(hyb["State"]));
db.AddInParameter(dbCom, "@City", DbType.String, hyb["City"]);
db.AddInParameter(dbCom, "@pass", DbType.String, hyb["pass"]);
db.AddInParameter(dbCom, "@Subscribe", DbType.Boolean, Convert.ToBoolean(hyb["Subscribe"]));
db.AddInParameter(dbCom, "@profilephoto", DbType.String, hyb["profilephoto"]);
db.AddInParameter(dbCom, "@Address", DbType.String, hyb["Address"]);
db.AddInParameter(dbCom, "@Pin", DbType.String, hyb["Pin"]);
db.AddInParameter(dbCom, "@LandMark", DbType.String, hyb["LandMark"]);
db.AddInParameter(dbCom, "@Mobile", DbType.String, hyb["Mobile"]);
db.AddOutParameter(dbCom, "@CurrentUID", DbType.Int32, 0);
db.ExecuteNonQuery(dbCom);
long mCurrentUid = Convert.ToInt64(db.GetParameterValue(dbCom, "CurrentUID").ToString());
return mCurrentUid;
}
catch (Exception ex)
{
return -1;
}
}
public long SaveJob(HybridDictionary hyb, int flag)
{
try
{
DbCommand dbCom = db.GetStoredProcCommand("SpJob");
db.AddInParameter(dbCom, "@ID", DbType.Int32, Convert.ToInt32(hyb["ID"]));
db.AddInParameter(dbCom, "@JobTitle", DbType.String, hyb["JobTitle"]);
db.AddInParameter(dbCom, "@JobDesc", DbType.String, hyb["JobDesc"]);
db.AddInParameter(dbCom, "@Skill", DbType.String, hyb["Skill"]);
db.AddInParameter(dbCom, "@CompanyName", DbType.String, hyb["CompanyName"]);
db.AddInParameter(dbCom, "@ToDate", DbType.DateTime, Convert.ToDateTime(hyb["ToDate"]));
db.AddInParameter(dbCom, "@Remarks", DbType.String, hyb["Remarks"]);
db.AddInParameter(dbCom, "@Flag", DbType.Int32, flag);
db.AddOutParameter(dbCom, "@CurrentID", DbType.Int32, 0);
db.ExecuteNonQuery(dbCom);
long mCurrentUid = Convert.ToInt64(db.GetParameterValue(dbCom, "CurrentID").ToString());
return mCurrentUid;
}
catch (Exception ex)
{
return -1;
}
}
public long SaveNewEvent(HybridDictionary hyb , int flag)
{
try
{
DbCommand dbCom = db.GetStoredProcCommand("SpNewEvent");
db.AddInParameter(dbCom, "@ID", DbType.Int32, Convert.ToInt32(hyb["ID"]));
db.AddInParameter(dbCom, "@Title", DbType.String, hyb["Title"]);
db.AddInParameter(dbCom, "@ToDate", DbType.DateTime, Convert.ToDateTime(hyb["ToDate"]));
db.AddInParameter(dbCom, "@Remarks", DbType.String, hyb["Remarks"]);
db.AddInParameter(dbCom, "@Flag", DbType.Int32, flag);
db.AddOutParameter(dbCom, "@CurrentID", DbType.Int32, 0);
db.ExecuteNonQuery(dbCom);
long mCurrentUid = Convert.ToInt64(db.GetParameterValue(dbCom, "CurrentID").ToString());
return mCurrentUid;
}
catch (Exception ex)
{
return -1;
}
}
public long VerifyUser(HybridDictionary hyLogin)
{
try
{
DbCommand dbCom = db.GetStoredProcCommand("usp_mst_VerifyUser");
db.AddInParameter(dbCom, "@AdminLoginName", DbType.String, hyLogin["AdminLoginName"]);
db.AddInParameter(dbCom, "@AdminPassword", DbType.String, hyLogin["AdminPassword"]);
db.AddOutParameter(dbCom, "@CurrentUID", DbType.Int64, 0);
db.ExecuteNonQuery(dbCom);
long mCurrentUid = long.Parse(db.GetParameterValue(dbCom, "CurrentUID").ToString());
return mCurrentUid;
}
catch (Exception ex)
{
return -1;
}
}
#region "Method"
public static SqlHelper Instance
{
get
{
return instance;
}
}
public DataTable ExecuteDataTable(string mQuery)
{
DbCommand cmdDataSet = db.GetSqlStringCommand(mQuery);
DataSet ds = db.ExecuteDataSet(cmdDataSet);
return ds.Tables[0];
}
public Int32 ExecuteQuery(string mQuery)
{
DbCommand dbCommand = db.GetSqlStringCommand(mQuery);
return Convert.ToInt32(db.ExecuteNonQuery(dbCommand));
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using OnDemand.ObjectModel.Managers;
using OnDemand.ObjectModel.Models;
namespace ClientService.Controllers
{
[Route("api/items")]
public class ItemController : Controller
{
private IClientsRepository _clientsRepo { get; set; }
public ItemController(IClientsRepository clientsRepository)
{
_clientsRepo = clientsRepository;
}
[Route("new")]
[HttpPost]
public async Task<Client> Create(string clientId, string name)
{
var item = new InsuredItem()
{
Name = name,
IsInsured = false
};
var client = await _clientsRepo.Get(clientId);
if (client.Items == null)
{
client.Items = new List<InsuredItem>();
}
client.Items.Add(item);
await _clientsRepo.Update(clientId, client);
return client;
}
[Route("protect")]
[HttpPost]
public async Task<StatusCodeResult> ChangeInsurance(string clientId, string itemId)
{
var client = await _clientsRepo.Get(clientId);
var item = client.Items.FirstOrDefault(c => c.Id == itemId);
if (item == null)
{
return StatusCode(404);
}
if (item.IsInsured)
{
var period = DateTime.UtcNow - item.StartInsuredAt;
var totalHours = Convert.ToDecimal(Math.Ceiling(period.TotalHours));
client.PaymentInformation.Amount -= totalHours * item.InsuredCost;
item.IsInsured = false;
}
else
{
item.IsInsured = true;
item.StartInsuredAt = DateTime.UtcNow;
}
await _clientsRepo.Update(clientId, client);
return StatusCode(200);
}
}
}
|
using AbiokaScrum.Authentication;
using System;
namespace AbiokaScrum.Api.Authentication
{
public class Context
{
private static readonly string contextName = "_AbiokaContext_";
public Context() {
ContextHolder.SetData(contextName, this);
}
public ICustomPrincipal Principal { get; set; }
public static Context Current {
get {
object obj = ContextHolder.GetData(contextName);
if (obj == null) {
throw new ApplicationException("Abioka context is empty");
}
return (Context)obj;
}
}
}
} |
using System.Collections.Generic;
using Audiotica.Data.Collection.SqlHelper;
namespace Audiotica.Data.Collection.Model
{
public class Artist : BaseEntry
{
public Artist()
{
Songs = new List<Song>();
Albums = new List<Album>();
}
public string ProviderId { get; set; }
public string Name { get; set; }
public List<Song> Songs { get; set; }
public List<Album> Albums { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectEuler25
{
class Program
{
static void Main(string[] args)
{
//What is the first term in the Fibonacci sequence to contain 1000 digits?
UInt64 a = 1;
UInt64 b = 1;
UInt64 temp;
double max = Math.Pow(10, 999);
while (b <= max)
{
temp = a + b;
a = b;
b = temp;
}
Console.WriteLine(a+b);
Console.ReadLine();
}
}
} |
namespace AutoTests.Framework.TestData.Entities
{
public class ResourceFileLocation
{
public string Directory { get; }
public string Extension { get; }
public ResourceFileLocation(string directory, string extension)
{
Directory = directory;
Extension = extension;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace CourseHunter_58_Params
{
public class Calculator
{
public double Average (int[] numbers)
{
double summ = 0;
foreach (var item in numbers)
{
summ += item;
}
return summ / numbers.Length;
}
public double Average2 (params int[] numbers)
{
double summ = 0;
foreach (var item in numbers)
{
summ += item;
}
return summ / numbers.Length;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.InteropServices;
namespace PROnline.Src
{
public class SMS
{
[DllImport("sms.dll", EntryPoint = "Sms_Connection")]
public static extern uint Sms_Connection(string CopyRight, uint Com_Port, uint Com_BaudRate, out string Mobile_Type, out string CopyRightToCOM);
[DllImport("sms.dll", EntryPoint = "Sms_Disconnection")]
public static extern uint Sms_Disconnection();
[DllImport("sms.dll", EntryPoint = "Sms_Send")]
public static extern uint Sms_Send(string Sms_TelNum, string Sms_Text);
[DllImport("sms.dll", EntryPoint = "Sms_Receive")]
public static extern uint Sms_Receive(string Sms_Type, out string Sms_Text);
[DllImport("sms.dll", EntryPoint = "Sms_Delete")]
public static extern uint Sms_Delete(string Sms_Index);
[DllImport("sms.dll", EntryPoint = "Sms_AutoFlag")]
public static extern uint Sms_AutoFlag();
[DllImport("sms.dll", EntryPoint = "Sms_NewFlag")]
public static extern uint Sms_NewFlag();
public static int Connect()
{
String TypeStr = "";
String CopyRightToCOM = "";
String CopyRightStr = "//上海迅赛信息技术有限公司,网址www.xunsai.com//";
uint comNum = (uint)MvcApplication.SMSCom;
uint status = Sms_Connection(CopyRightStr, comNum, 9600, out TypeStr, out CopyRightToCOM);
return (int)status;
}
public static string SendMessage(string sPhoneNum, string sContent)
{
try
{
if (MvcApplication.SMSStatus == 1)
{
if(Sms_Send(sPhoneNum, sContent)==1){
return "发送成功";
}
else{
return "发送失败";
}
}
else
{
return "短信猫未连接";
}
}
catch
{
return "发送失败";
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using NewRimLiqourProject.Migrations;
namespace RimLiqourProject.Models
{
[Bind(Exclude = "ProductID")]
public class Products
{
[Key]
[ScaffoldColumn(false)]
public int ProductID { get; set; }
public byte[] Image {get; set; }
[Display(Name = "Product Name")]
public string ProductName { get; set; }
[Display(Name = "Product Type")]
public string Type { get; set; }
[Display(Name = "Size")]
public decimal Size { get; set; }
[Display(Name = "Price")]
public decimal Price { get; set; }
[Display(Name = "Quantity")]
public int Quantity { get; set; }
}
} |
using System;
using System.Collections.Generic;
namespace Generic.Data.Models
{
public partial class TblPaymentRequestDetails
{
public int PayReqDetId { get; set; }
public int PayReqMasterId { get; set; }
public string Description { get; set; }
public string GlaccountCode { get; set; }
public decimal Amount { get; set; }
public decimal TotalAmount { get; set; }
public string AmountInWords { get; set; }
public string PreparedBy { get; set; }
public DateTime Pbdate { get; set; }
public string Pbsignature { get; set; }
public string CheckedBy { get; set; }
public DateTime Cbdate { get; set; }
public string Cbsignature { get; set; }
public string ApprovedBy { get; set; }
public DateTime Abdate { get; set; }
public string Absignature { get; set; }
public virtual TblPaymentRequestMaster PayReqMaster { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightingBook.Tests.Api.Dto.Dto.GetItinerary.Response.Hotel
{
public class Hotel
{
public Location Location { get; set; }
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<Policy> Policy { get; set; }
public List<Passenger> Passengers { get; set; }
public string Identifier { get; set; }
public string ItineraryIdentifier { get; set; }
}
}
|
namespace HT.Framework.AI
{
/// <summary>
/// A*搜寻规则
/// </summary>
public abstract class AStarRule
{
/// <summary>
/// 应用规则
/// </summary>
public abstract void Apply(AStarNode node);
}
}
|
using System;
using System.Html;
using System.Net;
using jQueryApi;
using SportsLinkScript.Shared;
using System.Serialization;
using System.Collections;
using SportsLinkScript.Pages;
namespace SportsLinkScript.Controls
{
public class Calendar : PotentialOffers
{
public Calendar(Element element)
: base(element)
{
this.ServiceName = "Calendar";
}
}
}
|
using Properties.Core.Interfaces;
using Properties.Core.Objects;
namespace Properties.Infrastructure.Data.Mappers
{
public class VideoMapper : IMapToExisting<Video,Video>
{
public bool Map(Video source, Video target)
{
target.MarkClean();
target.VideoType = source.VideoType;
target.VideoUrl = source.VideoUrl;
return target.IsDirty;
}
}
}
|
using RLNET;
namespace ConsoleApp6.Core
{
public static class Colors
{
public static RLColor FloorBackground = RLColor.Black;
public static RLColor Floor = Swatch.DbVegetation;
public static RLColor FloorBackgroundFov = Swatch.DbDark;
public static RLColor FloorFov = Swatch.DbGrass;
public static RLColor WallBackground = Swatch.SecondaryDarkest;
public static RLColor Wall = Swatch.Secondary;
public static RLColor WallBackgroundFov = Swatch.SecondaryDarker;
public static RLColor WallFov = Swatch.DbStone;
public static RLColor DoorBackground = Swatch.ComplimentDarkest;
public static RLColor Door = Swatch.ComplimentLighter;
public static RLColor DoorBackgroundFov = Swatch.ComplimentDarker;
public static RLColor DoorFov = Swatch.ComplimentLightest;
public static RLColor StairsBackground = Swatch.AlternateDarkest;
public static RLColor Stairs = Swatch.DbWood;
public static RLColor StairsBackgroundFov = Swatch.AlternateDarker;
public static RLColor StairsFov = Swatch.DbBrightWood;
public static RLColor TextHeading = RLColor.White;
public static RLColor Text = Swatch.DbLight;
public static RLColor Gold = Swatch.DbSun;
public static RLColor Player = Swatch.DbSkin;
public static RLColor KoboldColor = Swatch.DbBrightWood;
public static RLColor GoblinColor = Swatch.DbGrass;
public static RLColor SlimeColor = Swatch.DbDeepWater;
}
}
|
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;
namespace Caesar_Cipher_Algorithm_By_Csharp
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
}
private void ovalPictureBox2_Click(object sender, EventArgs e)
{
MessageError.Text = " ";
List<string> messageEncrpto = new List<string>();
List<char> alphbet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToLower().ToList<char>();
//store the message
string message = textBox1.Text;
//check if the message is empty or not
if (String.IsNullOrEmpty(message))
{
MessageError.Text = "Please enter string";
return;
}
int increment = 0;
//store the increment
if (textBox2.Text != null)
{
increment = Convert.ToInt32(textBox2.Text);
}
//check the number is vaild or not
if(increment > 25 || increment <= 0)
{
MessageError.Text = "Please enter number between 1 and 25";
return;
}
//convert the message to lower case
message = message.ToLower();
//split the meesage by whitespace
string[] words = message.Split(null);
string[] words_encrypto = new string[words.Length];
for(int j = 0; j < words.Length; j++)
{
//convert string to arrays of chars
char[] arr = words[j].ToCharArray();
char[] arr_encrypto = new char[arr.Length];
for(int i = 0; i < arr.Length; i++)
{
if (!alphbet.Contains(arr[i]))
{
MessageError.Text = "Please enter only alphbet from a to z ";
return;
}
int newIndex = alphbet.IndexOf(arr[i]) + increment;
if (newIndex >= 26)
{
newIndex = newIndex - 26;
arr_encrypto[i] = alphbet[newIndex];
}
else
{
arr_encrypto[i] = alphbet[newIndex];
}
}
//add every word after encrypto
words_encrypto[j] = new string(arr_encrypto);
}
//display the result
label2.Text = string.Join(" ", words_encrypto);
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
|
using System.Collections;
using UnityEngine;
namespace Assets.Scripts.Ui
{
public class View : MonoBehaviour
{
public bool IsShowing { get; protected set; }
protected GameManager GameManager;
public virtual void Init(GameManager gameManager)
{
GameManager = gameManager;
}
public virtual void Show()
{
gameObject.SetActive(true);
IsShowing = true;
}
public virtual IEnumerator ShowDelay(float delayTime)
{
IsShowing = true;
yield return new WaitForSeconds(delayTime);
gameObject.SetActive(true);
}
public virtual void Hide()
{
gameObject.SetActive(false);
IsShowing = false;
}
public void HideImmediately()
{
gameObject.SetActive(false);
IsShowing = false;
}
public virtual void UpdateView()
{
}
public virtual void Destroyed()
{
}
void OnDestroy()
{
Destroyed();
}
}
}
|
using System;
using System.Windows.Forms.VisualStyles;
using Autofac;
using Tests.Pages.ActionID;
using Framework.Core.Common;
using NUnit.Framework;
using Tests.Data.Oberon;
using Tests.Pages.Oberon.Contact;
using Tests.Pages.Oberon.CustomFields;
using Tests.Pages.Oberon.Dashboard;
using OpenQA.Selenium;
namespace Tests.Projects.Oberon.Contact
{
public class CanCreateIndividualWithCustomFields : BaseTest
{
private Driver Driver { get { return Scope.Resolve<Driver>(); }}
public static long TenantId;
public string SingleLineTextLabel;
public string ParagraphTextLabel;
public string SingleCheckBoxLabel;
public string NumberLabel;
public string CurrentyLabel;
public string DatePickerLabel;
[Test]
//[Ignore]
[Category("oberon"), Category("oberon_smoketest"), Category("oberon_contact"), Category("oberon_custom_fields"), Category("oberon_PRODUCTION")]
public void CanCreateIndividualWithCustomFieldsTest()
{
var actionIdLogin = Scope.Resolve<ActionIdLogIn>();
actionIdLogin.LogInTenant();
SingleLineTextLabel = "input-" + FakeData.RandomLetterString(15);
ParagraphTextLabel = "textarea-" + FakeData.RandomLetterString(15);
SingleCheckBoxLabel = "chkbx-" + FakeData.RandomLetterString(15);
NumberLabel = "num-" + FakeData.RandomLetterString(15);
CurrentyLabel = "curr-" + FakeData.RandomLetterString(15);
DatePickerLabel = "date-" + FakeData.RandomLetterString(15);
const int min = 1;
const int max = 999;
// create custom data fields
var fields = Scope.Resolve<CustomFields>();
fields.CreateSingleLineText(SingleLineTextLabel);
fields.CreateParagraphText(ParagraphTextLabel);
fields.CreateSingleCheckbox(SingleCheckBoxLabel);
fields.CreateNumber(NumberLabel, min, max);
fields.CreateCurrency(CurrentyLabel, min, max);
fields.CreateDatePicker(DatePickerLabel);
// create contact
var contact = Scope.Resolve<ContactCreate>();
string firstName = FakeData.RandomLetterString(1).ToUpper() + FakeData.RandomLetterString(9);
string lastName = FakeData.RandomLetterString(1).ToUpper() + FakeData.RandomLetterString(9);
contact.GoToPage();
contact.SetContactName(firstName, lastName);
// enter text into custom data fields
string singleLineTextToEnter = FakeData.RandomLetterString(15);
string paragraphTextToEnter = FakeData.RandomLetterString(15);
const bool singleCheckBoxClick = true;
string currencyTextToEnter = FakeData.RandomNumberInt(min, max).ToString();
string numberTextToEnter = FakeData.RandomNumberInt(min, max).ToString();
string datePickerDateToEnter = DateTime.Now.ToString("M/dd/yy");
string datePickerDateOutcome = DateTime.Now.ToString("MM/dd/yyyy");
contact.ExpandCustomContactFieldSection();
contact.SetCustomFieldSingleLineText(SingleLineTextLabel, singleLineTextToEnter);
contact.SetCustomFieldParagraphText(ParagraphTextLabel, paragraphTextToEnter);
contact.SetCustomFieldSingleCheckBox(singleCheckBoxClick, SingleCheckBoxLabel, FakeData.RandomLetterString(15));
contact.SetCustomFieldNumber(NumberLabel, numberTextToEnter);
contact.SetCustomFieldCurrency(CurrentyLabel, currencyTextToEnter);
contact.SetCustomFieldDatePicker(DatePickerLabel, datePickerDateToEnter);
contact.ClickSectionTitleCreateButton();
var detailPage = Scope.Resolve<ContactDetail>();
detailPage.WaitForSectionTitle();
// verify text entered into custom date fields on details page
var details = Scope.Resolve<ContactDetail>();
Driver.Click(details.CustomContactFieldsExpander);
//details.CustomContactFieldsExpander.Click();
Assert.IsTrue(details.VerifyCustomContactFields("Single Check Box", SingleCheckBoxLabel, null));
Assert.IsTrue(details.VerifyCustomContactFields(SingleLineTextLabel, singleLineTextToEnter));
Assert.IsTrue(details.VerifyCustomContactFields(ParagraphTextLabel, paragraphTextToEnter));
Assert.IsTrue(details.VerifyCustomContactFields(NumberLabel, numberTextToEnter + ".00"));
Assert.IsTrue(details.VerifyCustomContactFields(CurrentyLabel, "$" + currencyTextToEnter + ".00"));
Assert.IsTrue(details.VerifyCustomContactFields(DatePickerLabel, datePickerDateOutcome));
// delete contact
details.ClickDeleteLink();
//DB clean up
// delete custom fields
TenentDbSqlAccess.RemoveContactCustomField(TenantId, SingleLineTextLabel);
TenentDbSqlAccess.RemoveContactCustomField(TenantId, ParagraphTextLabel);
TenentDbSqlAccess.RemoveContactCustomField(TenantId, SingleCheckBoxLabel);
TenentDbSqlAccess.RemoveContactCustomField(TenantId, NumberLabel);
TenentDbSqlAccess.RemoveContactCustomField(TenantId, CurrentyLabel);
TenentDbSqlAccess.RemoveContactCustomField(TenantId, DatePickerLabel);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCode
{
/// <summary>
/// 各种排序算法
/// </summary>
class Sort
{
//static void Main(string[] args)
//{
// int[] arr = { 5, 7, 1, 8, 4 };
// //maopao(arr);
// //xuanzhe(arr);
// //charu(arr);
// quick(arr, 0, arr.Length - 1);
// for (int i = 0; i < arr.Length; i++)
// {
// Console.Write(arr[i]);
// }
//}
// 快速
public static void quick(int[] arr, int left, int right) {
if (left < right) {
int key = arr[left];
int low = left;
int high = right;
while (low < high) {
//右
while (high > low && arr[high] > key) {
high--;
}
arr[low] = arr[high];
//左
while (low < high && arr[low] < key) {
low++;
}
arr[high] = arr[low];
}
arr[low] = key;
quick(arr, left, low);
quick(arr, low + 1, right);
}
}
//选择
public static void xuanzhe(int[] arr) {
for (int i = 0; i < arr.Length; i++) {
for (int j = i + 1; j < arr.Length; j++) {
if (arr[j] < arr[i])
{
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
}
}
//插入
public static void charu(int[] arr)
{
for (int i = 1; i < arr.Length; i++) {
int cur = i;
for (int j = i-1; j > 0; j--) {
if (arr[cur] < arr[j])
{
int t = arr[cur];
arr[cur] = arr[j];
arr[j] = t;
cur--;
}
else break;
}
}
}
//冒泡
public static void maopao(int[] arr) {
for (int i = 0; i < arr.Length-1; i++) {
for (int j = 0; j < arr.Length-1; j++) {
if (arr[j] > arr[j + 1]) {
int t = arr[j];
arr[j] = arr[j+1];
arr[j + 1] = t;
}
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner1 : MonoBehaviour
{
public GameObject Jeep;
public Semaforo semaforo;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("GenerarCarro", 1, 2);
}
// Update is called once per frame
void Update()
{
}
void GenerarCarro()
{
if (semaforo.Semaforoverde)
{
Instantiate(Jeep, transform.position, Quaternion.identity);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raven.Client.Embedded;
using Raven.Client;
using DemoApp.Persistence.Common;
namespace DemoApp.Persistence.RavenDB
{
/// <summary>
/// I decided to use RavenDB instead of SQL, to save people having to have SQL Server, and also
/// it just takes less time to do with Raven. This is ALL the CRUD code. Simple no?
///
/// Thing is the IDatabaseAccessService and the items it persists could easily be applied to helper methods that
/// use StoredProcedures or ADO code, the data being stored would be exactly the same. You would just need to store
/// the individual property values in tables rather than store objects.
/// </summary>
public class DatabaseAccessService : IDatabaseAccessService
{
EmbeddableDocumentStore documentStore = null;
public DatabaseAccessService()
{
documentStore = new EmbeddableDocumentStore
{
DataDirectory = "Data"
};
documentStore.Initialize();
}
public void DeleteConnection(int connectionId)
{
using (IDocumentSession session = documentStore.OpenSession())
{
IEnumerable<Connection> conns = session.Query<Connection>().Where(x => x.Id == connectionId);
foreach (var conn in conns)
{
session.Delete<Connection>(conn);
}
session.SaveChanges();
}
}
public void DeletePersistDesignerItem(int persistDesignerId)
{
using (IDocumentSession session = documentStore.OpenSession())
{
IEnumerable<PersistDesignerItem> persistItems = session.Query<PersistDesignerItem>().Where(x => x.Id == persistDesignerId);
foreach (var persistItem in persistItems)
{
session.Delete<PersistDesignerItem>(persistItem);
}
session.SaveChanges();
}
}
public void DeleteSettingDesignerItem(int settingsDesignerItemId)
{
using (IDocumentSession session = documentStore.OpenSession())
{
IEnumerable<SettingsDesignerItem> settingItems = session.Query<SettingsDesignerItem>().Where(x => x.Id == settingsDesignerItemId);
foreach (var settingItem in settingItems)
{
session.Delete<SettingsDesignerItem>(settingItem);
}
session.SaveChanges();
}
}
public int SaveDiagram(DiagramItem diagram)
{
return SaveItem(diagram);
}
public int SavePersistDesignerItem(PersistDesignerItem persistDesignerItemToSave)
{
return SaveItem(persistDesignerItemToSave);
}
public int SaveSettingDesignerItem(SettingsDesignerItem settingsDesignerItemToSave)
{
return SaveItem(settingsDesignerItemToSave);
}
public int SaveGroupingDesignerItem(GroupDesignerItem groupDesignerItemToSave)
{
return SaveItem(groupDesignerItemToSave);
}
public int SaveConnection(Connection connectionToSave)
{
return SaveItem(connectionToSave);
}
public IEnumerable<DiagramItem> FetchAllDiagram()
{
using (IDocumentSession session = documentStore.OpenSession())
{
return session.Query<DiagramItem>().ToList();
}
}
public DiagramItem FetchDiagram(int diagramId)
{
using (IDocumentSession session = documentStore.OpenSession())
{
return session.Query<DiagramItem>().Single(x => x.Id == diagramId);
}
}
public PersistDesignerItem FetchPersistDesignerItem(int settingsDesignerItemId)
{
using (IDocumentSession session = documentStore.OpenSession())
{
return session.Query<PersistDesignerItem>().Single(x => x.Id == settingsDesignerItemId);
}
}
public SettingsDesignerItem FetchSettingsDesignerItem(int settingsDesignerItemId)
{
using (IDocumentSession session = documentStore.OpenSession())
{
return session.Query<SettingsDesignerItem>().Single(x => x.Id == settingsDesignerItemId);
}
}
public GroupDesignerItem FetchGroupingDesignerItem(int groupDesignerItemId)
{
using (IDocumentSession session = documentStore.OpenSession())
{
return session.Query<GroupDesignerItem>().Single(x => x.Id == groupDesignerItemId);
}
}
public Connection FetchConnection(int connectionId)
{
using (IDocumentSession session = documentStore.OpenSession())
{
return session.Query<Connection>().Single(x => x.Id == connectionId);
}
}
private int SaveItem(PersistableItemBase item)
{
using (IDocumentSession session = documentStore.OpenSession())
{
session.Store(item);
session.SaveChanges();
}
return item.Id;
}
}
}
|
namespace Igorious.StardewValley.ShowcaseMod.Core
{
public sealed class DepthProvider
{
private float _initialDepth;
private readonly float _step;
public DepthProvider(float initialDepth, float step = 0.0000001f)
{
_initialDepth = initialDepth;
_step = step;
}
public float GetDepth()
{
var result = _initialDepth;
_initialDepth += _step;
return result;
}
}
} |
using System;
using System.IO;
namespace Wheel.Util.FileSystem
{
/// <summary>
/// Utilitario de reflexión de WheelFramework.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
public static class FileSystemUtil
{
/// <summary>
/// Obtiene el directorio de la aplicación actual (la que lo invoca).
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
public static string RutaActual { get { return AppDomain.CurrentDomain.BaseDirectory; } }
/// <summary>
/// Obtiene el valor que indica se debe reemplazar por la ruta actual.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
public static string RUTA_AUTOMATICA { get { return "[Auto]"; } }
/// <summary>
/// Obtiene el valor que indica se debe reemplazar por el separador de carpetas del sistema operativo actual.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
public static string SEPARADOR_CARPETAS { get { return "[DS]"; } }
/// <summary>
/// Obtiene el valor que indica se debe reemplazar por la ruta actual.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
public static string RUTA_ACTUAL { get { return "[RutaActual]"; } }
/// <summary>
/// Obtiene el valor que indica se debe reemplazar por en nombre de archivo indicado.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
public static string NOMBRE_ARCHIVO { get { return "[FileName]"; } }
/// <summary>
/// Comprueba si un archivo existe en el sistema de archivos del sistema Windows.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
/// <param name="ruta">Ruta completa del archivo en el sistema.</param>
/// <returns><value>true</value> de encontrarlo, o <value>false</value> de lo contrario.</returns>
public static bool Existe(string ruta)
{
ruta = ObtenerRutaAbsoluta(ruta);
return File.Exists(ruta);
}
/// <summary>
/// Comprueba si un archivo a sido modificado, según la fecha de última modificación especificada.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
/// <param name="fechaUltimaModificacion">Fecha de última modificación.</param>
/// <param name="ruta">Ruta completa del archivo en el sistema.</param>
/// <returns><value>true</value> de haber sido modificado, o <value>false</value> de lo contrario.</returns>
/// <exception cref="FileNotFoundException">Lanzada al no encontrar el archivo en el sistema.</exception>
public static bool FueModificado(DateTime fechaUltimaModificacion, string ruta)
{
ruta = ObtenerRutaAbsoluta(ruta);
if (!Existe(ruta)) throw new FileNotFoundException("¡No se encuentra archivo en el sistema!", ruta);
return fechaUltimaModificacion < ObtenerFechaUltimaModificacion(ruta);
}
/// <summary>
/// Obtiene la fecha de última modificación del archivo al que representa la instancia actual.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
/// <param name="ruta">Ruta completa del archivo en el sistema.</param>
/// <returns>Fecha y hora de última modificación.</returns>
/// <exception cref="FileNotFoundException">Lanzada al no encontrar el archivo en el sistema.</exception>
public static DateTime ObtenerFechaUltimaModificacion(string ruta)
{
ruta = ObtenerRutaAbsoluta(ruta);
if (!Existe(ruta)) throw new FileNotFoundException("¡No se encuentra archivo en el sistema!", ruta);
return File.GetLastWriteTime(ruta);
}
/// <summary>
/// Obtiene la ruta de una archivo de manera automática o manual, según el valor de la ruta.
/// De ser el valor de ruta igual al valor de RUTA_AUTOMATICA, se busca la ruta actual y se añade el nombre del archivo.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
/// <exception cref="FileNotFoundException">Lanzada en caso que no exista el archivo en la ruta final.</exception>
/// <param name="ruta">Ruta del archivo.</param>
/// <param name="nombreArchivo">Nombre del archivo.</param>
/// <returns>Ruta final del archivo solicitado.</returns>
public static string ObtenerRutaArchivo(string ruta, string nombreArchivo)
{
string retorno = ObtenerRutaAbsoluta(ruta);
if (retorno != null)
{
bool agregarNombreArchivo = false;
if (retorno.Trim().Equals(RUTA_AUTOMATICA, StringComparison.InvariantCultureIgnoreCase))
{
agregarNombreArchivo = true;
}
retorno = retorno.Replace(RUTA_AUTOMATICA, AppDomain.CurrentDomain.BaseDirectory);
retorno = retorno.Replace(NOMBRE_ARCHIVO, nombreArchivo);
if (agregarNombreArchivo)
{
if (retorno[retorno.Length - 1] != Path.DirectorySeparatorChar)
{
retorno += Path.DirectorySeparatorChar;
}
retorno += nombreArchivo;
}
while (retorno[retorno.Length - 1] == Path.DirectorySeparatorChar) retorno = retorno.Substring(0, retorno.Length - 1);
}
return retorno;
}
/// <summary>
/// Obtiene la ruta de una archivo de manera automática o manual, según el valor de la ruta.
/// De ser el valor de ruta igual al valor de RUTA_AUTOMATICA, se busca la ruta actual y se añade el nombre del archivo.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
/// <exception cref="FileNotFoundException">Lanzada en caso que no exista el archivo en la ruta final.</exception>
/// <param name="ruta">Ruta del archivo.</param>
/// <param name="nombreArchivo">Nombre del archivo.</param>
/// <returns>Ruta final del archivo solicitado.</returns>
public static string ObtenerRutaArchivoExistente(string ruta, string nombreArchivo)
{
string retorno = ObtenerRutaArchivo(ruta, nombreArchivo);
if (!Existe(retorno))
{
throw new FileNotFoundException(string.Format("¡No se ha encontrado el archivo solicitado en {0}!", retorno), retorno);
}
return retorno;
}
/// <summary>
/// Comprueba si un archivo existe. Lanza una excepción si no existe el archivo en la ruta especificada.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
/// <exception cref="FileNotFoundException">Lanzada en caso que no exista el archivo en la ruta especificada.</exception>
/// <param name="ruta">Ruta del archivo a comprobar.</param>
public static void ComprobarExistenciaArchivo(string ruta)
{
ruta = ObtenerRutaAbsoluta(ruta);
if (!Existe(ruta))
{
throw new FileNotFoundException(string.Format("¡El archivo {} no existe!", ruta), ruta);
}
}
/// <summary>
/// Comprueba la existencia de cada subdirectorio de la ruta. De no existir una carpeta, la crea.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
/// <param name="ruta">Ruta a preparar.</param>
public static void PrepararDirectorio(string ruta)
{
ruta = ObtenerRutaAbsoluta(ruta);
string[] rutaSplit = ruta.Split(Path.DirectorySeparatorChar);
string rutaAux = rutaSplit[0];
for (int i = 1; i < rutaSplit.Length; i++)
{
rutaAux += Path.DirectorySeparatorChar + rutaSplit[i];
if (rutaSplit[i].Contains(".")) break;
if (i != 0)
{
DirectoryInfo info = new DirectoryInfo(rutaAux);
if (!info.Exists)
{
info.Create();
}
}
}
}
/// <summary>
/// Obtiene la ruta absoluta a partir de una ruta relativa, paramétrica o una combinación de ambas.
/// </summary>
/// <example>
/// RutaActual = "C:\Ruta\de\ejemplo".
///
/// Ruta relativa:
/// ObtenerRutaAbsoluta(RutaActual,"../a.txt");
/// Retorno:
/// "C:\Ruta\de\a.txt"
///
/// Ruta Paramétrica:
/// ObtenerRutaAbsoluta(RutaActual,"[RutaActual][DS]a.txt");
/// Retorno:
/// "C:\Ruta\de\ejemplo\a.txt"
///
/// Ruta combinada:
/// ObtenerRutaAbsoluta(RutaActual,"[RutaActual]/../a.txt");
/// Retorno:
/// "C:\Ruta\de\a.txt"
///
/// </example>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
/// <param name="rutaReferencial">Ruta de referencia para realizar la evaluación. Generalmente la ruta actual.</param>
/// <param name="ruta">Ruta ralativa, paramétrica o una combinación.</param>
/// <returns>Ruta absoluta solicitada.</returns>
public static string ObtenerRutaAbsoluta(string rutaReferencial, string ruta)
{
string retorno = null;
if (rutaReferencial != null && ruta != null)
{
if (!string.IsNullOrEmpty(Path.GetExtension(rutaReferencial)))
{
rutaReferencial = Path.GetDirectoryName(rutaReferencial);
}
}
if (rutaReferencial != null && ruta != null && ruta.Contains(RUTA_ACTUAL))
{
ruta = ruta.Replace(RUTA_ACTUAL, ".");
}
if (rutaReferencial == null && ruta != null && !ruta.Contains(RUTA_ACTUAL))
{
rutaReferencial = RutaActual;
}
if (ruta == null)
{
retorno = rutaReferencial;
}
if (rutaReferencial == null)
{
retorno = ruta;
}
if (rutaReferencial != null && ruta != null)
{
retorno = Path.Combine(rutaReferencial, ruta);
retorno = retorno.Replace(RUTA_ACTUAL, RutaActual)
.Replace(SEPARADOR_CARPETAS, Path.DirectorySeparatorChar.ToString());
retorno = Path.GetFullPath(retorno);
return retorno;
}
if (retorno != null)
{
retorno = retorno.Replace(RUTA_ACTUAL, RutaActual)
.Replace(SEPARADOR_CARPETAS, Path.DirectorySeparatorChar.ToString());
}
return retorno;
}
/// <summary>
/// Obtiene la ruta absoluta a partir de una ruta relativa, paramétrica o una combinación de ambas.
/// </summary>
/// <example>
/// RutaActual = "C:\Ruta\de\ejemplo".
///
/// Ruta relativa:
/// ObtenerRutaAbsoluta("../a.txt");
/// Retorno:
/// "C:\Ruta\de\a.txt"
///
/// Ruta Paramétrica:
/// ObtenerRutaAbsoluta("[RutaActual][DS]a.txt");
/// Retorno:
/// "C:\Ruta\de\ejemplo\a.txt"
///
/// Ruta combinada:
/// ObtenerRutaAbsoluta("[RutaActual]/../a.txt");
/// Retorno:
/// "C:\Ruta\de\a.txt"
///
/// </example>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
/// <param name="ruta">Ruta ralativa, paramétrica o una combinación.</param>
/// <returns>Ruta absoluta solicitada.</returns>
public static string ObtenerRutaAbsoluta(string ruta)
{
return ObtenerRutaAbsoluta(RutaActual, ruta);
}
/// <summary>
/// Determina si una ruta corresponde a un directorio.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
/// <param name="ruta">Ruta a verificar.</param>
/// <returns></returns>
public static bool EsDirectorio(string ruta)
{
ruta = ObtenerRutaAbsoluta(ruta);
return File.GetAttributes(ruta) == FileAttributes.Directory;
}
/// <summary>
/// Determina si una ruta corresponde a un archivo.
/// </summary>
/// <remarks>
/// <para>
/// <h2 class="groupheader">Registro de versiones</h2>
/// <ul>
/// <li>1.0.0</li>
/// <table>
/// <tr style="font-weight: bold;">
/// <td>Autor</td>
/// <td>Fecha</td>
/// <td>Descripción</td>
/// </tr>
/// <tr>
/// <td>Marcos Abraham Hernández Bravo.</td>
/// <td>10/11/2016</td>
/// <td>Versión Inicial.</td>
/// </tr>
/// </table>
/// </ul>
/// </para>
/// </remarks>
/// <param name="ruta">Ruta a verificar.</param>
/// <returns></returns>
public static bool EsArchivo(string ruta)
{
ruta = ObtenerRutaAbsoluta(ruta);
return File.GetAttributes(ruta) == FileAttributes.Archive;
}
}
}
|
using UnityEngine;
public class ThirdPersonCamera : MonoBehaviour
{
public GameObject Target;
public float Distance = 10.0f;
public float Height = 10.0f;
void Update()
{
var pos = Target.transform.position - Target.transform.forward * Distance;
pos.y = Target.transform.position.y + Height;
Camera.main.transform.position = pos;
Camera.main.transform.LookAt( Target.transform, Vector3.up );
}
}
|
using System;
namespace Odev
{
internal class Program
{
private static void Main(string[] args)
{
Products products1 = new Products();
products1.ProductName = "Keyboard";
products1.productPrice = 350;
products1.ProductStockAmount = 150;
Products products2 = new Products();
products2.ProductName = "Mouse";
products2.productPrice = 120;
products2.ProductStockAmount = 80;
Products products3 = new Products();
products3.ProductName = "Monitor";
products3.productPrice = 1500;
products3.ProductStockAmount = 50;
Products[] urunler = new Products[]
{
products1, products2, products3
};
Console.WriteLine("foreach ile");
Console.WriteLine("- - - - - - - - - - - -");
foreach (var urun in urunler)
{
Console.WriteLine($"Ürün Adı : {urun.ProductName} \nÜrün Fiyatı : {urun.productPrice} TL \nÜrün Adedi : {urun.ProductStockAmount}");
}
Console.WriteLine("for ile");
Console.WriteLine("- - - - - - - - - - - -");
for (int i = 0; i < urunler.Length; i++)
{
Console.WriteLine($"Ürün Adı : {urunler[i].ProductName} \nÜrün Fiyatı : {urunler[i].productPrice} TL \nÜrün Adedi : {urunler[i].ProductStockAmount}");
}
Console.WriteLine("while ile");
Console.WriteLine("- - - - - - - - - - - -");
int j = 0;
while (j < urunler.Length)
{
Console.WriteLine($"Ürün Adı : {urunler[j].ProductName} \nÜrün Fiyatı : {urunler[j].productPrice} TL \nÜrün Adedi : {urunler[j].ProductStockAmount}");
j++;
}
}
}
internal class Products
{
public string ProductName { get; set; }
public int productPrice { get; set; }
public int ProductStockAmount { get; set; }
}
} |
using Caelum.Banco.CustomInterfaces;
namespace Caelum.Banco.Contas {
class TotalizadorDeTributos {
public double Total { get; private set; }
public void Acumula(ITributavel conta) {
// Com a Interface garantimos que o objeto passado em conta terá o método CalculaTributo, nesse exemplo
this.Total += conta.CalculaTributo();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Wisp_Health : MonoBehaviour
{
public int health = 3;
private int r = 255;
private float flashTimer = 5;
private float deathTimer = 0;
// Update is called once per frame
void Update()
{
flashTimer += Time.deltaTime;
HitAni();
Death();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "PlayerAttack")
{
health--;
flashTimer = 0;
}
else if (collision.gameObject.tag == "PlayerAttack2")
{
health -= 2;
flashTimer = 0;
}
}
void HitAni()
{
if (flashTimer < .125f)
{
r = 0;
}
else
{
r = 255;
}
GetComponent<SpriteRenderer>().color = new Color(r, 255, 255, 175);
}
void Death()
{
if (health <= 0)
{
deathTimer += Time.deltaTime;
GetComponent<Rigidbody2D>().gravityScale = 1;
GetComponent<Wisp_Movement>().enabled = false;
gameObject.tag = "Untagged";
GetComponent<Animator>().SetBool("isDead", true);
if (deathTimer >= 2 && deathTimer < 2.33)
{
gameObject.tag = "Enemy";
GetComponent<CircleCollider2D>().radius = .7f;
GetComponent<CircleCollider2D>().
transform.localScale = new Vector2(2, 2);
GetComponent<Animator>().SetBool("isExplode", true);
}
else if(deathTimer >= 2.33)
{
Destroy(gameObject);
}
}
}
}
|
using System.Collections.Generic;
using System.Data.Entity;
namespace Common
{
public static class ValidationHelper
{
public static IEnumerable<string> ExtractValidationMessages(DbContext context)
{
var errors = context.GetValidationErrors();
foreach(var error in errors)
{
yield return "Validation error on " + error.Entry.Entity.GetType().FullName + "{" + error.Entry.Entity.ToString() + "}";
foreach(var errorMessage in error.ValidationErrors)
{
yield return "Property " + errorMessage.PropertyName + " " + errorMessage.ErrorMessage;
}
}
}
}
} |
using Backend.Model;
namespace PatientWebAppTests.CreateObjectsForTests
{
public class CreateSurveyResult
{
public SurveyResult CreateInvalidTestObject()
{
return new SurveyResult("Rated item", 7, 1, 0, -3, 4, 0);
}
public SurveyResult CreateValidTestObject()
{
return new SurveyResult("Rated item", 4, 1, 2, 5, 4, 3);
}
}
}
|
using System.Windows;
namespace CODE.Framework.Wpf.Mvvm
{
/// <summary>Indicates that the object implementing this interface can provide a reference to an associated view</summary>
public interface IHaveViewInformation
{
/// <summary>Reference to the associated view object</summary>
UIElement AssociatedView { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace PropertyGridExample.PropertyClasses
{
class PropertyTextField
{
String m_TextField;
[Browsable(true)]
[Description("Example of text field")]
[DisplayName("Text field")]
public String TextField
{
get { return m_TextField; }
set { m_TextField = value; }
}
}
}
|
using BookApi.Application.Services;
using BookApi.Application.ViewModels.Books;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BookApi.Web.Controllers.V1
{
[ApiVersion("1.0")]
public class BooksController : ApiBaseController
{
private readonly IBookService _bookService;
public BooksController(IBookService bookService)
{
_bookService = bookService;
}
[HttpGet]
public async Task<IActionResult> GetAllBooks()
{
return Ok(await _bookService.GetAllBooksAsync());
}
[HttpGet("{id}")]
public async Task<IActionResult> GetBookById(Guid id)
{
return Ok(await _bookService.GetBookByIdAsync(id));
}
[HttpPost]
public async Task<IActionResult> CreateBook([FromBody] BookCreateModel bookModel)
{
return Ok(await _bookService.CreateBookAsync(bookModel));
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateBook(Guid id, [FromBody] BookEditModel bookEdit)
{
bookEdit.Id = id;
return Ok(await _bookService.EditBookAsync(bookEdit));
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteBook(Guid id)
{
return Ok(await _bookService.RemoveBookAsync(id));
}
}
}
|
namespace ForumSystem.Web.Tests.Routes
{
using ForumSystem.Web.Controllers;
using MyTested.AspNetCore.Mvc;
using Xunit;
public class HomeControllerTests
{
[Fact]
public void GetPrivacyShouldBeRoutedCorrectly()
=> MyRouting
.Configuration()
.ShouldMap("/Home/Privacy")
.To<HomeController>(c => c.Privacy());
[Fact]
public void GetErrorShouldBeRoutedCorrectly()
=> MyRouting
.Configuration()
.ShouldMap("/Home/Error")
.To<HomeController>(c => c.Error());
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace PROnline.Models.Service
{
//视讯服务器
public class Servers
{
//服务器ID
public int ServersID { get; set; }
//服务器名称,可以使用学校名称,便于关联
[Display(Name = "服务器名称")]
public String ServerName { get; set; }
//服务器IP
[Display(Name = "服务器IP")]
public String ServerIP { get; set; }
//服务器端口
[Display(Name = "服务器端口")]
public int ServerPort { get; set; }
//是否可用,用于心跳检测
[Display(Name = "是否可用")]
public Boolean IsAvaiable { get; set; }
//备注
[Display(Name = "备注")]
public String Comment { get; set; }
}
} |
using System;
namespace gView.Interoperability.GeoServices.Rest.Reflection
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ServiceMethodAttribute : Attribute
{
public ServiceMethodAttribute(string name, string method)
{
this.Name = name;
this.Method = method;
}
public string Name { get; set; }
public string Method { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using ILogging;
using ServiceDeskSVC.DataAccess;
using ServiceDeskSVC.DataAccess.Models;
using ServiceDeskSVC.Domain.Entities.ViewModels;
namespace ServiceDeskSVC.Managers.Managers
{
public class NSUserManager:INSUserManager
{
private readonly INSUserRepository _nsUserRepository;
private readonly ILogger _logger;
public NSUserManager(INSUserRepository nsUserRepository, ILogger logger)
{
_nsUserRepository = nsUserRepository;
_logger = logger;
}
public List<NSUser_vm> GetUserBySearch(string searchTerm, int numResults)
{
var results = _nsUserRepository.GetUserFromSearch(searchTerm, numResults);
return results.Select(mapEntityToViewModelUser).OrderBy(s => s.FirstName).ThenBy(s2 => s2.LastName).ToList();
}
public List<NSUser_vm> GetAllUsers()
{
var users = _nsUserRepository.GetAllUsers();
return users.Select(mapEntityToViewModelUser).ToList();
}
public NSUser_vm GetUserByUserName(string userName)
{
if(string.IsNullOrEmpty(userName))
{
throw new ArgumentNullException(userName);
}
var user = _nsUserRepository.GetUserByUserName(userName);
return mapEntityToViewModelUser(user);
}
public NSUser_vm GetUserBySID(string sid)
{
if(string.IsNullOrEmpty(sid))
{
throw new ArgumentNullException(sid);
}
var user = _nsUserRepository.GetUserBySID(sid);
return mapEntityToViewModelUser(user);
}
private NSUser_vm mapEntityToViewModelUser(ServiceDesk_Users EFUser)
{
return new NSUser_vm
{
Id = EFUser.Id,
SID = EFUser.SID,
UserName = EFUser.UserName,
FirstName = EFUser.FirstName,
LastName = EFUser.LastName,
EMail = EFUser.EMail,
Department = EFUser.Department.DepartmentName,
Location = EFUser.NSLocation.LocationCity
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace MetaDslx.Core
{
public class ModelList<T> : ModelCollection, IList<T>
where T: class
{
private List<T> items;
public ModelList(ModelObject owner, ModelProperty ownerProperty)
: base(owner, ownerProperty)
{
this.items = new List<T>();
}
public ModelList(ModelObject owner, ModelProperty ownerProperty, IEnumerable<T> values)
: base(owner, ownerProperty)
{
this.items = new List<T>();
foreach (var value in values)
{
this.Add(value);
}
}
public ModelList(ModelObject owner, ModelProperty ownerProperty, IEnumerable<Lazy<object>> values)
: base(owner, ownerProperty)
{
this.items = new List<T>();
foreach (var value in values)
{
this.MLazyAdd(value);
}
}
#region IList<T> Members
public int IndexOf(T item)
{
this.MFlushLazyItems();
return this.items.IndexOf(item);
}
public void Insert(int index, T item)
{
this.MFlushLazyItems();
this.items.Insert(index, item);
this.Owner.MOnAddValue(this.OwnerProperty, item, true);
}
public void RemoveAt(int index)
{
this.MFlushLazyItems();
object item = this.items[index];
this.items.RemoveAt(index);
this.Owner.MOnRemoveValue(this.OwnerProperty, item, true);
}
public T this[int index]
{
get
{
this.MFlushLazyItems();
return this.items[index];
}
set
{
this.MFlushLazyItems();
object item = this.items[index];
this.items[index] = null;
this.Owner.MOnRemoveValue(this.OwnerProperty, item, true);
if (this.items.Contains(value))
{
this.items.RemoveAt(index);
}
else
{
item = value;
this.items[index] = value;
this.Owner.MOnAddValue(this.OwnerProperty, item, true);
}
}
}
#endregion
#region ICollection<T> Members
public void Add(T item)
{
this.MFlushLazyItems();
if (!this.items.Contains(item))
{
this.items.Add(item);
this.Owner.MOnAddValue(this.OwnerProperty, item, true);
}
}
public override void Clear()
{
this.ClearLazyItems();
List<T> oldItems = this.items;
this.items = new List<T>();
foreach (var item in oldItems)
{
this.Owner.MOnRemoveValue(this.OwnerProperty, item, true);
}
}
public bool Contains(T item)
{
this.MFlushLazyItems();
return this.items.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
this.MFlushLazyItems();
this.items.CopyTo(array, arrayIndex);
}
public int Count
{
get
{
this.MFlushLazyItems();
return this.items.Count;
}
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
this.MFlushLazyItems();
if (this.items.Remove(item))
{
this.Owner.MOnRemoveValue(this.OwnerProperty, item, true);
return true;
}
return false;
}
public void RemoveAll(T item)
{
this.MFlushLazyItems();
bool removed = false;
while (this.items.Remove(item))
{
removed = true;
}
if (removed)
{
this.Owner.MOnRemoveValue(this.OwnerProperty, item, true);
}
}
#endregion
#region IEnumerable<T> Members
public new IEnumerator<T> GetEnumerator()
{
this.MFlushLazyItems();
return this.items.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
public void AddRange(IEnumerable<T> collection)
{
this.MFlushLazyItems();
foreach (T item in collection)
{
this.Add(item);
}
}
public override bool MAdd(object item, bool firstCall)
{
this.MFlushLazyItems();
if (!this.items.Contains(item))
{
this.items.Add((T)item);
this.Owner.MOnAddValue(this.OwnerProperty, item, firstCall);
return true;
}
return false;
}
public override bool MRemove(object item, bool firstCall)
{
this.MFlushLazyItems();
if (this.items.Remove((T)item))
{
this.Owner.MOnRemoveValue(this.OwnerProperty, item, firstCall);
return true;
}
return false;
}
public override IEnumerator<object> MGetEnumerator()
{
return this.GetEnumerator();
}
}
public class ModelMultiList<T> : ModelCollection, IList<T>
where T : class
{
private List<T> items;
public ModelMultiList(ModelObject owner, ModelProperty ownerProperty)
: base(owner, ownerProperty)
{
if (ownerProperty.OppositeProperties.Count() > 0)
{
throw new InvalidOperationException("Multi lists cannot have opposite properties.");
}
this.items = new List<T>();
}
public ModelMultiList(ModelObject owner, ModelProperty ownerProperty, IEnumerable<T> values)
: base(owner, ownerProperty)
{
if (ownerProperty.OppositeProperties.Count() > 0)
{
throw new InvalidOperationException("Multi lists cannot have opposite properties.");
}
this.items = new List<T>();
foreach (var value in values)
{
this.Add(value);
}
}
public ModelMultiList(ModelObject owner, ModelProperty ownerProperty, IEnumerable<Lazy<object>> values)
: base(owner, ownerProperty)
{
if (ownerProperty.OppositeProperties.Count() > 0)
{
throw new InvalidOperationException("Multi lists cannot have opposite properties.");
}
this.items = new List<T>();
foreach (var value in values)
{
this.MLazyAdd(value);
}
}
#region IList<T> Members
public int IndexOf(T item)
{
this.MFlushLazyItems();
return this.items.IndexOf(item);
}
public void Insert(int index, T item)
{
this.MFlushLazyItems();
this.items.Insert(index, item);
this.Owner.MOnAddValue(this.OwnerProperty, item, true);
}
public void RemoveAt(int index)
{
this.MFlushLazyItems();
object item = this.items[index];
this.items.RemoveAt(index);
this.Owner.MOnRemoveValue(this.OwnerProperty, item, true);
}
public T this[int index]
{
get
{
this.MFlushLazyItems();
return this.items[index];
}
set
{
this.MFlushLazyItems();
object item = this.items[index];
this.items[index] = null;
this.Owner.MOnRemoveValue(this.OwnerProperty, item, true);
item = value;
this.items[index] = value;
this.Owner.MOnAddValue(this.OwnerProperty, item, true);
}
}
#endregion
#region ICollection<T> Members
public void Add(T item)
{
this.MFlushLazyItems();
this.items.Add(item);
this.Owner.MOnAddValue(this.OwnerProperty, item, true);
}
public override void Clear()
{
this.ClearLazyItems();
List<T> oldItems = this.items;
this.items = new List<T>();
foreach (var item in oldItems)
{
this.Owner.MOnRemoveValue(this.OwnerProperty, item, true);
}
}
public bool Contains(T item)
{
this.MFlushLazyItems();
return this.items.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
this.MFlushLazyItems();
this.items.CopyTo(array, arrayIndex);
}
public int Count
{
get
{
this.MFlushLazyItems();
return this.items.Count;
}
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
this.MFlushLazyItems();
if (this.items.Remove(item))
{
this.Owner.MOnRemoveValue(this.OwnerProperty, item, true);
return true;
}
return false;
}
public void RemoveAll(T item)
{
this.MFlushLazyItems();
while (this.items.Remove(item))
{
this.Owner.MOnRemoveValue(this.OwnerProperty, item, true);
}
}
#endregion
#region IEnumerable<T> Members
public new IEnumerator<T> GetEnumerator()
{
this.MFlushLazyItems();
return this.items.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
public void AddRange(IEnumerable<T> collection)
{
this.MFlushLazyItems();
foreach (T item in collection)
{
this.Add(item);
}
}
public override bool MAdd(object item, bool firstCall)
{
this.MFlushLazyItems();
if (firstCall)
{
this.items.Add((T)item);
this.Owner.MOnAddValue(this.OwnerProperty, item, firstCall);
return true;
}
return false;
}
public override bool MRemove(object item, bool firstCall)
{
this.MFlushLazyItems();
if (firstCall)
{
if (this.items.Remove((T)item))
{
this.Owner.MOnRemoveValue(this.OwnerProperty, item, firstCall);
return true;
}
}
return false;
}
public override IEnumerator<object> MGetEnumerator()
{
return this.GetEnumerator();
}
}
}
|
using System;
namespace algorithmscsharp
{
public class RecursiveMultiplication
{
public static string GetProduct(string number1, string number2)
{
var len1 = number1.Length;
var len2 = number2.Length;
if (len1 <= 1 && len2 <= 1)
{
double.TryParse(number1, out double number1Double);
double.TryParse(number2, out double number2Double);
return (number1Double * number2Double).ToString();
}
var num1MiddleDigitIndex = len1 % 2 == 0 ? len1 / 2 : len1 / 2 + 1;
var num2MiddleDigitIndex = len2 % 2 == 0 ? len2 / 2 : len2 / 2 + 1;
var a = number1.Substring(0, num1MiddleDigitIndex);
var b = number1.Substring(num1MiddleDigitIndex);
var c = number2.Substring(0, num2MiddleDigitIndex);
var d = number2.Substring(num2MiddleDigitIndex);
var ac = GetProduct(a, c);
var bd = GetProduct(b, d);
var bc = GetProduct(b, c);
var ad = GetProduct(a, d);
var acPadded = ac + new string('0', (len1 + len2) / 2);
var bcPadded = bc + new string('0', len2 / 2);
var adPadded = ad + new string('0', len1 / 2);
double.TryParse(acPadded, out double acPaddedDouble);
double.TryParse(bcPadded, out double bcPaddedDouble);
double.TryParse(adPadded, out double adPaddedDouble);
double.TryParse(bd, out double bdDouble);
return (acPaddedDouble + bcPaddedDouble + adPaddedDouble + bdDouble).ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ecom.DataModel;
namespace ECom.Abstraction.Repository
{
interface ICustomerRepository
{
IEnumerable<Customer> GetAllCustomers();
void Add(Customer entity);
void Delete(Customer entity);
Customer Get(int CustomerId);
}
}
|
namespace Sentry.Tests.Infrastructure;
public class DiagnosticLoggerTests
{
[Fact]
public void StripsEnvironmentNewlineFromMessage()
{
var logger = new FakeLogger(SentryLevel.Debug);
logger.LogDebug("Foo" + Environment.NewLine + "Bar" + Environment.NewLine);
Assert.Equal(" Debug: Foo Bar", logger.LastMessageLogged);
}
[Fact]
public void StripsNewlineCharsFromMessage()
{
var logger = new FakeLogger(SentryLevel.Debug);
logger.LogDebug("Foo\nBar\n");
Assert.Equal(" Debug: Foo Bar", logger.LastMessageLogged);
}
[Fact]
public void StripsLinefeedCharsFromMessage()
{
var logger = new FakeLogger(SentryLevel.Debug);
logger.LogDebug("Foo\rBar\r");
Assert.Equal(" Debug: Foo Bar", logger.LastMessageLogged);
}
[Fact]
public void StripsComboCharsFromMessage()
{
var logger = new FakeLogger(SentryLevel.Debug);
logger.LogDebug("Foo\r\nBar\r\n");
Assert.Equal(" Debug: Foo Bar", logger.LastMessageLogged);
}
private class FakeLogger : DiagnosticLogger
{
public FakeLogger(SentryLevel minimalLevel) : base(minimalLevel)
{
}
public string LastMessageLogged { get; private set; }
protected override void LogMessage(string message) => LastMessageLogged = message;
}
}
|
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace CM_App_Creator
{
internal static class NativeMethods
{
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[System.Security.SuppressUnmanagedCodeSecurity]
public static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags);
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
[System.Security.SuppressUnmanagedCodeSecurity]
public static extern bool FreeLibrary(IntPtr hModule);
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[System.Security.SuppressUnmanagedCodeSecurity]
public static extern bool EnumResourceNames(IntPtr hModule, IntPtr lpszType, ENUMRESNAMEPROCA lpEnumFunc, IntPtr lParam);
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[System.Security.SuppressUnmanagedCodeSecurity]
public static extern IntPtr FindResource(IntPtr hModule, IntPtr lpName, IntPtr lpType);
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
[System.Security.SuppressUnmanagedCodeSecurity]
public static extern IntPtr LoadResource(IntPtr hModule, IntPtr hResInfo);
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
[System.Security.SuppressUnmanagedCodeSecurity]
public static extern IntPtr LockResource(IntPtr hResData);
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
[System.Security.SuppressUnmanagedCodeSecurity]
public static extern uint SizeofResource(IntPtr hModule, IntPtr hResInfo);
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
[System.Security.SuppressUnmanagedCodeSecurity]
public static extern IntPtr GetCurrentProcess();
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[System.Security.SuppressUnmanagedCodeSecurity]
public static extern int QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax);
[System.Runtime.InteropServices.DllImport("psapi.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[System.Security.SuppressUnmanagedCodeSecurity]
public static extern int GetMappedFileName(IntPtr hProcess, IntPtr lpv, StringBuilder lpFilename, int nSize);
}
[System.Runtime.InteropServices.UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Winapi, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[System.Security.SuppressUnmanagedCodeSecurity]
internal delegate bool ENUMRESNAMEPROCA(IntPtr hModule, IntPtr lpszType, IntPtr lpszName, IntPtr lParam);
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
namespace WebQz.Repository
{
public class QuestionsRepository : IQuestionsRepository
{
private List<Models.Questions> questions = new();
public QuestionsRepository()
{
try
{
DBConnection.connection.Open();
SqlCommand sqlCommand = new SqlCommand("GetAllQuestions", DBConnection.connection);
sqlCommand.CommandType = CommandType.StoredProcedure;
SqlDataReader dataReader = sqlCommand.ExecuteReader();
if (dataReader.HasRows)
{
while (dataReader.Read())
questions.Add(new Models.Questions()
{
Id = dataReader.GetInt32(0),
TextQ = dataReader.GetString(1),
RightAnswer = dataReader.GetString(2),
Answer1 = dataReader.GetString(3),
Answer2 = dataReader.GetString(4),
Answer3 = dataReader.GetString(5),
Answer4 = dataReader.GetString(6)
});
}
dataReader.Close();
sqlCommand.Dispose();
DBConnection.connection.Close();
}
catch (Exception)
{
DBConnection.connection.Close();
}
}
public List<Models.Questions> GetQuestions() => questions;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public enum orderType
{
per,
mid,
last
}
public class leecodeBstTree : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
BST<int, String> bstTree = new BST<int, string>();
bstTree.put(6, "这是6");
bstTree.put(3, "这是3");
bstTree.put(5, "这是5");
bstTree.put(8, "这是8");
bstTree.put(55, "这是55");
bstTree.put(44, "这是44");
bstTree.put(8, "这是8,又变成了88");
//Debug.Log(bstTree.get(8));
//bstTree.PreOrderRecur(orderType.per);
bstTree.PreOrderRecur(orderType.last);
//bstTree.PreOrderRecur(orderType.last);
}
#region 面试题 04.02. 最小高度树
/*解题思路,使用二分类似的方法,每次取分开的数组的中间一个
* 就是中序遍历,树中序遍历是升序的,所以可以从中间开始构建一个
* 最矮的树
*/
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public TreeNode SortedArrayToBST(int[] nums)
{
if (nums.Length == 0) return null;
return put(0, nums.Length - 1, nums);
}
TreeNode put(int hi, int lo, int[] nums)
{
if (hi > lo) return null;
int mid = (hi + lo) / 2;
var node = new TreeNode(nums[mid]);
node.left = put(hi, mid - 1, nums);
node.right = put(mid + 1, lo, nums);
return node;
}
#endregion
#region 108. 将有序数组转换为二叉搜索树
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public TreeNode SortedArrayToBST2(int[] nums)
{
return sortHelp(nums,0,nums.Length);
}
public TreeNode sortHelp(int[] nums,int lo,int hi)
{
if (lo > hi)
{
return null;
}
int mid = lo + (hi - lo) / 2;
int nodeVal = nums[mid];
TreeNode node = new TreeNode(nodeVal);
node.left = sortHelp(nums, lo, mid-1);
node.right = sortHelp(nums, mid + 1, hi);
return node;
}
#endregion
#region 102. 二叉树的层序遍历
public IList<IList<int>> LevelOrder(TreeNode root)
{
var queueList = new Queue<TreeNode>();
var levelOrder = new List<IList<int>>();
if (root == null)
{
return levelOrder;
}
queueList.Enqueue(root);
while (queueList.Count > 0)
{
int curLsitLen = queueList.Count;
var tempList = new List<int>();
for(int i = 0; i < curLsitLen; i++)
{
var outNode = queueList.Dequeue();
tempList.Add(outNode.val);
if (outNode.left!=null)
queueList.Enqueue(outNode.left);
if(outNode.right!=null)
queueList.Enqueue(outNode.right);
}
levelOrder.Add(tempList);
}
return levelOrder;
}
#endregion
#region 105. 从前序与中序遍历序列构造二叉树
//Hashtable indexMap;
//public TreeNode buildTree(int[] preorder,int []inorder)
//{
// int n = preorder.Length;
// indexMap = new Hashtable();
// for(int i = 0; i < n; i++)
// {
// indexMap.Add(inorder[i],i);
// }
// return myBuildTree(preorder, inorder, 0, n - 1, 0, n - 1);
//}
//private TreeNode myBuildTree(int[] preorder, int[] inorder, int preorder_left, int preorder_right, int inorder_left, int inorder_right)
//{
// if (preorder_left > preorder_right)
// return null;
// int preorder_root = preorder_left;
// int inorder_root = (int)indexMap[preorder[preorder_root]];
// TreeNode root = new TreeNode(preorder[preorder_root]);
// int size_left_subtree = inorder_root - inorder_left;
// root.left = myBuildTree(preorder, inorder, preorder_left + 1, preorder_left + size_left_subtree, inorder_left, inorder_root - 1);
// root.right = myBuildTree(preorder, inorder, preorder_left + size_left_subtree + 1, preorder_right, inorder_root + 1, inorder_right);
// return root;
//}
#endregion
#region 270. 最接近的二叉搜索树值
public int ClosestValue(TreeNode root, double target)
{
double pred = double.MinValue;
Stack<TreeNode> nodeStack = new Stack<TreeNode>();
TreeNode cur = root;
while (nodeStack.Count != 0 || cur != null)
{
while (cur != null)
{
nodeStack.Push(cur);
cur = cur.left;
}
TreeNode node = nodeStack.Pop();
if (target >= pred && target < node.val)
{
return Math.Abs(pred - target) < Math.Abs(node.val - target) ? (int)pred : node.val;
}
pred = node.val;
cur = node.right;
}
return (int)pred;
}
#endregion
#region 236. 二叉树的最近公共祖先
#endregion
#region BST Tree
public class BST<Key,Value> where Key : IComparable
{
internal Node root;
internal class Node
{
internal Key key;
internal Value val;
internal Node left, right;
internal int N;
public Node(Key key,Value val,int N)
{
this.key = key;
this.val = val;
this.N = N;
}
}
#region 树的遍历
public void PreOrderRecur(orderType orderType)
{
if(orderType == orderType.per)
{
PreOrderRecur(root);
PreOrderStack(root);
}
else if(orderType == orderType.mid)
{
MidOrderRecur(root);
MidOrderStack(root);
}
else if(orderType == orderType.last)
{
LastOrderRecur(root);
LastOrderStack_1(root);
LastOrderStack_2(root);
}
}
private void PreOrderRecur(Node x)
{
if (x == null) return;
Debug.Log("前序遍历 " + x.val); ;
PreOrderRecur(x.left);
PreOrderRecur(x.right);
}
private void MidOrderRecur(Node x)
{
if (x == null) return;
MidOrderRecur(x.left);
Debug.Log("中序遍历 " + x.val);
MidOrderRecur(x.right);
}
private void LastOrderRecur(Node x)
{
if (x == null) return;
LastOrderRecur(x.left);
LastOrderRecur(x.right);
Debug.Log("后序遍历 " + x.val);
}
private void PreOrderStack(Node x)
{
Stack<Node> nodeStack = new Stack<Node>();
nodeStack.Push(x);
while (nodeStack.Count != 0)
{
Node curNode = nodeStack.Pop();
Debug.Log("Stack 前序遍历 "+ curNode.val);
if (curNode.right!=null)
{
nodeStack.Push(curNode.right);
}
if (curNode.left != null)
{
nodeStack.Push(curNode.left);
}
}
}
//树的非递归方式中序遍历
//1.空节点 树通过判断当前节点的子节点是否是空节点,来对stack进行pop操作
//2.cur当前节点 当前节点会根据stack的pop操作进行更新,(由于前面会递归,一直会把当前节点更
// 新为没有左节点的子节点,此子节点没有左节点(离开while循环),则会进行pop操作,然后把节点更新为右节点) 此时有2种情况,如果右节点为空则继续pop,更新cur节点(为上一层节点),
// 否则cur会变成右节点,然后继续执行左节点更新递归
private void MidOrderStack(Node x)
{
Stack<Node> nodeStack = new Stack<Node>();
Node cur = x;
while (nodeStack.Count != 0||cur !=null)
{
while (cur != null)
{
nodeStack.Push(cur);
cur = cur.left;
}
Node node = nodeStack.Pop();
Debug.Log("Stack 中序遍历 " + node.val);
cur = node.right;
}
}
private void LastOrderStack_1(Node x)
{
if (x == null) return;
Stack<Node> nodeStack1 = new Stack<Node>();
Stack<Node> nodeStack2 = new Stack<Node>();
Node cur = x;
nodeStack1.Push(x);
while (nodeStack1.Count != 0)
{
cur = nodeStack1.Pop();
if (cur.left != null)
{
nodeStack1.Push(cur.left);
}
if (cur.right != null)
{
nodeStack1.Push(cur.right);
}
nodeStack2.Push(cur);
}
while (nodeStack2.Count != 0)
{
Node node = nodeStack2.Pop();
Debug.Log("树的后序遍历 Stack版本1 ==>" + node.val);
}
}
//1.h 的作用是 阻止C一直向下寻找递归,C判断H不相等之后则会一直走到最后一个循环,然后不断向上pop遍历
//2.Peek 和 Push ,相当于插入后不断拿最新的那个.left一直向下递归
private void LastOrderStack_2(Node x)
{
if (x == null) return;
Stack<Node> nodeStack = new Stack<Node>();
nodeStack.Push(x);
Node c = x;
Node h = null;
while (nodeStack.Count != 0)
{
c = nodeStack.Peek();
if (c.left != null && h != c.left && h != c.right)
{
nodeStack.Push(c.left);
}
else if(c.right !=null && h != c.right){
nodeStack.Push(c.right);
}
else
{
Node node = nodeStack.Pop();
Debug.Log("树的后序遍历 Stack版本2 ==>" + node.val);
h = c;
}
}
}
#endregion
public int Size()
{
return size(root);
}
private int size(Node x )
{
if (x == null) return 0;
else
return x.N;
}
public Value get(Key key)
{
return get(root,key);
}
private Value get(Node root,Key key)
{
if (root == null) return default(Value);
int cmp = root.key.CompareTo(key);
if (cmp > 0)
{
return get(root.left, key);
}
else if(cmp < 0)
{
return get(root.right, key);
}
else
{
return root.val;
}
}
public void put(Key key, Value val)
{
root = put(root, key, val);
}
private Node put(Node root, Key key, Value val)
{
if (root == null)
return new Node(key, val,0);
int cmp = key.CompareTo(root.key);
if (cmp < 0)
{
root.left = put(root.left, key, val);
}
else if (cmp >0)
{
root.right = put(root.right, key, val);
}
else
{
root.val = val;
}
return root;
}
}
#endregion
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Better10Hearts
{
class ModConfig
{
public int NPCStaminaIncrease { get; set; } = 20;
public int SpouseStaminaIncrease { get; set; } = 40;
}
}
|
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEditor;
public class YpMinionMovesTowardsPlayer
{
private GameObject ypMinion = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Prefabs/YPMinion.prefab");
private GameObject player = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Prefabs/Player1.prefab");
[UnityTest]
public IEnumerator YpMinionMovesToPlayer()
{
var playerInstance = Object.Instantiate(player, new Vector3(0, 0, 0), Quaternion.identity);
var ypMinionInstance = Object.Instantiate(ypMinion, new Vector3(9, 8, 0), Quaternion.identity);
float distfromplayer = (ypMinionInstance.transform.position - playerInstance.transform.position).sqrMagnitude;
yield return new WaitForSeconds(0.5f);
float distfromplayer1 = (ypMinionInstance.transform.position - playerInstance.transform.position).sqrMagnitude;
Assert.Less(distfromplayer1, distfromplayer);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
/// <summary>
/// Contiene los posibles tipos de productos
/// </summary>
public enum ETipo
{
alimento,
juguete,
cama,
cuidado
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.