text stringlengths 13 6.01M |
|---|
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Queries;
namespace ShoppingListTest
{
[TestFixture(Platform.Android)]
[TestFixture(Platform.iOS)]
public class Tests
{
IApp app;
Platform platform;
public Tests(Platform platform)
{
this.platform = platform;
}
[SetUp]
public void BeforeEachTest()
{
app = AppInitializer.StartApp(platform);
}
[Test]
public void AppLaunches()
{
app.Screenshot("First screen.");
}
[Test]
public void AddEmptyList()
{
app.WaitForElement(c => c.Marked("NoResourceEntry-0").Text("New Shopping"));
app.Tap(c => c.Marked("NoResourceEntry-0"));
app.EnterText(e => e.Class("EntryEditText"), "NewList");
app.PressEnter();
app.Tap(c => c.Marked("NoResourceEntry-0"));
Assert.AreEqual(1, app.Query(q => q.Class("ListView").Child()).Length);
}
[Test]
public void AddAndRemoveList()
{
app.WaitForElement(c => c.Marked("NoResourceEntry-0").Text("New Shopping"));
app.Tap(c => c.Marked("NoResourceEntry-0"));
app.EnterText(e => e.Class("EntryEditText"), "NewList");
app.PressEnter();
app.Tap(c => c.Marked("NoResourceEntry-0"));
Assert.AreEqual(1, app.Query(q => q.Class("ListView").Child()).Length);
app.Tap(c => c.Class("AppCompatButton"));
Assert.AreEqual(0, app.Query(q => q.Class("ListView").Child()).Length);
}
[Test]
public void AddListWithItems()
{
int itemsNum = 7;
app.WaitForElement(c => c.Marked("NoResourceEntry-0").Text("New Shopping"));
app.Tap(c => c.Marked("NoResourceEntry-0"));
app.EnterText(e => e.Class("EntryEditText"), "NewList");
app.PressEnter();
for (int i = 0; i < itemsNum; i++)
{
app.EnterText(c => c.Class("EntryEditText").Index(1), "item"+i);
app.PressEnter();
}
Assert.AreEqual(itemsNum, app.Query(q => q.Class("ListView").Child()).Length);
app.Tap(c => c.Marked("NoResourceEntry-0"));
Assert.AreEqual(1, app.Query(q => q.Class("ListView").Child()).Length);
app.Tap(c => c.Class("AppCompatButton"));
Assert.AreEqual(0, app.Query(q => q.Class("ListView").Child()).Length);
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using WebShop.Data.Models;
namespace WebShop.Data.Repository.Contract
{
public interface IOrderRepo : IRepository<ORDER>
{
public Task<ORDER> CreateOrderAsync(ORDER order);
public Task<IEnumerable<ORDER>> GetOrdersByUserIdAsync(string userId);
public ORDER GetOrderByIdAsync(int orderId);
Task<ORDER_STATUS> GetOrderStatus(string text);
}
}
|
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace HCore.Tenants.Database.SqlServer.Models.Impl
{
public class TenantModel
{
public const int MaxNameLength = 50;
public const int MaxSubdomainPatternLength = 255;
public const int MaxUrlLength = 255;
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Uuid { get; set; }
public long DeveloperUuid { get; set; }
public DeveloperModel Developer { get; set; }
// Deprecated, for migration only
// TODO: remove, once migrated
[StringLength(MaxSubdomainPatternLength)]
public string SubdomainPattern { get; set; }
public string[] SubdomainPatterns { get; set; }
[StringLength(MaxUrlLength)]
public string BackendApiUrl { get; set; }
[StringLength(MaxUrlLength)]
public string FrontendApiUrl { get; set; }
[StringLength(MaxUrlLength)]
public string WebUrl { get; set; }
[StringLength(DeveloperModel.MaxNameLength)]
public string Name { get; set; }
public bool? RequiresTermsAndConditions { get; set; }
[StringLength(DeveloperModel.MaxUrlLength)]
public string LogoSvgUrl { get; set; }
[StringLength(DeveloperModel.MaxUrlLength)]
public string LogoPngUrl { get; set; }
[StringLength(DeveloperModel.MaxUrlLength)]
public string IconIcoUrl { get; set; }
public string StorageImplementation { get; set; }
public string StorageConnectionString { get; set; }
public int? PrimaryColor { get; set; }
public int? SecondaryColor { get; set; }
public int? TextOnPrimaryColor { get; set; }
public int? TextOnSecondaryColor { get; set; }
public string SupportEmail { get; set; }
public string NoreplyEmail { get; set; }
public string CustomInvitationEmailTextPrefix { get; set; }
public string CustomInvitationEmailTextSuffix { get; set; }
public string ProductName { get; set; }
public string DefaultCulture { get; set; }
public string DefaultCurrency { get; set; }
public string ExternalAuthenticationMethod { get; set; }
public string OidcClientId { get; set; }
public string OidcClientSecret { get; set; }
public string OidcEndpointUrl { get; set; }
public string SamlEntityId { get; set; }
public string SamlPeerEntityId { get; set; }
public string SamlPeerIdpMetadataLocation { get; set; }
public string SamlPeerIdpMetadata { get; set; }
public string SamlCertificate { get; set; }
public bool? SamlAllowWeakSigningAlgorithm { get; set; }
public string ExternalDirectoryType { get; set; }
public string ExternalDirectoryHost { get; set; }
public int? ExternalDirectoryPort { get; set; }
public bool? ExternalDirectoryUsesSsl { get; set; }
public string ExternalDirectorySslCertificate { get; set; }
public string ExternalDirectoryAccountDistinguishedName { get; set; }
public string ExternalDirectoryPassword { get; set; }
public string ExternalDirectoryLoginAttribute { get; set; }
public string ExternalDirectoryBaseContexts { get; set; }
public string ExternalDirectoryUserFilter { get; set; }
public string ExternalDirectoryGroupFilter { get; set; }
public int? ExternalDirectorySyncIntervalSeconds { get; set; }
public string ExternalDirectoryAdministratorGroupUuid { get; set; }
public bool ExternalUsersAreManuallyManaged { get; set; }
public string CustomTenantSettingsJson { get; set; }
public bool RequiresDevAdminSsoReplacement { get; set; }
public string DevAdminSsoReplacementSamlPeerEntityId { get; set; }
public string DevAdminSsoReplacementSamlPeerIdpMetadataLocation { get; set; }
public string CreatedByUserUuid { get; set; }
[ConcurrencyCheck]
public int Version { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? LastUpdatedAt { get; set; }
public void SetCustomTenantSettings<TCustomTenantSettingsDataType>(TCustomTenantSettingsDataType customTenantSettings)
{
CustomTenantSettingsJson = JsonConvert.SerializeObject(customTenantSettings);
}
public TCustomTenantSettingsDataType GetCustomTenantSettings<TCustomTenantSettingsDataType>()
{
if (CustomTenantSettingsJson == null)
return default;
return JsonConvert.DeserializeObject<TCustomTenantSettingsDataType>(CustomTenantSettingsJson);
}
}
}
|
using LocusNew.Core.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LocusNew.Core.AdminViewModels
{
public class GlobalSettingsViewModel
{
public int Id { get; set; }
[Required]
public string PhoneNumber { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Address { get; set; }
[Required]
[AllowHtml]
public string AboutUs { get; set; }
public string FacebookLink { get; set; }
public string InstagramLink { get; set; }
public string TwitterLink { get; set; }
public string PinterestLink { get; set; }
public string GooglePlusLink { get; set; }
public string LinkedinLink { get; set; }
public string YoutubeLink { get; set; }
public int CityPart1Id { get; set; }
public string CityPart1Image { get; set; }
public HttpPostedFileBase File1 { get; set; }
public int CityPart2Id { get; set; }
public string CityPart2Image { get; set; }
public HttpPostedFileBase File2 { get; set; }
public int CityPart3Id { get; set; }
public string CityPart3Image { get; set; }
public HttpPostedFileBase File3 { get; set; }
public int CityPart4Id { get; set; }
public string CityPart4Image { get; set; }
public HttpPostedFileBase File4 { get; set; }
public int CityPart5Id { get; set; }
public string CityPart5Image { get; set; }
public HttpPostedFileBase File5 { get; set; }
public int CityPart6Id { get; set; }
public string CityPart6Image { get; set; }
public HttpPostedFileBase File6 { get; set; }
public string FaxNumber { get; set; }
public IEnumerable<CityPart> CityParts { get; set; }
}
} |
using System.Linq;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.UnifiedPlatform.Service.Common.Models;
using Microsoft.UnifiedPlatform.Service.Common.AppExceptions;
using Microsoft.UnifiedPlatform.Service.Common.Configuration;
namespace Microsoft.UnifiedPlatform.Service.Configuration
{
public class ClusterConfigurationProvider: IClusterConfigurationProvider
{
private readonly BaseConfigurationProvider _configurationProvider;
public ClusterConfigurationProvider(BaseConfigurationProvider configurationProvider)
{
_configurationProvider = configurationProvider;
}
public async Task<List<ClusterConfigurationDto>> GetAllClusters()
{
try
{
var clusterConfig = await _configurationProvider.GetConfiguration("Cluster", null);
var clusters = JsonConvert.DeserializeObject<Dictionary<string, string>>(clusterConfig);
if (clusters != null && clusters.Any())
return clusters.Values.Select(value => JsonConvert.DeserializeObject<ClusterConfigurationDto>(value)).ToList();
return null;
}
catch (ConfigurationNotFoundException)
{
return null;
}
}
public async Task<List<AppConfigurationDto>> GetAllApplications(string clusterName)
{
try
{
var applicationConfig = await _configurationProvider.GetConfiguration(clusterName, null);
var applications = JsonConvert.DeserializeObject<Dictionary<string, string>>(applicationConfig);
if (applications != null && applications.Any())
return applications.Values.Select(value => JsonConvert.DeserializeObject<AppConfigurationDto>(value)).ToList();
return null;
}
catch (ConfigurationNotFoundException)
{
return null;
}
}
public async Task<ClusterConfigurationDto> GetClusterDetails(string clusterName)
{
try
{
var clusterDetails = await _configurationProvider.GetConfiguration("Cluster", clusterName);
return JsonConvert.DeserializeObject<ClusterConfigurationDto>(clusterDetails);
}
catch (ConfigurationNotFoundException exception)
{
throw new InvalidClusterException(clusterName, exception);
}
}
public async Task<AppConfigurationDto> GetApplicationDetails(string clusterName, string appName)
{
try
{
var appDetails = await _configurationProvider.GetConfiguration(clusterName, appName);
return JsonConvert.DeserializeObject<AppConfigurationDto>(appDetails);
}
catch (ConfigurationNotFoundException exception)
{
throw new InvalidAppException(clusterName, appName, exception);
}
}
public async Task<string> GetApplicationSecret(string clusterName, string appName)
{
await GetApplicationDetails(clusterName, appName);
var appSecretKey = $"{clusterName}-{appName}";
try
{
var appSecret = await _configurationProvider.GetConfiguration(appSecretKey, "Secret");
return appSecret;
}
catch (ConfigurationNotFoundException exception)
{
throw new IncompleteConfigurationException(clusterName, appName, $"ApplicationSecret: {appSecretKey}-Secret", exception);
}
}
public async Task<string> GetClusterConnectionString(string clusterName, string appName)
{
await GetClusterDetails(clusterName);
try
{
var redisConnectionString = await _configurationProvider.GetConfiguration(clusterName, "Redis-ConnectionString");
return redisConnectionString;
}
catch (ConfigurationNotFoundException exception)
{
throw new IncompleteConfigurationException(clusterName, appName, $"RedisConnectionString: {clusterName}-Redis-ConnectionString", exception);
}
}
}
}
|
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace AsteroidShooter
{
public class Background
{
Texture2D texture;
public Background(Texture2D texture)
{
this.texture = texture;
}
public void Draw(SpriteBatch spriteBatch, GraphicsDevice graphicsDevice)
{
spriteBatch.Draw(texture, new Rectangle(0, 0, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height), Color.White);
}
}
}
|
using MentorAlgorithm.Algorithm;
using MentorAlgorithm.Helpers;
using OxyPlot;
using OxyPlot.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace MentorAlgorithm
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
List<Traffic> Traffics { get; set; } = new List<Traffic>();
public int NumberOfNodes { get; set; } = 90;
public int Threshold { get; set; } = 2;
public int Capacity { get; set; } = 10;
public double Radius { get; set; } = 0.3;
public double Alpha { get; set; } = 0.5;
public double Umin { get; set; } = 0.7;
Mentor mentor;
public MainWindow()
{
DataContext = this;
InitializeComponent();
ListTraffics.ItemsSource = Traffics;
}
private void BtnRun_Click(object sender, RoutedEventArgs e)
{
//try
//{
btnContinue.IsEnabled = false;
if (NumberOfNodes <= 0 || Threshold <= 0 || Capacity < 0 || Radius < 0)
return;
mentor = new Mentor(NumberOfNodes, Capacity, Threshold, Radius, Alpha, Umin);
mentor.GenerateNodes();
mentor.GenerateCosts(0.4);
Execute();
//}
//catch
//{
// MessageBox.Show("Initialize not empty!!!", "Warning");
//}
}
private void BtnContinue_Click(object sender, RoutedEventArgs e)
{
if (NumberOfNodes <= 0 || Threshold <= 0 || Capacity < 0 || Radius < 0)
return;
var nodes = mentor.Nodes.Select(node => new Node(node.X, node.Y, node.Name));
//var costs = mentor.Costs;
//var maxCost = mentor._maxCost;
mentor = new Mentor(NumberOfNodes, Capacity, Threshold, Radius, Alpha, Umin);
//mentor.GenerateNodes();
mentor.Nodes = nodes.ToList();
//mentor.Costs = costs;
//mentor._maxCost = maxCost;
mentor.GenerateCosts(0.4);
Execute();
}
private void Execute()
{
try
{
var listTraffics = ListTraffics.ItemsSource as List<Traffic>;
for (int i = 0; i < listTraffics.Count; i++)
{
string from = listTraffics[i].From, to = listTraffics[i].To;
if (!from.Contains('i') && !to.Contains('i'))
{
mentor.SetTraffic(mentor.Nodes[int.Parse(from)], mentor.Nodes[int.Parse(to)], listTraffics[i].Value);
continue;
}
for (int j = 0; j < mentor.NumberOfNode; j++)
{
int f = Helpers.Helper.Evaluate(from.Replace("i", j.ToString()));
int t = Helpers.Helper.Evaluate(to.Replace("i", j.ToString()));
if (t < mentor.NumberOfNode)
mentor.SetTraffic(mentor.Nodes[f], mentor.Nodes[t], listTraffics[i].Value);
}
}
//for (int i = 0; i < mentor.NumberOfNode; i++)
//{
// if (i + 2 < mentor.NumberOfNode)
// mentor.SetTraffic(mentor.Nodes[i], mentor.Nodes[i + 2], 1);
// if (i + 8 < mentor.NumberOfNode)
// mentor.SetTraffic(mentor.Nodes[i], mentor.Nodes[i + 8], 2);
// if (i + 12 < mentor.NumberOfNode)
// mentor.SetTraffic(mentor.Nodes[i], mentor.Nodes[i + 12], 3);
//}
//mentor.SetTraffic(mentor.Nodes[13], mentor.Nodes[47], 15);
//mentor.SetTraffic(mentor.Nodes[34], mentor.Nodes[69], 13);
//mentor.SetTraffic(mentor.Nodes[20], mentor.Nodes[38], 30);
//mentor.SetTraffic(mentor.Nodes[45], mentor.Nodes[29], 10);
mentor.FindBackbone(x => x.Add(new Node(double.NaN, double.NaN, "Null")));
Plotter.Annotations.Clear();
for (int i = 0; i < mentor.NumberOfNode; i++)
{
var textAnnotation = new TextAnnotation
{
Text = i.ToString(),
TextPosition = new DataPoint(mentor.Nodes[i].X, mentor.Nodes[i].Y),
StrokeThickness = 0,
FontSize = 11,
TextColor = Colors.White,
HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
VerticalAlignment = System.Windows.VerticalAlignment.Center
};
Plotter.Annotations.Add(textAnnotation);
}
//Chuyển lưu lượng giữa các nút backbone và dựng cây prim-dijkstra giữa các nút backbone
mentor.ConnectBackbone();
//Liên kết trên cây sau khi áp dụng mentor 2
var temp = mentor.LinksResult.ToDictionary(k => k.Key, v => v.Value.Item1);
foreach (var item in temp)
{
if (item.Value > 0)
{
mentor.TreeLinks.Add(item.Key.Item1);
mentor.TreeLinks.Add(item.Key.Item2);
mentor.TreeLinks.Add(new Node(double.NaN, double.NaN, "Null"));
}
}
Plotter.DataContext = mentor;
//logger
if (overwriteConsole.IsChecked == true)
Logger.Inlines.Clear();
LogLine("1. ");
LogLine("Lưu lượng giữa các nút:");
foreach (var item in mentor.Traffics)
Log("T(" + item.Key.Item1.Name + ", " + item.Key.Item2.Name + ") = " + item.Value + "\t");
LogLine("Trọng số của các nút:");
for (int i = 0; i < mentor.NumberOfNode; i++)
Log("W(" + i + ") = " + mentor.Nodes[i].Traffic + "\t");
LogLine("Lưu lượng thực tế đi qua các nút backbones:");
//foreach (var item in mentor._trafficBackbones)
// Log("T(" + item.Key.Item1.Name + ", " + item.Key.Item2.Name + ") = " + item.Value + "\t");
Log(mentor._trafficBackbones.ToStringTable("Node", mentor.Backbones, node => node.Name));
LogLine("2. ");
LogLine("Số đường sử dụng trên từng liên kết và độ sử dụng trên liên kết đó: link(node i, node j) = (n, u)");
//foreach (var item in mentor.LinksResult)
// Log("Link(" + item.Key.Item1.Name + ", " + item.Key.Item2.Name + ") = (" + item.Value.Item1 + ", " + item.Value.Item2.ToString() + ")\t");
LogLine(temp.ToStringTable("Node", mentor.Backbones, node => node.Name));
LogLine(mentor.LinksResult.ToDictionary(k => k.Key, v => v.Value.Item2).ToStringTable("Node", mentor.Backbones, node => node.Name));
LogLine("Giá thay đổi trên liên kết trực tiếp sau khi dùng Mentor 2: ");
//foreach (var item in mentor.D)
// Log("( " + item.Key.Item1.Name + ", " + item.Key.Item2.Name + ") = " + item.Value + "\t");
//var columnHeaders = new List<string> { "Node" };
//columnHeaders.AddRange(mentor.Backbones.Select(x => x.Name));
//Log(mentor.D.ToStringTable(columnHeaders.ToArray(), node => node.Value));
//LogLine("Trước khi thêm liên kết trực tiếp: ");
//LogLine(mentor.OldD);
//LogLine("Sau khi thêm liên kết trực tiếp: ");
//LogLine(mentor.D.ToStringTable("Node", mentor.Backbones, node => node.Name));
//LogLine(" *Giá: ");
LogLine("Trước khi thêm liên kết trực tiếp: ");
LogLine(mentor.d.ToStringTable("Node", mentor.Backbones, node => node.Name));
LogLine("Sau khi thêm liên kết trực tiếp: ");
LogLine(mentor.newCost.ToStringTable("Node", mentor.Backbones, node => node.Name));
btnContinue.IsEnabled = true;
}
catch
{
MessageBox.Show("Initialize not empty!!!", "Warning");
}
}
private void GridPlotter_Checked(object sender, RoutedEventArgs e)
{
Plotter.Axes[0].MajorGridlineStyle = LineStyle.Solid; //major: chính
Plotter.Axes[0].MinorGridlineStyle = LineStyle.Solid; //minor: phụ
Plotter.Axes[1].MajorGridlineStyle = LineStyle.Solid;
Plotter.Axes[1].MinorGridlineStyle = LineStyle.Solid;
}
private void GridPlotter_Unchecked(object sender, RoutedEventArgs e)
{
Plotter.Axes[0].MajorGridlineStyle = LineStyle.None; //major: chính
Plotter.Axes[0].MinorGridlineStyle = LineStyle.None; //minor: phụ
Plotter.Axes[1].MajorGridlineStyle = LineStyle.None;
Plotter.Axes[1].MinorGridlineStyle = LineStyle.None;
}
private void AppendConsole_Checked(object sender, RoutedEventArgs e)
{
overwriteConsole.IsChecked = false;
}
private void OverwriteConsole_Checked(object sender, RoutedEventArgs e)
{
appendConsole.IsChecked = false;
}
public void Log(string text)
{
Logger.Inlines.Add(text);
}
public void LogLine(string text)
{
Logger.Inlines.Add("\n" + text + "\n");
}
}
public class Traffic
{
public string From { get; set; }
public string To { get; set; }
public int Value { get; set; }
}
}
|
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
using AGL.DeveloperTest.Contracts.DataProviders;
using AGL.DeveloperTest.Models;
using System.Configuration;
namespace AGL.DeveloperTest.DataProviders
{
/// <summary>
/// JosnDataProvider class
/// </summary>
public class JosnDataProvider : IJosnDataProvider
{
private static string AppSettings_Url = "Url";
private List<Person> _getPeopleCache;
/// <summary>
/// Get People
/// </summary>
/// <returns>List of person</returns>
public List<Person> GetPeople()
{
if (_getPeopleCache == null)
{
string _url = ConfigurationManager.AppSettings[AppSettings_Url];
_getPeopleCache = JsonConvert.DeserializeObject<List<Person>>(new WebClient().DownloadString(_url));
}
return _getPeopleCache;
}
}
}
|
using Logging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
namespace Server
{
public class Program
{
static void Main(string[] args)
{
Trace.TraceInformation("StartServer");
string url = ConfigurationManager.AppSettings["ServiceUri"];
DbTraceListener list = new DbTraceListener("loggerSetting");
list.Write(new object(),"");
HttpListener listener = new HttpListener();
listener.Prefixes.Add(url);
try
{
listener.Start();
while (listener.IsListening)
{
byte[] responseBytes = null;
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
if (request.HttpMethod == "POST")
{
responseBytes = RequestHandler.GetResponseBytes(request);
context.Response.ContentType = @"application/json";
context.Response.ContentLength64 = responseBytes.Length;
}
using (Stream output = context.Response.OutputStream)
{
output.Write(responseBytes, 0, responseBytes.Length);
}
}
}
catch (Exception e)
{
}
finally
{
listener.Close();
}
}
}
}
|
using System.Collections.Generic;
using System;
using UnityEngine;
public interface Move {
List<Vector3> GetMovesFrom(Vector3 startPosition, Board[] boards);
Move AddConstraint(params Constraint[] c);
void RemoveConstraint(Type constraintType);
Move Clone();
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Security.Cryptography;
using System.IO;
namespace Encryption_App
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public static class Encrypt
{
// This size of the IV (in bytes) must = (keysize / 8). Default keysize is 256, so the IV must be
// 32 bytes long. Using a 16 character string here gives us 32 bytes when converted to a byte array.
private const string initVector = "pemgail9uzpgzl88";
// This constant is used to determine the keysize of the encryption algorithm
private const int keysize = 256;
//Encrypt
public static string EncryptString(string plainText, string passPhrase)
{
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
//Decrypt
public static string DecryptString(string cipherText, string passPhrase)
{
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
public partial class MainWindow : Window
{
public string keyphrase;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string TextEncrypt, FinalEncrypt;
TextEncrypt = txtTarget.Text;
keyphrase = Microsoft.VisualBasic.Interaction.InputBox("Enter Key Phrase", "Key Phrase", "password", -1, -1);
FinalEncrypt = Encrypt.EncryptString(TextEncrypt, keyphrase);
txtTarget.Text = String.Empty;
txtTarget.Text = FinalEncrypt;
System.Windows.Clipboard.SetDataObject(FinalEncrypt);
MessageBox.Show("The encrypted text has been generated and copied to the clipboard.","Success!",MessageBoxButton.OK, MessageBoxImage.Information);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Close();
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
string EncryptedText, DecryptedText;
EncryptedText = txtTarget.Text;
keyphrase = Microsoft.VisualBasic.Interaction.InputBox("Enter Key Phrase", "Key Phrase", "password", -1, -1);
DecryptedText = Encrypt.DecryptString(EncryptedText, keyphrase);
txtTarget.Text = String.Empty;
txtTarget.Text = DecryptedText;
Clipboard.SetDataObject(DecryptedText);
MessageBox.Show("The text has been decrypted and copied to the clipboard.", "Success!", MessageBoxButton.OK, MessageBoxImage.Information);
}
private void btnBack_Click(object sender, RoutedEventArgs e)
{
Launcher launcher = new Launcher();
launcher.Show();
this.Hide();
}
}
}
|
using UnityEngine;
namespace PhotonInMaze.Common {
public static class Colors {
public static Color32 Navy = new Color32(19, 26, 132, 255);
public static Color32 Ocean = new Color32(1, 96, 100, 255);
public static Color32 Cerulean = new Color32(4, 146, 194, 255);
}
} |
using System.Web.Mvc;
using DevExpress.Web.Mvc;
namespace DevExpress.Web.Demos {
public partial class UploadControlController : DemoController {
public ActionResult MultiFileSelection() {
return DemoView("MultiFileSelection");
}
public ActionResult MultiSelectionImageUpload() {
UploadControlExtension.GetUploadedFiles("ucMultiSelection", UploadControlDemosHelper.ValidationSettings, UploadControlDemosHelper.ucMultiSelection_FileUploadComplete);
return null;
}
public ActionResult MultiFileSelectionPartial() {
return PartialView("MultiFileSelectionPartial");
}
}
}
|
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Podemski.Musicorum.Dao.Entities;
namespace Podemski.Musicorum.Dao.File
{
internal sealed class CustomContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (member.DeclaringType == typeof(Artist) && member.Name == nameof(Artist.Albums))
{
property.Ignored = true;
}
if (member.DeclaringType == typeof(Album) && member.Name == nameof(Album.Artist))
{
property.Ignored = true;
}
if (member.DeclaringType == typeof(Album) && member.Name == nameof(Album.Tracks))
{
property.Ignored = true;
}
if (member.DeclaringType == typeof(Track) && member.Name == nameof(Track.Album))
{
property.Ignored = true;
}
return property;
}
}
}
|
using System;
namespace Uintra.Features.Information
{
public interface IInformationService
{
Uri DocumentationLink { get; }
Version Version { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BookListMVC.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace BookListMVC.Controllers
{
public class LoginController : Controller
{
private UserManager<LoginModel> userManager;
private SignInManager<LoginModel> signInManager;
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult Loginn(string returnUrl)
{
ViewBag.returnUrl = returnUrl;
return View();
}
[HttpPost]
public async Task<IActionResult> Loginn(LoginModel model,string returnUrl)
{
if (ModelState.IsValid)
{
var user = await userManager.FindByEmailAsync(model.Email);
if (user != null)
{
await signInManager.SignOutAsync();
var result = await signInManager.PasswordSignInAsync(user, model.Password, false, false);
if (result.Succeeded)
{
return Redirect(returnUrl ?? "/");
}
}
ModelState.AddModelError("Email", "Hatalı giriş");
}
return View(model);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using SportsLink;
namespace SportsLinkWeb.Models
{
public class RegistrationJson
{
public string Name;
public string Email;
public DateTime Birthday;
public string Gender;
public Location Location;
public double NTRPRating;
public string SinglesDoubles;
}
public class Location
{
public string Name;
public long Id;
}
} |
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using PointTrans.Commands;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("PointTrans.Tests")]
namespace PointTrans
{
/// <summary>
/// IExcelContext
/// </summary>
/// <seealso cref="System.IDisposable" />
public interface IPointContext : IDisposable
{
/// <summary>
/// Gets or sets where the cursor X starts per row.
/// </summary>
/// <value>
/// The x start.
/// </value>
int XStart { get; set; }
/// <summary>
/// Gets or sets the cursor X coordinate.
/// </summary>
/// <value>
/// The x.
/// </value>
int X { get; set; }
/// <summary>
/// Gets or sets the cursor Y coordinate.
/// </summary>
/// <value>
/// The y.
/// </value>
int Y { get; set; }
/// <summary>
/// Gets or sets the amount the cursor X advances.
/// </summary>
/// <value>
/// The delta x.
/// </value>
int DeltaX { get; set; }
/// <summary>
/// Gets or sets the amount the cursor Y advances.
/// </summary>
/// <value>
/// The delta y.
/// </value>
int DeltaY { get; set; }
/// <summary>
/// Gets or sets the cursor CsvX coordinate, advances with X.
/// </summary>
/// <value>
/// The CSV x.
/// </value>
int CsvX { get; set; }
/// <summary>
/// Gets or sets the cursor CsvY coordinate, advances with Y.
/// </summary>
/// <value>
/// The CSV y.
/// </value>
int CsvY { get; set; }
/// <summary>
/// Gets or sets the next direction.
/// </summary>
/// <value>
/// The next direction.
/// </value>
//NextDirection NextDirection { get; set; }
/// <summary>
/// Gets the stack of commands per row.
/// </summary>
/// <value>
/// The command rows.
/// </value>
Stack<CommandRow> CmdRows { get; }
/// <summary>
/// Gets the stack of commands per column.
/// </summary>
/// <value>
/// The command cols.
/// </value>
Stack<CommandCol> CmdCols { get; }
/// <summary>
/// Gets the stack of sets.
/// </summary>
/// <value>
/// The sets.
/// </value>
Stack<IPointSet> Sets { get; }
/// <summary>
/// Gets the stack of frames.
/// </summary>
/// <value>
/// The frames.
/// </value>
Stack<object> Frames { get; }
/// <summary>
/// Gets the current frame.
/// </summary>
/// <value>
/// The frame.
/// </value>
object Frame { get; set; }
/// <summary>
/// Flushes all pending commands.
/// </summary>
void Flush();
/// <summary>
/// Gets the specified range.
/// </summary>
/// <param name="cells">The cells.</param>
/// <returns></returns>
//ExcelRangeBase Get(string cells);
/// <summary>
/// Advances the cursor based on NextDirection.
/// </summary>
/// <param name="range">The range.</param>
/// <param name="nextDirection">The next direction.</param>
/// <returns></returns>
//ExcelRangeBase Next(ExcelRangeBase range, NextDirection? nextDirection = null);
/// <summary>
/// Advances the cursor to the next row.
/// </summary>
/// <param name="column">The column.</param>
/// <returns></returns>
//ExcelColumn Next(ExcelColumn column);
/// <summary>
/// Advances the cursor to the next row.
/// </summary>
/// <param name="row">The row.</param>
/// <returns></returns>
//ExcelRow Next(ExcelRow row);
}
// https://docs.microsoft.com/en-us/office/open-xml/how-to-create-a-presentation-document-by-providing-a-file-name
internal class PointContext : IPointContext
{
public PointContext()
{
Stream = new MemoryStream();
Doc = PresentationDocument.Create(Stream, PresentationDocumentType.Presentation, true);
P = Doc.AddPresentationPart();
P.Presentation = new Presentation();
}
public void Dispose() => Doc.Dispose();
public int XStart { get; set; } = 1;
public int X { get; set; } = 1;
public int Y { get; set; } = 1;
public int DeltaX { get; set; } = 1;
public int DeltaY { get; set; } = 1;
public int CsvX { get; set; } = 1;
public int CsvY { get; set; } = 1;
//public NextDirection NextDirection { get; set; } = NextDirection.Column;
public Stack<CommandRow> CmdRows { get; } = new Stack<CommandRow>();
public Stack<CommandCol> CmdCols { get; } = new Stack<CommandCol>();
public Stack<IPointSet> Sets { get; } = new Stack<IPointSet>();
public Stack<object> Frames { get; } = new Stack<object>();
public Stream Stream;
public PresentationDocument Doc;
public PresentationPart P;
//public ExcelWorksheet EnsureWorksheet() => WS ?? (WS = WB.Worksheets.Add($"Sheet {WB.Worksheets.Count + 1}"));
//public ExcelRangeBase Get(string cells) => WS.Cells[this.DecodeAddress(cells)];
//public ExcelRangeBase Next(ExcelRangeBase range, NextDirection? nextDirection = null) => (nextDirection ?? NextDirection) == NextDirection.Column ? range.Offset(0, DeltaX) : range.Offset(DeltaY, 0);
//public ExcelColumn Next(ExcelColumn col) => throw new NotImplementedException();
//public ExcelRow Next(ExcelRow row) => throw new NotImplementedException();
public void Flush()
{
//if (Sets.Count == 0) this.WriteRowLast(null);
Frames.Clear();
CommandRow.Flush(this, 0);
CommandCol.Flush(this, 0);
PopSet.Flush(this, 0);
}
public object Frame
{
get => (CmdRows.Count, CmdCols.Count, Sets.Count);
set
{
var (rows, cols, sets) = ((int rows, int cols, int sets))value;
CommandRow.Flush(this, rows);
CommandCol.Flush(this, cols);
PopSet.Flush(this, sets);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercicio35
{
class R35
{
static void Main(string[] args)
{
{
char Esq, Dirta; Console.Write("Digite uma palavra ");
String Palavra = Console.ReadLine().ToUpper();
int Numcaract = Palavra.Length;
bool Palindromo = true;
for (int C = 0; (C < Numcaract / 2 && Palindromo == true); C++)
{
Esq = Convert.ToChar(Palavra.Substring(C, 1));
Dirta = Convert.ToChar(Palavra.Substring(Numcaract - 1 - C, 1));
if (Esq != Dirta)
Palindromo = false;
}
Console.WriteLine("{0} {1}", Palavra, Palindromo == true ? " é palíndromo" : "não é palíndromo");
}
}
}
}
|
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.Xml.Serialization;
namespace GUI_XML
{
public enum genderType { male, female };
public enum eyeColorType { gray, brown, blue, green};
[Serializable]
[XmlInclude(typeof(Person))]
[XmlInclude(typeof(Student))]
[XmlInclude(typeof(Employee))]
public class Person
{
public String SurName { get; set; }
public String GivenName { get; set; }
public double Height { get; set; }
public eyeColorType EyeColor{ get; set; }
public genderType Gender { get; set; }
public Person(String Surname,String GivenName, double Height,genderType Gender,eyeColorType eyeColor)
{
this.SurName = Surname;
this.GivenName = GivenName;
this.Height = Height;
this.Gender = Gender;
this.EyeColor = eyeColor;
}
public Person()
{
}
}
}
|
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using MongoDB.Driver;
namespace XH.Infrastructure.Identity.MongoDb
{
public class RoleStore<TRole> : IQueryableRoleStore<TRole> where TRole : IdentityRole
{
private readonly IMongoCollection<TRole> _roles;
private readonly string _tenantId;
public RoleStore(IMongoCollection<TRole> roles, string tenantId)
{
_roles = roles;
_tenantId = tenantId;
}
public IQueryable<TRole> Roles
{
get
{
return _roles.AsQueryable();
}
}
public Task CreateAsync(TRole role)
{
//Contract.Requires(role != null);
role.TenantId = _tenantId;
_roles.InsertOne(role);
return Task.CompletedTask;
}
public Task DeleteAsync(TRole role)
{
//Contract.Requires(role != null);
_roles.DeleteOne(it => it.Id == role.Id);
return Task.CompletedTask;
}
public void Dispose()
{
}
public Task<TRole> FindByIdAsync(string roleId)
{
return _roles.Find(it => it.Id == roleId).FirstOrDefaultAsync();
}
public Task<TRole> FindByNameAsync(string roleName)
{
return _roles.Find(it => it.Name == roleName && it.TenantId == _tenantId).FirstOrDefaultAsync();
}
public Task UpdateAsync(TRole role)
{
//Contract.Requires(role != null);
return _roles.ReplaceOneAsync(it => it.Id == role.Id, role);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;
namespace MegaMan.Common
{
public enum SceneCommands
{
PlayMusic,
Add,
Move,
Remove,
Entity,
Text,
Fill,
FillMove,
Option,
Sound,
Next,
Call,
Effect
}
public abstract class SceneCommandInfo
{
public abstract SceneCommands Type { get; }
public abstract void Save(XmlTextWriter writer);
public static List<SceneCommandInfo> Load(XElement node, string basePath)
{
var list = new List<SceneCommandInfo>();
foreach (var cmdNode in node.Elements())
{
switch (cmdNode.Name.LocalName)
{
case "PlayMusic":
list.Add(ScenePlayCommandInfo.FromXml(cmdNode));
break;
case "Sprite":
case "Meter":
case "Add":
list.Add(SceneAddCommandInfo.FromXml(cmdNode));
break;
case "SpriteMove":
list.Add(SceneMoveCommandInfo.FromXml(cmdNode));
break;
case "Remove":
list.Add(SceneRemoveCommandInfo.FromXml(cmdNode));
break;
case "Entity":
list.Add(SceneEntityCommandInfo.FromXml(cmdNode));
break;
case "Text":
list.Add(SceneTextCommandInfo.FromXml(cmdNode));
break;
case "Fill":
list.Add(SceneFillCommandInfo.FromXml(cmdNode));
break;
case "FillMove":
list.Add(SceneFillMoveCommandInfo.FromXml(cmdNode));
break;
case "Option":
list.Add(MenuOptionCommandInfo.FromXml(cmdNode, basePath));
break;
case "Sound":
list.Add(SceneSoundCommandInfo.FromXml(cmdNode, basePath));
break;
case "Next":
list.Add(SceneNextCommandInfo.FromXml(cmdNode));
break;
case "Call":
list.Add(SceneCallCommandInfo.FromXml(cmdNode));
break;
case "Effect":
list.Add(SceneEffectCommandInfo.FromXml(cmdNode));
break;
}
}
return list;
}
}
public class ScenePlayCommandInfo : SceneCommandInfo
{
public override SceneCommands Type { get { return SceneCommands.PlayMusic; } }
public int Track { get; set; }
public static ScenePlayCommandInfo FromXml(XElement node)
{
var info = new ScenePlayCommandInfo();
info.Track = node.GetInteger("track");
return info;
}
public override void Save(XmlTextWriter writer)
{
writer.WriteStartElement("PlayMusic");
writer.WriteAttributeString("track", Track.ToString());
writer.WriteEndElement();
}
}
public class SceneAddCommandInfo : SceneCommandInfo
{
public override SceneCommands Type { get { return SceneCommands.Add; } }
public string Name { get; set; }
public string Object { get; set; }
public int X { get; set; }
public int Y { get; set; }
public static SceneAddCommandInfo FromXml(XElement node)
{
var info = new SceneAddCommandInfo();
var nameAttr = node.Attribute("name");
if (nameAttr != null) info.Name = nameAttr.Value;
info.Object = node.RequireAttribute("object").Value;
info.X = node.GetInteger("x");
info.Y = node.GetInteger("y");
return info;
}
public override void Save(XmlTextWriter writer)
{
writer.WriteStartElement("Add");
if (!string.IsNullOrEmpty(Name)) writer.WriteAttributeString("name", Name);
writer.WriteAttributeString("object", Object);
writer.WriteAttributeString("x", X.ToString());
writer.WriteAttributeString("y", Y.ToString());
writer.WriteEndElement();
}
}
public class SceneRemoveCommandInfo : SceneCommandInfo
{
public override SceneCommands Type { get { return SceneCommands.Remove; } }
public string Name { get; set; }
public static SceneRemoveCommandInfo FromXml(XElement node)
{
var info = new SceneRemoveCommandInfo();
info.Name = node.RequireAttribute("name").Value;
return info;
}
public override void Save(XmlTextWriter writer)
{
writer.WriteStartElement("Remove");
writer.WriteAttributeString("name", Name);
writer.WriteEndElement();
}
}
public class SceneEntityCommandInfo : SceneCommandInfo
{
public override SceneCommands Type { get { return SceneCommands.Entity; } }
public string Name { get; set; }
public string Entity { get; set; }
public string State { get; set; }
public int X { get; set; }
public int Y { get; set; }
public static SceneEntityCommandInfo FromXml(XElement node)
{
var info = new SceneEntityCommandInfo();
info.Entity = node.RequireAttribute("entity").Value;
var nameAttr = node.Attribute("name");
if (nameAttr != null) info.Name = nameAttr.Value;
var stateAttr = node.Attribute("state");
if (stateAttr != null) info.State = stateAttr.Value;
info.X = node.GetInteger("x");
info.Y = node.GetInteger("y");
return info;
}
public override void Save(XmlTextWriter writer)
{
writer.WriteStartElement("Entity");
if (!string.IsNullOrEmpty(Name)) writer.WriteAttributeString("name", Name);
writer.WriteAttributeString("entity", Entity);
if (!string.IsNullOrEmpty(State)) writer.WriteAttributeString("state", State);
writer.WriteAttributeString("x", X.ToString());
writer.WriteAttributeString("y", Y.ToString());
writer.WriteEndElement();
}
}
public class SceneTextCommandInfo : SceneCommandInfo
{
public override SceneCommands Type { get { return SceneCommands.Text; } }
public string Name { get; set; }
public string Content { get; set; }
public SceneBindingInfo Binding { get; set; }
public int? Speed { get; set; }
public int X { get; set; }
public int Y { get; set; }
public string Font { get; set; }
public static SceneTextCommandInfo FromXml(XElement node)
{
var info = new SceneTextCommandInfo();
var contentAttr = node.Attribute("content");
if (contentAttr != null)
{
info.Content = contentAttr.Value;
}
var nameAttr = node.Attribute("name");
if (nameAttr != null) info.Name = nameAttr.Value;
int speed;
if (node.TryInteger("speed", out speed)) info.Speed = speed;
info.X = node.GetInteger("x");
info.Y = node.GetInteger("y");
var bindingNode = node.Element("Binding");
if (bindingNode != null) info.Binding = SceneBindingInfo.FromXml(bindingNode);
var fontAttr = node.Attribute("font");
if (fontAttr != null)
{
info.Font = fontAttr.Value;
}
return info;
}
public override void Save(XmlTextWriter writer)
{
writer.WriteStartElement("Text");
if (!string.IsNullOrEmpty("Font")) writer.WriteAttributeString("font", Font);
if (!string.IsNullOrEmpty(Name)) writer.WriteAttributeString("name", Name);
writer.WriteAttributeString("content", Content);
if (Speed != null) writer.WriteAttributeString("speed", Speed.Value.ToString());
writer.WriteAttributeString("x", X.ToString());
writer.WriteAttributeString("y", Y.ToString());
if (Binding != null) Binding.Save(writer);
writer.WriteEndElement();
}
}
public class SceneFillCommandInfo : SceneCommandInfo
{
public override SceneCommands Type { get { return SceneCommands.Fill; } }
public string Name { get; set; }
public byte Red { get; set; }
public byte Green { get; set; }
public byte Blue { get; set; }
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Layer { get; set; }
public static SceneFillCommandInfo FromXml(XElement node)
{
var info = new SceneFillCommandInfo();
var nameAttr = node.Attribute("name");
if (nameAttr != null) info.Name = nameAttr.Value;
var colorAttr = node.RequireAttribute("color");
var color = colorAttr.Value;
var split = color.Split(',');
info.Red = byte.Parse(split[0]);
info.Green = byte.Parse(split[1]);
info.Blue = byte.Parse(split[2]);
info.X = node.GetInteger("x");
info.Y = node.GetInteger("y");
info.Width = node.GetInteger("width");
info.Height = node.GetInteger("height");
int layer = 1;
if (node.TryInteger("layer", out layer)) info.Layer = layer;
return info;
}
public override void Save(XmlTextWriter writer)
{
writer.WriteStartElement("Fill");
if (!string.IsNullOrEmpty(Name)) writer.WriteAttributeString("name", Name);
writer.WriteAttributeString("color", Red.ToString() + "," + Green.ToString() + "," + Blue.ToString());
writer.WriteAttributeString("x", X.ToString());
writer.WriteAttributeString("y", Y.ToString());
writer.WriteAttributeString("width", Width.ToString());
writer.WriteAttributeString("height", Height.ToString());
writer.WriteAttributeString("layer", Layer.ToString());
writer.WriteEndElement();
}
}
public class SceneFillMoveCommandInfo : SceneCommandInfo
{
public override SceneCommands Type { get { return SceneCommands.FillMove; } }
public string Name { get; set; }
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int Duration { get; set; }
public static SceneFillMoveCommandInfo FromXml(XElement node)
{
var info = new SceneFillMoveCommandInfo();
info.Name = node.RequireAttribute("name").Value;
info.Duration = node.GetInteger("duration");
info.X = node.GetInteger("x");
info.Y = node.GetInteger("y");
info.Width = node.GetInteger("width");
info.Height = node.GetInteger("height");
return info;
}
public override void Save(XmlTextWriter writer)
{
writer.WriteStartElement("FillMove");
if (!string.IsNullOrEmpty(Name)) writer.WriteAttributeString("name", Name);
writer.WriteAttributeString("x", X.ToString());
writer.WriteAttributeString("y", Y.ToString());
writer.WriteAttributeString("width", Width.ToString());
writer.WriteAttributeString("height", Height.ToString());
writer.WriteAttributeString("duration", Duration.ToString());
writer.WriteEndElement();
}
}
public class SceneMoveCommandInfo : SceneCommandInfo
{
public override SceneCommands Type { get { return SceneCommands.Move; } }
public string Name { get; set; }
public int X { get; set; }
public int Y { get; set; }
public int Duration { get; set; }
public static SceneMoveCommandInfo FromXml(XElement node)
{
var info = new SceneMoveCommandInfo();
info.Name = node.RequireAttribute("name").Value;
int d = 0;
node.TryInteger("duration", out d);
info.Duration = d;
info.X = node.GetInteger("x");
info.Y = node.GetInteger("y");
return info;
}
public override void Save(XmlTextWriter writer)
{
writer.WriteStartElement("Move");
if (!string.IsNullOrEmpty(Name)) writer.WriteAttributeString("name", Name);
writer.WriteAttributeString("x", X.ToString());
writer.WriteAttributeString("y", Y.ToString());
if (Duration > 0) writer.WriteAttributeString("duration", Duration.ToString());
writer.WriteEndElement();
}
}
public class MenuOptionCommandInfo : SceneCommandInfo
{
public override SceneCommands Type { get { return SceneCommands.Option; } }
public int X { get; set; }
public int Y { get; set; }
public List<SceneCommandInfo> OnEvent { get; private set; }
public List<SceneCommandInfo> OffEvent { get; private set; }
public List<SceneCommandInfo> SelectEvent { get; private set; }
public static MenuOptionCommandInfo FromXml(XElement node, string basePath)
{
var info = new MenuOptionCommandInfo();
info.X = node.GetInteger("x");
info.Y = node.GetInteger("y");
var onNode = node.Element("On");
if (onNode != null)
{
info.OnEvent = SceneCommandInfo.Load(onNode, basePath);
}
var offNode = node.Element("Off");
if (offNode != null)
{
info.OffEvent = SceneCommandInfo.Load(offNode, basePath);
}
var selectNode = node.Element("Select");
if (selectNode != null)
{
info.SelectEvent = SceneCommandInfo.Load(selectNode, basePath);
}
return info;
}
public override void Save(XmlTextWriter writer)
{
writer.WriteStartElement("Option");
writer.WriteAttributeString("x", X.ToString());
writer.WriteAttributeString("y", Y.ToString());
if (OnEvent != null)
{
writer.WriteStartElement("On");
foreach (var cmd in OnEvent)
{
cmd.Save(writer);
}
writer.WriteEndElement();
}
if (OffEvent != null)
{
writer.WriteStartElement("Off");
foreach (var cmd in OffEvent)
{
cmd.Save(writer);
}
writer.WriteEndElement();
}
if (SelectEvent != null)
{
writer.WriteStartElement("Select");
foreach (var cmd in SelectEvent)
{
cmd.Save(writer);
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}
public class SceneSoundCommandInfo : SceneCommandInfo
{
public override SceneCommands Type { get { return SceneCommands.Sound; } }
public SoundInfo SoundInfo { get; private set; }
public static SceneSoundCommandInfo FromXml(XElement node, string basePath)
{
var info = new SceneSoundCommandInfo();
info.SoundInfo = SoundInfo.FromXml(node, basePath);
return info;
}
public override void Save(XmlTextWriter writer)
{
SoundInfo.Save(writer);
}
}
public class SceneNextCommandInfo : SceneCommandInfo
{
public override SceneCommands Type { get { return SceneCommands.Next; } }
public HandlerTransfer NextHandler { get; private set; }
public static SceneNextCommandInfo FromXml(XElement node)
{
var info = new SceneNextCommandInfo();
info.NextHandler = HandlerTransfer.FromXml(node);
return info;
}
public override void Save(XmlTextWriter writer)
{
NextHandler.Save(writer);
}
}
public class SceneCallCommandInfo : SceneCommandInfo
{
public override SceneCommands Type { get { return SceneCommands.Call; } }
public string Name { get; private set; }
public static SceneCallCommandInfo FromXml(XElement node)
{
var info = new SceneCallCommandInfo();
info.Name = node.Value;
return info;
}
public override void Save(XmlTextWriter writer)
{
writer.WriteStartElement("Call");
writer.WriteValue(this.Name);
writer.WriteEndElement();
}
}
public class SceneEffectCommandInfo : SceneCommandInfo
{
public string GeneratedName { get; private set; }
public string EntityName { get; private set; }
public XElement EffectNode { get; private set; }
public static SceneEffectCommandInfo FromXml(XElement node)
{
var info = new SceneEffectCommandInfo();
info.GeneratedName = Guid.NewGuid().ToString();
info.EntityName = node.RequireAttribute("entity").Value;
info.EffectNode = node;
return info;
}
public override SceneCommands Type
{
get { return SceneCommands.Effect; }
}
public override void Save(XmlTextWriter writer)
{
throw new NotImplementedException();
}
}
public class SceneBindingInfo
{
public string Source { get; set; }
public string Target { get; set; }
public static SceneBindingInfo FromXml(XElement node)
{
var info = new SceneBindingInfo();
info.Source = node.RequireAttribute("source").Value;
info.Target = node.RequireAttribute("target").Value;
return info;
}
public void Save(XmlTextWriter writer)
{
writer.WriteStartElement("Bind");
writer.WriteAttributeString("source", Source);
writer.WriteAttributeString("target", Target);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SampleEFCore.Model
{
public class MyValueRequest
{
public string Name { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Sequences.Library
{
public class StringSequence
{
private readonly List<string> _list = new List<string>();
// "delegation" - this class implements Add by delegating the work to another class
public void Add(string item)
{
_list.Add(item);
}
public void Remove(string item)
{
_list.Remove(item);
}
// overload index operator with delegation to the list
public string this[int index]
{
get => _list[index];
set => _list[index] = value;
}
public string LongestString()
{
return null;
}
public
}
}
|
namespace StorageMasterTests
{
using FluentAssertions;
using NUnit.Framework;
using System;
using StorageMaster.Entities.Products;
[TestFixture]
public class ProductTests
{
[Test]
public void DoesConstructorThrowExceptionWhenNegativePriceIsGiven()
{
Assert.Throws<InvalidOperationException>(() => new Gpu(-1));
}
[Test]
public void DoesConstructorSetCorrectValuesSuccessfully()
{
var validProduct = new Gpu(100);
validProduct.Price.Should().Be(100);
}
}
}
|
using Application.Models;
using Domain.Base;
using Domain.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Application.Base
{
public abstract class Service<T> : IService<T> where T : BaseEntity
{
public readonly IUnitOfWork _unitOfWork;
public readonly IGenericRepository<T> _repository;
public Service(IUnitOfWork unitOfWork, IGenericRepository<T> repository)
{
_unitOfWork = unitOfWork;
_repository = repository;
}
public virtual Response<T> Agregar(T entity)
{
_repository.Add(entity);
_unitOfWork.Commit();
return new Response<T> {
Mensaje = "Registro agregado con éxito",
Entity = entity
};
}
public virtual IEnumerable<T> Buscar(Expression<Func<T, bool>> predicate = null, string include = "")
{
return _repository.FindBy(predicate, includeProperties: include);
}
public virtual IEnumerable<T> All()
{
return _repository.GetAll();
}
}
}
|
namespace BookShopSystemQueries
{
using BookShopSystem.Data;
using BookShopSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
BookShopContext context = new BookShopContext();
FindProfit(context);
}
// 1
private static void BookTitlesByAgeRestriction(BookShopContext context)
{
var input = Console.ReadLine();
foreach (var book in context.Books.Where(b => b.AgeRestriction.ToString() == input))
{
Console.WriteLine(book.Title);
}
}
//2
private static void GoldenBooks(BookShopContext context)
{
var collection = context.Books
.Where(b => b.EditionType.ToString() == "Gold" && b.Copies < 5000)
.OrderBy(b => b.Id);
foreach (Book book in collection)
{
Console.WriteLine(book.Title);
}
}
//3
private static void BooksByPrice(BookShopContext context)
{
var collection = context.Books
.Where(b => b.Price < 5 || b.Price > 40)
.OrderBy(b => b.Id);
foreach (Book book in collection)
{
Console.WriteLine($"{book.Title} - ${book.Price}");
}
}
//4
private static void NotReleasedBooks(BookShopContext context)
{
var year = int.Parse(Console.ReadLine());
var collection = context.Books
.Where(b => b.ReleaseDate.Year != year)
.OrderBy(b => b.Id);
foreach (Book book in collection)
{
Console.WriteLine(book.Title);
}
}
// 5
private static void BookTitlesByCategory(BookShopContext context)
{
string[] input = Console.ReadLine()
.Split(' ')
.Select(c => c.ToLower())
.ToArray();
foreach (Book book in context.Books)
{
if (book.Categories.Any(c => input.Contains(c.Name.ToLower())))
{
Console.WriteLine(book.Title);
}
}
}
// 6
private static void BooksReleasedBeforeDate(BookShopContext context)
{
DateTime inputDate = DateTime.Parse(Console.ReadLine());
var collection = context.Books
.Where(b => b.ReleaseDate < inputDate);
foreach (Book book in collection)
{
Console.WriteLine($"{book.Title} - {book.EditionType} - {book.Price}");
}
}
// 7
private static void AuthorsSearch(BookShopContext context)
{
var inputString = Console.ReadLine();
var collection = context.Authors
.Where(a => a.FirstName.EndsWith(inputString));
foreach (Author author in collection)
{
Console.WriteLine($"{author.FirstName} {author.LastName}");
}
}
// 8
private static void BooksSearch(BookShopContext context)
{
var inputString = Console.ReadLine().ToLower();
var collection = context.Books
.Where(b => b.Title.ToLower().Contains(inputString));
foreach (Book book in collection)
{
Console.WriteLine(book.Title);
}
}
// 9
private static void BookTitlesSearch(BookShopContext context)
{
var inputString = Console.ReadLine().ToLower();
var collection = context.Books
.Where(b => b.Author.LastName.ToLower().StartsWith(inputString))
.OrderBy(b => b.Id);
foreach (Book book in collection)
{
Console.WriteLine($"{book.Title} ({book.Author.FirstName} {book.Author.LastName})");
}
}
// 10
private static void CountBooks(BookShopContext context)
{
var inputSize = int.Parse(Console.ReadLine());
var result = context.Books
.Where(b => b.Title.Length > inputSize).Count();
Console.WriteLine($"There are {result} books with longer title than {inputSize} symbols");
}
//11
private static void TotalBookCopies(BookShopContext context)
{
context.Authors
.OrderByDescending(a => a.Books.Sum(b => b.Copies))
.ToList()
.ForEach(a =>
{
Console.WriteLine($"{a.FirstName} {a.LastName} - {a.Books.Sum(b => b.Copies)}");
});
}
// 12
private static void FindProfit(BookShopContext context)
{
context.Categories.OrderByDescending(c => c.Books.Sum(b => (b.Price * b.Copies)))
.ThenBy(c => c.Name)
.ToList()
.ForEach(c =>
{
Console.WriteLine($"{c.Name} - ${c.Books.Sum(b => (b.Price * b.Copies))}");
});
}
// 13
private static void MostRecentBooks(BookShopContext context)
{
context.Categories.OrderByDescending(c => c.Books.Count())
.Where(c => c.Books.Count > 35)
.Select(c => new
{
c.Name,
c.Books
})
.ToList()
.ForEach(c =>
{
Console.WriteLine($"--{c.Name}: {c.Books.Count} books");
c.Books.OrderByDescending(b => b.ReleaseDate)
.ThenBy(b => b.Title)
.Take(3)
.Select(b => new
{
b.Title,
b.ReleaseDate
}).ToList().ForEach(book =>
{
Console.WriteLine($"{book.Title} ({book.ReleaseDate.Year})");
});
});
}
// 14
private static void IncreaseBookCopies(BookShopContext context)
{
DateTime date = DateTime.Parse("06 - Jun - 2013");
int addedBooks = 0;
context.Books.Where(b => b.ReleaseDate > date).ToList().ForEach(b =>
{
b.Copies += 44;
addedBooks += 44;
});
context.SaveChanges();
Console.WriteLine(addedBooks);
}
// 15
private static void RemoveBooks(BookShopContext context)
{
context.Books.RemoveRange(context.Books.Where(b => b.Copies < 4200));
context.SaveChanges();
Console.WriteLine(context.SaveChanges() + " books were deleted");
}
// 16
private static void StoredProcedure(BookShopContext context)
{
string[] names = Console.ReadLine().Split(' ');
var count = context.Database.SqlQuery<int>($"EXEC dbo.usp_GetBooksCountByAuthor {names[0]}, {names[1]}").First();
Console.WriteLine($"{names[0]} {names[1]} has written {count} books");
}
}
}
|
/** 版本信息模板在安装目录下,可自行修改。
* tb_user.cs
*
* 功 能: N/A
* 类 名: tb_user
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2017-04-05 10:52:25 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
namespace ND.FluentTaskScheduling.Model
{
/// <summary>
/// 任务表
/// </summary>
public partial class tb_user
{
public tb_user()
{}
#region Model
private int _id;
private string _userpassword;
private string _username;
private int _userrole;
private DateTime _userupdatetime;
private string _usermobile;
private string _useremail;
private string _realname;
private int _createby = 0;
private int _isdel = 0;
private DateTime _createtime = DateTime.Now;
/// <summary>
/// 创建时间
/// </summary>
public DateTime createtime
{
set { _createtime = value; }
get { return _createtime; }
}
/// <summary>
/// 创建人
/// </summary>
public int createby
{
set { _createby = value; }
get { return _createby; }
}
/// <summary>
/// 是否删除
/// </summary>
public int isdel
{
set { _isdel = value; }
get { return _isdel; }
}
/// <summary>
/// 员工姓名
/// </summary>
public string realname
{
set { _realname = value; }
get { return _realname; }
}
/// <summary>
///
/// </summary>
public int id
{
set{ _id=value;}
get{return _id;}
}
/// <summary>
/// 员工密码
/// </summary>
public string userpassword
{
set { _userpassword = value; }
get { return _userpassword; }
}
/// <summary>
/// 登录账户
/// </summary>
public string username
{
set{ _username=value;}
get{return _username;}
}
/// <summary>
/// 员工角色,查看代码枚举:开发人员,管理员
/// </summary>
public int userrole
{
set{ _userrole=value;}
get{return _userrole;}
}
/// <summary>
///
/// </summary>
public DateTime userupdatetime
{
set { _userupdatetime = value; }
get { return _userupdatetime; }
}
/// <summary>
/// 员工手机号码
/// </summary>
public string usermobile
{
set { _usermobile = value; }
get { return _usermobile; }
}
/// <summary>
///
/// </summary>
public string useremail
{
set{ _useremail=value;}
get{return _useremail;}
}
#endregion Model
}
}
|
using SnowBLL.Validators.Routes;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace SnowBLL.Models.Routes
{
public class RouteCreateModel : IValidatableObject
{
/// <summary>
/// Name of route
/// </summary>
public string Name { get; set; }
/// <summary>
///
/// </summary>
public string Line { get; set; }
public short Difficulty { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var validator = new RouteCreateModelValidator();
var result = validator.Validate(this);
return result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new[] { item.PropertyName }));
}
}
}
|
using UnityEngine;
using System.Collections;
public class LoseCollider : MonoBehaviour {
/*
* Since this minigame was first written in using a two year old version of the Unity C# API, some of the physics
* implementation does not function as we had hoped. Due to time restraints we opted to make quick fixes regarding
* some deprecated functions, switching them out for what Unity had suggested. The result of this is that the ball
* bounces in an awkward way.
*/
private LevelManager levelManager;
void OnTriggerEnter2D (Collider2D trigger) {
levelManager = GameObject.FindObjectOfType<LevelManager>();
BackgroundMusic.Pause ();
levelManager.endGameScreen();
}
void OnCollisionEnter2D (Collision2D collision) {
print ("Collision");
}
}
|
using Robust.Shared.Prototypes;
namespace Content.Server.GameTicking.Rules;
[Prototype("gameRule")]
public sealed class GameRulePrototype : IPrototype
{
[IdDataFieldAttribute]
public string ID { get; } = default!;
}
|
using System;
using Compl.CodeAnalysis.Binding;
using Compl.CodeAnalysis.Syntax;
namespace Compl.CodeAnalysis
{
internal sealed class Evaluator
{
private readonly BoundExpression _root;
public Evaluator(BoundExpression root)
{
_root = root;
}
public object Evaluate()
{
return EvaluateExpression(_root);
}
private object EvaluateExpression(BoundExpression node)
{
if (node is BoundLiteralExpression n)
return n.Value;
if (node is BoundUnaryExpression u)
{
var operand = EvaluateExpression(u.Operand);
switch (u.OperatorKind)
{
case BoundUnaryOperatorKind.Identity:
return (int)operand;
case BoundUnaryOperatorKind.Negation:
return -(int)operand;
case BoundUnaryOperatorKind.LogicalNegation:
return !(bool)operand;
default:
throw new Exception($"Unexepected unary operator {u.OperatorKind}");
}
}
if (node is BoundBinaryExpression b)
{
var left = EvaluateExpression(b.Left);
var right = EvaluateExpression(b.Right);
switch (b.OperatorKind)
{
case BoundBinaryOperatorKind.Addition:
return (int)left + (int)right;
case BoundBinaryOperatorKind.Subtraction:
return (int)left - (int)right;
case BoundBinaryOperatorKind.Multiplication:
return (int)left * (int)right;
case BoundBinaryOperatorKind.Division:
return (int)left / (int)right;
case BoundBinaryOperatorKind.LogicalAnd:
return (bool)left && (bool)right;
case BoundBinaryOperatorKind.LogicalOr:
return (bool)left || (bool)right;
default:
throw new Exception($"Unexepected binary operator {b.OperatorKind}");
}
}
throw new Exception($"Unexepected node {node.Kind}");
}
}
} |
namespace InterfaceExample
{
public class Fruit : StoreItem, IItem
{
private string name;
private double price;
public Fruit(string name, double price,double calories) : base(calories)
{
this.name = name;
this.price = price;
}
public override double Price => this.price;
public string Name => this.name;
}
}
|
using UnityEngine;
using UnityEditor;
using Ardunity;
[CustomEditor(typeof(DeviceRollReactor))]
public class DeviceRollReactorEditor : ArdunityObjectEditor
{
bool foldout = false;
SerializedProperty script;
SerializedProperty invert;
SerializedProperty OnActive;
SerializedProperty OnDeactive;
void OnEnable()
{
script = serializedObject.FindProperty("m_Script");
invert = serializedObject.FindProperty("invert");
OnActive = serializedObject.FindProperty("OnActive");
OnDeactive = serializedObject.FindProperty("OnDeactive");
}
public override void OnInspectorGUI()
{
this.serializedObject.Update();
//DeviceRollReactor reactor = (DeviceRollReactor)target;
GUI.enabled = false;
EditorGUILayout.PropertyField(script, true, new GUILayoutOption[0]);
GUI.enabled = true;
EditorGUILayout.PropertyField(invert, new GUIContent("invert"));
foldout = EditorGUILayout.Foldout(foldout, "Events");
if(foldout)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(OnActive, new GUIContent("OnActive"));
EditorGUILayout.PropertyField(OnDeactive, new GUIContent("OnDeactive"));
EditorGUI.indentLevel--;
}
this.serializedObject.ApplyModifiedProperties();
}
static public void AddMenuItem(GenericMenu menu, GenericMenu.MenuFunction2 func)
{
string menuName = "Unity/Add Reactor/Device/DeviceRollReactor";
if(Selection.activeGameObject != null)
menu.AddItem(new GUIContent(menuName), false, func, typeof(DeviceRollReactor));
else
menu.AddDisabledItem(new GUIContent(menuName));
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace HullSpeed
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Sailboat mySailboat;
public MainWindow()
{
InitializeComponent();
mySailboat = new Sailboat();
}
private void CalcButton_OnClick(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(LengthTextBox.Text) || LengthTextBox.Text.All(char.IsNumber)==false)
{
MessageBox.Show("Insert the lenght of the ship");
}
else
{
HullSpeedResultLabel.Content = mySailboat.Hullspeed();
}
}
private void MainWindow_OnKeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.IsKeyDown(Key.LeftCtrl) & Keyboard.IsKeyDown(Key.L))
{
this.FontSize = this.FontSize + 2;
}
else if (Keyboard.IsKeyDown(Key.LeftCtrl) & Keyboard.IsKeyDown(Key.S))
{
this.FontSize = this.FontSize - 2;
}
}
private void UIElement_OnMouseUp(object sender, MouseButtonEventArgs e)
{
if (string.IsNullOrEmpty(NameTextBox.Text) == false)
{
MessageBox.Show("The name of the ship is " + mySailboat.Name);
}
}
private void NameTextBox_OnTextChanged(object sender, TextChangedEventArgs e)
{
mySailboat.Name = NameTextBox.Text;
}
private void LengthTextBox_OnTextChanged(object sender, TextChangedEventArgs e)
{
mySailboat.Length = double.Parse(LengthTextBox.Text);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XFCovidTrack.ViewModels;
namespace XFCovidTrack.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class HealthcarePage : ContentPage
{
public List<Person> Data { get; set; }
public HealthcarePage()
{
InitializeComponent();
Data = new List<Person>()
{
new Person { Name = "David", Height = 180 },
new Person { Name = "Michael", Height = 170 },
new Person { Name = "Steve", Height = 160 },
new Person { Name = "Joel", Height = 182 }
};
BindingContext = new ChartMV();
// test.ItemsSource = Data;
}
}
public class Person
{
public string Name { get; set; }
public double Height { get; set; }
}
} |
namespace AutoTests.Framework.Models.PropertyAttributes
{
public class DisabledAttribute : PropertyAttribute
{
}
} |
using BDTest.Maps;
using BDTest.Test;
namespace BDTest.NetCore.Razor.ReportMiddleware.Models;
public class ChartViewModel
{
public int Index { get; set; }
public List<Scenario> Scenarios { get; set; }
public List<BDTestOutputModel> Reports { get; set; }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
namespace db_project
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Database db = new Database();
string[] ids;
string tables;
string fields;
List<string> searchOptions;
System.Data.DataView dataBuff;
string[] idsBuff;
public MainWindow()
{
InitializeComponent();
Connect();
//db.InitializeDefaultConnection();
}
void Connect()
{
ConnectionWindow w = new ConnectionWindow(db);
w.ShowDialog();
if (db.connection == null)
{
buttonCreateRelation.IsEnabled = buttonDeleteRelation.IsEnabled = false;
buttonDelete.IsEnabled = buttonCreate.IsEnabled = buttonUpdate.IsEnabled = false;
button.IsEnabled = false;
tableSelectionComboBox.IsEnabled = false;
}
else
{
buttonCreateRelation.IsEnabled = buttonDeleteRelation.IsEnabled = true;
buttonDelete.IsEnabled = buttonCreate.IsEnabled = buttonUpdate.IsEnabled = true;
button.IsEnabled = true;
tableSelectionComboBox.IsEnabled = true;
}
}
void LoadTable()
{
tables = "";
fields = "";
string where = "";
string order = "";
searchOptions = new List<string>();
switch (tableSelectionComboBox.Text)
{
case "Artists":
tables = "artist";
fields = "artist.artist_id as id, first_name, last_name";
where = "artist.artist_id IS NOT NULL";
order = "artist.artist_id";
searchOptions.Add("First name");
searchOptions.Add("Last name");
if (addCheckBox0.IsChecked.Value)
{
fields += ", internet_site.site, artist_site.username";
tables += ", artist_site, internet_site";
where = "artist.artist_id = artist_site.artist_id AND internet_site.site_id = artist_site.site_id";
searchOptions.Add("Site");
searchOptions.Add("Username");
}
break;
case "Paintings":
fields = "painting.painting_id as id, artist.first_name as artist, artist.last_name, painting.title as name, painting.technique, painting.year";
tables = "painting, artist";
where = "artist.artist_id = painting.artist_id";
order = "painting_id";
searchOptions.Add("Artist first name");
searchOptions.Add("Artist last name");
searchOptions.Add("Painting name");
searchOptions.Add("Technique");
searchOptions.Add("Year");
break;
case "Exhibitions":
tables = "exhibition";
fields = "exhibition.exhibition_id as id, exhibition_name as exhibition";
where = "exhibition.exhibition_id IS NOT NULL";
order = "exhibition.exhibition_id";
searchOptions.Add("Exhibition name");
if (addCheckBox0.IsChecked.Value)
{
fields += ", painting.title as painting";
tables += ", painting_exhibition, painting";
where += " AND exhibition.exhibition_id = painting_exhibition.exhibition_id AND painting.painting_id = painting_exhibition.painting_id";
searchOptions.Add("Painting name");
}
if (addCheckBox1.IsChecked.Value)
{
fields += ", address, city, country";
tables += ", address, city, country";
where += " AND exhibition.address_id = address.address_id AND address.city_id = city.city_id AND city.country_id = country.country_id";
searchOptions.Add("Address");
searchOptions.Add("City");
searchOptions.Add("Country");
}
break;
case "Auctions":
tables = "auction";
fields = "auction.auction_id as id, auction_name as auction";
where = "auction.auction_id IS NOT NULL";
order = "auction.auction_id";
searchOptions.Add("Auction name");
if (addCheckBox0.IsChecked.Value)
{
fields += ", painting.title as painting";
tables += ", painting_auction, painting";
where += " AND auction.auction_id = painting_auction.auction_id AND painting.painting_id = painting_auction.painting_id";
searchOptions.Add("Painting name");
}
if (addCheckBox1.IsChecked.Value)
{
fields += ", address, city, country";
tables += ", address, city, country";
where += " AND auction.address_id = address.address_id AND address.city_id = city.city_id AND city.country_id = country.country_id";
searchOptions.Add("Address");
searchOptions.Add("City");
searchOptions.Add("Country");
}
break;
case "Sites":
fields = "site_id as id, site";
tables = "internet_site";
where = "site_id IS NOT NULL";
order = "site_id";
searchOptions.Add("Site");
break;
default:
return;
}
var data = db.LoadTable(fields, tables, where, order);
ids = new string[data.Table.Rows.Count];
for (int i = 0; i < ids.Length; i++)
ids[i] = data.Table.Rows[i].ItemArray[0].ToString();
data.Table.Columns.RemoveAt(0);
dataGrid.ItemsSource = data;
idsBuff = ids;
dataBuff = data;
searchFieldComboBox.ItemsSource = searchOptions;
Search(); //не очень хорошо оставлять это здесь(!!!)
}
void DeleteSelectedItem()
{
if (tables == null)
return;
//Начало транзакции
db.BeginTransaction();
string table = tables.Split(',')[0];
string idField = fields.Split(' ')[0];
int idIndex = dataGrid.SelectedIndex;
if (idIndex == -1)
return;
MessageBoxResult r = MessageBox.Show("Are you sure you want to delete this item?","", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (r == MessageBoxResult.Yes)
if (CheckCascade(table))
db.DeleteEntity(table, idField, ids[idIndex]);
db.EndTransaction(true); //? менять значение?
}
bool CheckCascade(string table)
{
int idIndex = dataGrid.SelectedIndex;
string subquery;
switch (table)
{
case "artist":
subquery = String.Format("SELECT painting_id FROM painting WHERE artist_id = {0};", ids[idIndex]);
var data = db.ExecuteQuery(subquery);
if (data.Table.Rows.Count > 0)
{
MessageBoxResult r = MessageBox.Show("All the artist's paintings will be deleted!", "Warning", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
if (r == MessageBoxResult.OK)
{
db.DeleteEntity("painting", "artist_id", ids[idIndex]);
}
else
{
return false;
}
}
db.DeleteEntity("artist_site", "artist_id", ids[idIndex]);
return true;
case "painting":
db.DeleteEntity("painting_exhibition", "painting_id", ids[idIndex]);
db.DeleteEntity("painting_auction", "painting_id", ids[idIndex]);
return true;
case "exhibition":
db.DeleteEntity("painting_exhibition", "exhibition_id", ids[idIndex]);
//TODO : удалять адрес, город, страну, и даже небо, даже Аллаха...
return true;
case "auction":
db.DeleteEntity("painting_auction", "auction_id", ids[idIndex]);
return true;
case "internet_site":
db.DeleteEntity("artist_site", "site_id", ids[idIndex]);
return true;
}
return false;
}
void UpdateSelectedItem()
{
if (tables == null)
return;
string table = tables.Split(',')[0];
string idField = fields.Split(' ')[0];
int idIndex = dataGrid.SelectedIndex;
if (idIndex == -1)
return;
UpdateWindow w = new UpdateWindow(db, table, idField, ids[idIndex]);
w.ShowDialog();
LoadTable();
}
void Search()
{
if (searchFieldComboBox.SelectedIndex < 0)
return;
List<string> newIds = new List<string>();
System.Data.DataView t = new System.Data.DataView(dataBuff.ToTable());
int deleted = 0;
for (int i = 0; i < dataBuff.Table.Rows.Count; i++)
{
if (exactMatchCheckBox.IsChecked.Value)
{
if (dataBuff.Table.Rows[i].ItemArray[searchFieldComboBox.SelectedIndex].ToString() != searchTextBox.Text)
{
t.Table.Rows[i - deleted].Delete();
deleted++;
continue;
}
}
else
{
if (!dataBuff.Table.Rows[i].ItemArray[searchFieldComboBox.SelectedIndex].ToString().Contains(searchTextBox.Text))
{
t.Table.Rows[i - deleted].Delete();
deleted++;
continue;
}
}
newIds.Add(idsBuff[i]);
}
ids = newIds.ToArray();
dataGrid.ItemsSource = t;
}
void CancelSearch()
{
ids = idsBuff;
dataGrid.ItemsSource = dataBuff;
}
private void tableSelectionComboBox_SelectionChanged(object sender, EventArgs e)
{
switch (tableSelectionComboBox.Text)
{
case "Artists":
addCheckBox0.Visibility = Visibility.Visible;
addCheckBox0.IsChecked = false;
addCheckBox0.Content = "Show sites";
addCheckBox1.Visibility = Visibility.Hidden;
break;
case "Exhibitions":
addCheckBox0.Visibility = Visibility.Visible;
addCheckBox0.IsChecked = false;
addCheckBox0.Content = "Show paintings";
addCheckBox1.Visibility = Visibility.Visible;
addCheckBox1.IsChecked = false;
addCheckBox1.Content = "Show address";
break;
case "Auctions":
addCheckBox0.Visibility = Visibility.Visible;
addCheckBox0.IsChecked = false;
addCheckBox0.Content = "Show paintings";
addCheckBox1.Visibility = Visibility.Visible;
addCheckBox1.IsChecked = false;
addCheckBox1.Content = "Show address";
break;
default:
addCheckBox0.Visibility = Visibility.Hidden;
addCheckBox1.Visibility = Visibility.Hidden;
break;
}
LoadTable();
}
private void addCheckBox0_Click(object sender, RoutedEventArgs e)
{
LoadTable();
}
private void addCheckBox1_Click(object sender, RoutedEventArgs e)
{
LoadTable();
}
private void buttonCreate_Click(object sender, RoutedEventArgs e)
{
CreateWindow w = new CreateWindow(db);
w.ShowDialog();
LoadTable();
}
private void buttonCreateRelation_Click(object sender, RoutedEventArgs e)
{
CreateRelationWindow w = new CreateRelationWindow(db);
w.Show();
}
private void buttonDelete_Click(object sender, RoutedEventArgs e)
{
DeleteSelectedItem();
LoadTable();
}
private void buttonUpdate_Click(object sender, RoutedEventArgs e)
{
UpdateSelectedItem();
}
private void buttonDeleteRelation_Click(object sender, RoutedEventArgs e)
{
deleteRelationWindow w = new deleteRelationWindow(db);
w.ShowDialog();
}
private void buttonSearch_Click(object sender, RoutedEventArgs e)
{
Search();
}
private void searchTextBox_KeyDown(object sender, KeyEventArgs e)
{
Search();
}
private void buttonCancelSearch_Click(object sender, RoutedEventArgs e)
{
CancelSearch();
}
private void searchTextBox_GotFocus(object sender, RoutedEventArgs e)
{
if (searchTextBox.Text == "Search")
searchTextBox.Text = "";
}
private void button_Click(object sender, RoutedEventArgs e)
{
string[] allTables = new string[] { "artist", "artist_site", "internet_site",
"painting", "painting_exhibition", "exhibition",
"painting_auction", "auction", "address", "city", "country"};
System.Data.DataSet ds = new System.Data.DataSet("artist_database");
for (int i = 0; i < allTables.Length; i++)
{
System.Data.DataTable t = db.LoadTable(allTables[i]).ToTable(allTables[i]);
ds.Tables.Add(t);
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "XML|*.xml";
string fname;
if (saveFileDialog.ShowDialog() == true)
{
fname = saveFileDialog.FileName;
ds.WriteXml(fname);
ds.WriteXmlSchema(fname + "_shema.xml");
}
}
private void buttonRefreshConn_Click(object sender, RoutedEventArgs e)
{
Connect();
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
namespace Labirintus
{
/// <summary>
/// Interaction logic for Jatekter.xaml
/// </summary>
public partial class Jatekter : Window
{
private Labyrinth lab;
public Jatekter()
{
InitializeComponent();
lab = new Labyrinth(labirintus);
lab.Megjelenit();
}
public Jatekter(string fajlnev)
{
InitializeComponent();
lab = new Labyrinth(labirintus, fajlnev);
lab.Megjelenit();
}
private void BtnVissza_Click(object sender, RoutedEventArgs e)
{
MessageBoxResult result = MessageBox.Show("Biztosan ki akar lépni a főmenübe?", "Visszalépés", MessageBoxButton.YesNo);
if (result == MessageBoxResult.Yes)
{
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
this.Close();
}
}
private void BtnBalra_Click(object sender, RoutedEventArgs e)
{
lab.Fordulas('B');
}
private void BtnElore_Click(object sender, RoutedEventArgs e)
{
lab.Elore();
lbLepesek.Content = "Eddig megtett lépések: " + lab.a;
}
private void BtnJobbra_Click(object sender, RoutedEventArgs e)
{
lab.Fordulas('J');
}
private void BtnAutomata_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start("https://youtu.be/dQw4w9WgXcQ");
}
}
internal class Labyrinth
{
public int a = 0;
private char[,] Labirint;
private Grid labirintus;
private Border[,] cellak;
private Pos jatekos = new Pos(1, 1);
public Labyrinth(Grid labirintus, string fajlnev)
{
this.labirintus = labirintus;
Labirint = new char[9, 9];
for (int i = 0; i < 9; i++)
{
labirintus.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
labirintus.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
}
cellak = new Border[9, 9];
for (int i = 0; i < 9 * 9; i++)
{
cellak[i / 9, i % 9] = new Border();
cellak[i / 9, i % 9].KeyDown += Lenyom;
labirintus.Children.Add(cellak[i / 9, i % 9]);
Grid.SetRow(cellak[i / 9, i % 9], i / 9);
Grid.SetColumn(cellak[i / 9, i % 9], i % 9);
}
string[] forras = new string[9];
int index = 0;
StreamReader sr = new StreamReader(fajlnev);
while (!sr.EndOfStream)
{
forras[index] = sr.ReadLine();
index++;
}
sr.Close();
for (int sor = 0; sor < 9; sor++)
{
for (int oszlop = 0; oszlop < 9; oszlop++)
{
Labirint[sor, oszlop] = forras[sor][oszlop];
}
}
}
public Labyrinth(Grid labirintus)
{
this.labirintus = labirintus;
Labirint = new char[9, 9];
for (int i = 0; i < 9; i++)
{
labirintus.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
labirintus.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
}
cellak = new Border[9, 9];
for (int i = 0; i < 9 * 9; i++)
{
cellak[i / 9, i % 9] = new Border();
cellak[i / 9, i % 9].KeyDown += Lenyom;
labirintus.Children.Add(cellak[i / 9, i % 9]);
Grid.SetRow(cellak[i / 9, i % 9], i / 9);
Grid.SetColumn(cellak[i / 9, i % 9], i % 9);
}
GenerateLabyrinth();
}
public void Megjelenit()
{
for (int sor = 0; sor < 9; sor++)
{
for (int oszlop = 0; oszlop < 9; oszlop++)
{
Border cella = cellak[sor, oszlop];
if (oszlop == 1 && sor == 1)
{
// 1. sor, 1. oszlop, a játékos alphelyzete
System.Windows.Point Point1 = new System.Windows.Point(26.8, 40.2);
System.Windows.Point Point2 = new System.Windows.Point(13.4, 13.4);
System.Windows.Point Point3 = new System.Windows.Point(40.2, 13.4);
PointCollection myPointCollection = new PointCollection();
myPointCollection.Add(Point1);
myPointCollection.Add(Point2);
myPointCollection.Add(Point3);
cella.Child = new Polygon() { Stroke = Brushes.Black, StrokeThickness = 4, Fill = Brushes.Green, Points = myPointCollection, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
}
else if (Labirint[sor, oszlop] == '*')
{
cella.Background = Brushes.Black;
}
else if (Labirint[sor, oszlop] == '.')
{
cella.Background = null;
}
}
}
}
private void Lenyom(object sender, KeyEventArgs args)
{
}
private struct Pos
{
public int x, y;
public Pos(int x, int y)
{
this.x = x;
this.y = y;
}
}
private struct Jatekos
{
public Pos pozició;
public char irány;
public Jatekos(Pos poz, char ir)
{
pozició = poz;
irány = ir;
}
public Jatekos(int x, int y, char ir)
{
pozició = new Pos(x, y);
irány = ir;
}
}
private enum LabyrinthOptions
{
Nothing, Road, Wall
}
private Random rnd = new Random();
private int canCreateExit = 10;
public async void GenerateLabyrinth()
{
Stack<Pos> createdRoads = new Stack<Pos>();
createdRoads.Push(new Pos(1, 1));
bool[,] visited = new bool[9, 9];
visited[1, 1] = true;
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
Labirint[x, y] = (x % 2 == 1 && y % 2 == 1) ? '.' : '*';
}
}
int visitedCount = 0;
void Visit(Pos position)
{
List<Pos> unvisitedNeighbours = new List<Pos>();
if (IsNotVisited(position.x + 2, position.y)) unvisitedNeighbours.Add(new Pos(position.x + 2, position.y));
if (IsNotVisited(position.x - 2, position.y)) unvisitedNeighbours.Add(new Pos(position.x - 2, position.y));
if (IsNotVisited(position.x, position.y + 2)) unvisitedNeighbours.Add(new Pos(position.x, position.y + 2));
if (IsNotVisited(position.x, position.y - 2)) unvisitedNeighbours.Add(new Pos(position.x, position.y - 2));
if (unvisitedNeighbours.Count > 0)
{
createdRoads.Push(position);
Pos choosenPos = unvisitedNeighbours[rnd.Next(0, unvisitedNeighbours.Count)];
Labirint[(choosenPos.x + position.x) / 2, (choosenPos.y + position.y) / 2] = '.';
visited[choosenPos.x, choosenPos.y] = true;
createdRoads.Push(choosenPos);
visitedCount++;
}
}
bool IsNotVisited(int x, int y)
{
return x > 0 && x < 8 && y > 0 && y < 8 && !visited[x, y];
}
while (createdRoads.Count > 0 && visitedCount < 15)
{
Pos currentPos = createdRoads.Pop();
Visit(currentPos);
Megjelenit();
await Task.Delay(100);
}
Labirint[8, 7] = '.';
Megjelenit();
}
private char jatekPoz = 'V';
private int poz = 0;
private RotateTransform elforgatas = new RotateTransform(0);
private long forditas = 0;
public void Fordulas(char merre)
{
char[] poziciok = new char[] { 'V', '<', '^', '>' };
forditas++;
if (merre.Equals('J')) { poz++; elforgatas = new RotateTransform(forditas += 90); }
else { poz--; elforgatas = new RotateTransform(forditas -= 90); }
if (poz == 0 || poz == 4 || poz == -4) { poz = 0; jatekPoz = poziciok[poz]; }
else if (poz > 0) { jatekPoz = poziciok[poz]; }
else
{
if (poz == -1) { poz = 3; jatekPoz = poziciok[3]; }
else if (poz == -2) { poz = 2; jatekPoz = poziciok[2]; }
else if (poz == -3) { poz = 1; jatekPoz = poziciok[1]; }
}
int sor = 1; int oszlop = 1;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (cellak[i, j].Child != null)
{
sor = i; oszlop = j;
}
}
}
elforgatas.CenterX = 23.5;
elforgatas.CenterY = 40.5;
cellak[sor, oszlop].Child.RenderTransform = elforgatas;
}
public void Elore()
{
int sor = 1; int oszlop = 1;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (cellak[i, j].Child != null)
{
sor = i; oszlop = j;
}
}
}
try
{
switch (jatekPoz)
{
case 'V':
if (cellak[sor + 1, oszlop].Background == null)
{
cellak[sor, oszlop].Child = null;
System.Windows.Point PointDel1 = new System.Windows.Point(26.8, 40.2);
System.Windows.Point PointDel2 = new System.Windows.Point(13.4, 13.4);
System.Windows.Point PointDel3 = new System.Windows.Point(40.2, 13.4);
PointCollection myPointCollectionDel = new PointCollection();
myPointCollectionDel.Add(PointDel1);
myPointCollectionDel.Add(PointDel2);
myPointCollectionDel.Add(PointDel3);
cellak[sor + 1, oszlop].Child = new Polygon() { Stroke = Brushes.Black, StrokeThickness = 4, Fill = Brushes.Green, Points = myPointCollectionDel, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
a++;
}
break;
case '<':
if (cellak[sor, oszlop - 1].Background == null)
{
cellak[sor, oszlop].Child = null;
System.Windows.Point PointNyugat1 = new System.Windows.Point(26.8, 40.2);
System.Windows.Point PointNyugat2 = new System.Windows.Point(13.4, 13.4);
System.Windows.Point PointNyugat3 = new System.Windows.Point(40.2, 13.4);
PointCollection myPointCollectionNyugat = new PointCollection();
myPointCollectionNyugat.Add(PointNyugat1);
myPointCollectionNyugat.Add(PointNyugat2);
myPointCollectionNyugat.Add(PointNyugat3);
cellak[sor, oszlop - 1].Child = new Polygon() { Stroke = Brushes.Black, StrokeThickness = 4, Fill = Brushes.Green, Points = myPointCollectionNyugat, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
RotateTransform elforgatas = new RotateTransform(90);
elforgatas.CenterX = 23;
elforgatas.CenterY = 40.5;
cellak[sor, oszlop - 1].Child.RenderTransform = elforgatas;
a++;
}
break;
case '^':
if (cellak[sor - 1, oszlop].Background == null)
{
cellak[sor, oszlop].Child = null;
System.Windows.Point PointEszak1 = new System.Windows.Point(26.8, 40.2);
System.Windows.Point PointEszak2 = new System.Windows.Point(13.4, 13.4);
System.Windows.Point PointEszak3 = new System.Windows.Point(40.2, 13.4);
PointCollection myPointCollectionEszak = new PointCollection();
myPointCollectionEszak.Add(PointEszak1);
myPointCollectionEszak.Add(PointEszak2);
myPointCollectionEszak.Add(PointEszak3);
cellak[sor - 1, oszlop].Child = new Polygon() { Stroke = Brushes.Black, StrokeThickness = 4, Fill = Brushes.Green, Points = myPointCollectionEszak, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
RotateTransform elforgatas = new RotateTransform(-180);
elforgatas.CenterX = 23;
elforgatas.CenterY = 40.5;
cellak[sor - 1, oszlop].Child.RenderTransform = elforgatas;
a++;
}
break;
case '>':
if (cellak[sor, oszlop + 1].Background == null)
{
cellak[sor, oszlop].Child = null;
System.Windows.Point PointKelet1 = new System.Windows.Point(26.8, 40.2);
System.Windows.Point PointKelet2 = new System.Windows.Point(13.4, 13.4);
System.Windows.Point PointKelet3 = new System.Windows.Point(40.2, 13.4);
PointCollection myPointCollectionKelet = new PointCollection();
myPointCollectionKelet.Add(PointKelet1);
myPointCollectionKelet.Add(PointKelet2);
myPointCollectionKelet.Add(PointKelet3);
cellak[sor, oszlop + 1].Child = new Polygon() { Stroke = Brushes.Black, StrokeThickness = 4, Fill = Brushes.Green, Points = myPointCollectionKelet, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
RotateTransform elforgatas = new RotateTransform(-90);
elforgatas.CenterX = 23;
elforgatas.CenterY = 40.5;
cellak[sor, oszlop + 1].Child.RenderTransform = elforgatas;
a++;
}
break;
default:
break;
}
}
catch (Exception)
{
MessageBox.Show("Gratulálunk! Kijutottál.");
}
}
}
} |
using SimpleSpace.Core;
using UnityEngine;
namespace SimpleSpace.NonECS
{
public class VFXComponent : MonoBehaviour
{
[SerializeField]
private ParticleListener _particleListener = null;
private void Start()
{
GetComponents();
}
private void OnEnable()
{
_particleListener.ParticleStopped += RecycleParticle;
}
[ContextMenu("Grab Components")]
private void GetComponents()
{
if (_particleListener == null)
{
_particleListener = GetComponentInChildren<ParticleListener>();
}
}
private void RecycleParticle()
{
PoolManager.instance.ReturnToPool(gameObject);
}
private void OnDisable()
{
_particleListener.ParticleStopped -= RecycleParticle;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IdomOffice.Core.Config
{
public class ConfigStringInfo:ConfigInfo
{
public string GetValue(string key)
{
var item = LoadJson().Find(m => m.Key == key);
string itemtype = item.KeyType;
string itemvalue = item.Value;
return itemvalue;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EBS.Infrastructure.Task;
using Dapper.DBContext;
using EBS.Infrastructure;
using EBS.Infrastructure.Log;
namespace EBS.Domain.Service
{
/// <summary>
/// 月库存自动任务:每月1日执行,保存上月库存
/// </summary>
public class StoreInventoryMonthlyTask:ITask
{
IDBContext _db;
ILogger _log;
public StoreInventoryMonthlyTask()
{
_db = AppContext.Current.Resolve<IDBContext>();
_log = AppContext.Current.Resolve<ILogger>();
}
public void Execute()
{
var today = DateTime.Now;
var todayString =today.ToString("yyyy-MM-dd HH:mm:ss");
_log.Info("执行{0}库存存储自动任务", todayString);
if (today.AddDays(1).Day == 1)
{
// 每天 00:03分 执行
_log.Info("时间条件{0}是月末,开始存储当月库存", todayString);
string sql = @"insert into StoreInventoryMonthly (Monthly,StoreId,ProductId,Quantity,AvgCostPrice)
select @Monthly,StoreId,ProductId,Quantity,AvgCostPrice from StoreInventory";
_db.Command.Execute(sql, new { Monthly = today.ToString("yyyy-MM") });
}
else
{
_log.Info("时间条件{0}不满足,结束任务", todayString);
}
_log.Info("任务执行完毕");
}
}
}
|
namespace ModelTransformationComponent.SystemRules
{
/// <summary>
/// Системная конструкция однострочного комментария
/// <para/>
/// Наследует <see cref="SystemRule"/>
/// </summary>
public class Comment : SystemRule
{
/// <summary>
/// Литерал конструкции однострочного комментария
/// </summary>
public override string Literal=> "//";
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using Framework.Core.Common;
using Tests.Data.Oberon;
namespace Tests.Helpers
{
public class DataFileGenerator
{
private DataTable _dataTable;
private DataFileType _fileType;
public DataFileGenerator(DataFileType fileType)
{
_dataTable=new DataTable();
_fileType = fileType;
}
public DataFileGenerator AddColumn(string columnName, Type type)
{
_dataTable.Columns.Add(columnName, type);
return this;
}
public DataFileGenerator AddRow(params object[] columnValues)
{
if (columnValues.Length > 0)
{
DataRow newRow = _dataTable.NewRow();
for (int i = 0; i < columnValues.Length; i++)
{
var value = columnValues[i] ?? DBNull.Value;
newRow[i] = value;
}
_dataTable.Rows.Add(newRow);
}
return this;
}
/// <summary>
///
/// </summary>
/// <returns>filepath</returns>
public string Save(bool createHeaderRow, string deploymentDirectory)
{
if (!Directory.Exists(deploymentDirectory))
{
Directory.CreateDirectory(deploymentDirectory);
}
string fileName = GenerateFileName(_fileType);
string filePath = Path.Combine(deploymentDirectory, fileName);
while (File.Exists(filePath))
{
fileName = GenerateFileName(_fileType);
filePath = Path.Combine(deploymentDirectory, fileName);
}
if (_fileType == DataFileType.CSV)
{
SaveAsCsv(createHeaderRow,filePath);
}
return filePath;
}
private string GenerateFileName(DataFileType fileType)
{
string extension = fileType == DataFileType.CSV ? "csv" : "xls";
string fileName = FakeData.RandomNumberString(10) + "." + extension;
return fileName;
}
private void SaveAsCsv(bool createHeaderRow, string fileName)
{
var sb = new StringBuilder();
if (createHeaderRow)
{
IEnumerable<string> columnNames = _dataTable.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
}
foreach (DataRow row in _dataTable.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, sb.ToString());
}
}
}
|
using CsvHelper;
using System;
namespace Repository.ImportData.Extensions
{
public static class CsvReaderExtensions
{
public static string GetString(this CsvReader reader, int columnIndex)
{
return reader.GetField(columnIndex).Trim();
}
public static int? GetInt(this CsvReader reader, int columnIndex)
{
try
{
return int.Parse(reader.GetString(columnIndex));
}
catch { return null; }
}
public static double? GetDouble(this CsvReader reader, int columnIndex)
{
try
{
return Double.Parse(reader.GetString(columnIndex));
}
catch { return null; }
}
public static Decimal GetDecimal(this CsvReader reader, int columnIndex)
{
Decimal value;
Decimal.TryParse(reader.GetString(columnIndex), out value);
return value;
}
public static void SkipHeaders(this CsvReader reader, int count)
{
for (int i = 0; i < count; i++)
{
reader.Read();
reader.ReadHeader();
}
}
}
}
|
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Collections;
using CTCI.Models;
using System.Linq;
using System.Text.RegularExpressions;
using System;
using System.Data.Odbc;
//讀取shp 的相關文件
//http://blog.sina.com.cn/s/blog_80a9926b0101h8ux.html
namespace CTCI.Controllers
{
public class FieldMapController : Controller
{
CtciMachineEntities db = new CtciMachineEntities();
string file_path
{
get
{
string path = System.Web.Configuration.WebConfigurationManager.AppSettings["AttachedFilePath"];
if (Path.IsPathRooted(path))
{
return path;
}
return Server.MapPath(path);
}
}
class Polyline //線
{
public double[] Box = new double[4];
public int NumParts;
public int NumPoints;
public ArrayList Parts; //在部分中第一个点的索引
public ArrayList Points; //所有部分的点
}
class Fline //線
{
public Fline()
{
Color = "#ff7800";
}
public ArrayList Points; //所有部分的点
public string Color;
}
class pointD
{
public double x;
public double y;
}
public class FileModel
{
public int FieldID { get; set; }
public HttpPostedFileBase shpFile { get; set; }
public HttpPostedFileBase dbfFile { get; set; }
}
[HttpPost]
public ActionResult AddFieldMap(FileModel model)
{
if (model.FieldID == 0)
return Json(new { Success = false, Message = "FieldID null" });
if (model.shpFile == null)
return Json(new { Success = false, Message = "shpFile null" });
if(model.shpFile.FileName.Substring(model.shpFile.FileName.Length-4, 4) != ".shp")
return Json(new { Success = false, Message = "shpFile type error" });
if (model.dbfFile != null && model.dbfFile.FileName.Substring(model.dbfFile.FileName.Length - 4, 4) != ".dbf")
return Json(new { Success = false, Message = "dbfFile type error" });
DeleteFidldMap(model.FieldID);
bool shpflag = true;
bool dbfflag = true;
if (model.shpFile != null)
{
shpflag = SaveFile(model.shpFile, model.FieldID + ".shp");
}
if (model.dbfFile != null)
{
dbfflag = SaveFile(model.dbfFile, model.FieldID + ".dbf");
}
//確認是否存成功
if (!shpflag)
{
DeleteFidldMap(model.FieldID);
return Json(new { Success = false, Message = "shp save error" });
}
if (model.dbfFile != null)
{
if (!dbfflag)
{
DeleteFidldMap(model.FieldID);
return Json(new { Success = false, Message = "dbf save error" });
}
else
{
try
{
if (!checkCount(model.FieldID.ToString()))
{
DeleteFidldMap(model.FieldID);
return Json(new { Success = false, Message = "shp and dbf count not equal" });
}
}
catch (Exception ex)
{
DeleteFidldMap(model.FieldID);
//return Json(new { Success = false, Message = "can't read file, please check file and upload again" });
return Json(new { Success = false, Message = ex.ToString() });
}
DeleteFile(model.FieldID + ".dbf");
}
}
//確定OK
var newFieldMap = new c_FieldMap()
{
FieldID = model.FieldID,
FileName = model.FieldID.ToString()
};
db.c_FieldMap.Add(newFieldMap);
db.SaveChanges();
return Json(new { Success = true, Message = "OK" });
}
public bool SaveFile(HttpPostedFileBase File, string FileName)
{
try
{
if (!Directory.Exists(file_path))
Directory.CreateDirectory(file_path);
if (File.ContentLength > 0)
{
File.SaveAs(file_path + FileName);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
[HttpPost]
public ActionResult DeleteFidldMap(int FieldID)
{
try
{
DeleteFile(FieldID + ".shp");
DeleteFile(FieldID + ".dbf");
DeleteFile(FieldID + ".color");
var RAF = db.c_FieldMap.FirstOrDefault(x => x.FieldID == FieldID);
if (RAF != null)
{
db.c_FieldMap.Remove(RAF);
db.SaveChanges();
}
return Json("OK");
}
catch (Exception ex)
{
return Json(ex);
}
}
public bool DeleteFile(string FileName)
{
if (!System.IO.File.Exists(file_path + FileName))
return false;
System.IO.File.Delete(file_path + FileName);
return true;
}
[HttpPost]
public ActionResult ReadFieldMap(int FieldID)
{
var FieldMap = db.c_FieldMap.FirstOrDefault(x => x.FieldID == FieldID);
if (FieldMap == null)
return Json(null);
var filename = FieldMap.FileName;
ArrayList polylines = new ArrayList();
ArrayList Flines = new ArrayList();
if (!System.IO.File.Exists(file_path + filename + ".shp"))
return Json(null);
FileStream myFile = System.IO.File.Open(file_path + filename + ".shp", FileMode.Open);
//處理header
BinaryReader br = new BinaryReader(myFile);
br.ReadBytes(24);
int FileLength = br.ReadInt32();//<0代表数据长度未知
int FileBanben = br.ReadInt32();
int Shapetype = br.ReadInt32();
double xmin = br.ReadDouble();
double ymax = br.ReadDouble();
double xmax = br.ReadDouble();
double ymin = br.ReadDouble();
//取中心
Fline F_ = new Fline();
pointD mid = new pointD();
mid.x = (xmin + xmax) / 2;
mid.y = (ymin + ymax) / 2;
F_.Points = new ArrayList();
F_.Points.Add(mid);
Flines.Add(F_);
//略過Header結尾
br.ReadBytes(32);
//開始讀線
while (br.PeekChar() != -1)
{
Polyline polyline = new Polyline();
polyline.Box = new double[4];
polyline.Parts = new ArrayList();
polyline.Points = new ArrayList();
uint RecordNum = br.ReadUInt32();
int DataLength = br.ReadInt32();
//读取第i个记录
int tempI = br.ReadInt32();
polyline.Box[0] = br.ReadDouble();
polyline.Box[1] = br.ReadDouble();
polyline.Box[2] = br.ReadDouble();
polyline.Box[3] = br.ReadDouble();
polyline.NumParts = br.ReadInt32();
polyline.NumPoints = br.ReadInt32();
for (int i = 0; i < polyline.NumParts; i++)
{
int parts = new int();
parts = br.ReadInt32();
polyline.Parts.Add(parts);
}
for (int j = 0; j < polyline.NumPoints; j++)
{
pointD pointtemp = new pointD();
pointtemp.x = br.ReadDouble();
pointtemp.y = br.ReadDouble();
polyline.Points.Add(pointtemp);
}
polylines.Add(polyline);
}
myFile.Close();
//轉換成要用的model
for (int i = 0; i < polylines.Count; i++)
{
Fline F = new Fline();
F.Points = ((Polyline)polylines[i]).Points;
Flines.Add(F);
}
//標上顏色
if (System.IO.File.Exists(file_path + filename + ".color"))
{
string[] Colors = GetRGBColor_(filename + ".color");
if (Colors.Length == polylines.Count)
{
for (int i = 0; i < polylines.Count; i++)
{
((Fline)Flines[i]).Color = Colors[i].ToString();
}
}
}
var jsonResult = Json(Flines, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
bool checkCount(string FileName)
{
ArrayList polylines = new ArrayList();
int ColorCount = SaveRGBColor(FileName);
FileStream myFile = System.IO.File.Open(file_path + FileName + ".shp", FileMode.Open);
//處理header
BinaryReader br = new BinaryReader(myFile);
br.ReadBytes(100);
//開始讀線
while (br.PeekChar() != -1)
{
Polyline polyline = new Polyline();
polyline.Box = new double[4];
polyline.Parts = new ArrayList();
polyline.Points = new ArrayList();
uint RecordNum = br.ReadUInt32();
int DataLength = br.ReadInt32();
//读取第i个记录
int tempI = br.ReadInt32();
polyline.Box[0] = br.ReadDouble();
polyline.Box[1] = br.ReadDouble();
polyline.Box[2] = br.ReadDouble();
polyline.Box[3] = br.ReadDouble();
polyline.NumParts = br.ReadInt32();
polyline.NumPoints = br.ReadInt32();
for (int i = 0; i < polyline.NumParts; i++)
{
int parts = new int();
parts = br.ReadInt32();
polyline.Parts.Add(parts);
}
for (int j = 0; j < polyline.NumPoints; j++)
{
pointD pointtemp = new pointD();
pointtemp.x = br.ReadDouble();
pointtemp.y = br.ReadDouble();
polyline.Points.Add(pointtemp);
}
polylines.Add(polyline);
}
myFile.Close();
return polylines.Count == ColorCount;
}
//讀.dbf
ArrayList GetRGBColor(string FileName)
{
ArrayList Colors = new ArrayList();
string cnstr = "Driver={Microsoft dBase Driver (*.dbf)}; SourceType=DBF; SourceDB=" + file_path + FileName + "; Exclusive=No; Collate=Machine; NULL=NO; DELETED=NO; BACKGROUNDFETCH=NO;";
using (OdbcConnection connect = new OdbcConnection())
{
OdbcCommand cmd = new OdbcCommand();
cmd.Connection = connect;
connect.ConnectionString = cnstr;
connect.Open();
cmd.CommandText = "select RGBColor from " + file_path + FileName;
OdbcDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Colors.Add(reader.GetString(0));
}
reader.Close();
connect.Close();
}
return Colors;
}
//讀.color
string[] GetRGBColor_(string FileName)
{
string[] colors = System.IO.File.ReadAllLines(file_path + FileName);
return colors;
}
//轉檔用
int SaveRGBColor(string FileName)
{
if (!System.IO.File.Exists(file_path + FileName + ".color"))
System.IO.File.Delete(file_path + FileName + ".color");
int count = 0;
string cnstr = "Driver={Microsoft dBase Driver (*.dbf)}; SourceType=DBF; SourceDB=" + file_path + FileName + ".dbf; Exclusive=No; Collate=Machine; NULL=NO; DELETED=NO; BACKGROUNDFETCH=NO;";
using (OdbcConnection connect = new OdbcConnection())
{
OdbcCommand cmd = new OdbcCommand();
cmd.Connection = connect;
connect.ConnectionString = cnstr;
connect.Open();
cmd.CommandText = "select RGBColor from " + file_path + FileName + ".dbf";
OdbcDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
count++;
System.IO.File.AppendAllText(file_path + FileName + ".color", reader.GetString(0) + Environment.NewLine);
}
reader.Close();
connect.Close();
}
return count;
}
/*
public void test()
{
string shpfilepath = "";
using (System.Windows.Forms.OpenFileDialog)
{ }
openFileDialog1.Filter = "shapefiles(*.shp)|*.shp|All files(*.*)|*.*";//打开文件路径
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
shpfilepath = openFileDialog1.FileName;
BinaryReader br = new BinaryReader(openFileDialog1.OpenFile());
//读取文件过程
br.ReadBytes(24);
int FileLength = br.ReadInt32();//<0代表数据长度未知
int FileBanben = br.ReadInt32();
ShapeType = br.ReadInt32();
xmin = br.ReadDouble();
ymax = -1 * br.ReadDouble();
xmax = br.ReadDouble();
ymin = -1 * br.ReadDouble();
double width = xmax - xmin;
double height = ymax - ymin;
//n1 = (float)(this.panel1.Width * 0.9 / width);//x轴放大倍数
//n2 = (float)(this.panel1.Height * 0.9 / height);//y轴放大倍数
br.ReadBytes(32);
switch (ShapeType)
{
case 1:
points.Clear();
while (br.PeekChar() != -1)
{
Point point = new Point();
uint RecordNum = br.ReadUInt32();
int DataLength = br.ReadInt32();
//读取第i个记录
br.ReadInt32();
point.X = br.ReadDouble();
point.Y = -1 * br.ReadDouble();
points.Add(point);
}
StreamWriter sw = new StreamWriter("point.txt");
foreach (Point p in points)
{
sw.WriteLine("{0},{1},{2} ", p.X, -1 * p.Y, 0);
}
sw.Close();
break;
case 3:
polylines.Clear();
while (br.PeekChar() != -1)
{
Polyline polyline = new Polyline();
polyline.Box = new double[4];
polyline.Parts = new ArrayList();
polyline.Points = new ArrayList();
uint RecordNum = br.ReadUInt32();
int DataLength = br.ReadInt32();
//读取第i个记录
br.ReadInt32();
polyline.Box[0] = br.ReadDouble();
polyline.Box[1] = br.ReadDouble();
polyline.Box[2] = br.ReadDouble();
polyline.Box[3] = br.ReadDouble();
polyline.NumParts = br.ReadInt32();
polyline.NumPoints = br.ReadInt32();
for (int i = 0; i < polyline.NumParts; i++)
{
int parts = new int();
parts = br.ReadInt32();
polyline.Parts.Add(parts);
}
for (int j = 0; j < polyline.NumPoints; j++)
{
Point pointtemp = new Point();
pointtemp.X = br.ReadDouble();
pointtemp.Y = -1 * br.ReadDouble();
polyline.Points.Add(pointtemp);
}
polylines.Add(polyline);
}
StreamWriter sw2 = new StreamWriter("line.txt");
count = 1;
foreach (Polyline p in polylines)
{
for (int i = 0; i < p.NumParts; i++)
{
int startpoint;
int endpoint;
if (i == p.NumParts - 1)
{
startpoint = (int)p.Parts[i];
endpoint = p.NumPoints;
}
else
{
startpoint = (int)p.Parts[i];
endpoint = (int)p.Parts[i + 1];
}
sw2.WriteLine("线" + count.ToString() + ":");
for (int k = 0, j = startpoint; j < endpoint; j++, k++)
{
Point ps = (Point)p.Points[j];
sw2.WriteLine(" {0},{1},{2} ", ps.X, -1 * ps.Y, 0);
}
count++;
}
}
sw2.Close();
break;
case 5:
polygons.Clear();
while (br.PeekChar() != -1)
{
Polygon polygon = new Polygon();
polygon.Parts = new ArrayList();
polygon.Points = new ArrayList();
uint RecordNum = br.ReadUInt32();
int DataLength = br.ReadInt32();
//读取第i个记录
int m = br.ReadInt32();
for (int i = 0; i < 4; i++)
{
polygon.Box[i] = br.ReadDouble();
}
polygon.NumParts = br.ReadInt32();
polygon.NumPoints = br.ReadInt32();
for (int j = 0; j < polygon.NumParts; j++)
{
int parts = new int();
parts = br.ReadInt32();
polygon.Parts.Add(parts);
}
for (int j = 0; j < polygon.NumPoints; j++)
{
Point pointtemp = new Point();
pointtemp.X = br.ReadDouble();
pointtemp.Y = -1 * br.ReadDouble();
polygon.Points.Add(pointtemp);
}
polygons.Add(polygon);
}
StreamWriter sw1 = new StreamWriter("polygon.txt");
count = 1;
foreach (Polygon p in polygons)
{
for (int i = 0; i < p.NumParts; i++)
{
int startpoint;
int endpoint;
if (i == p.NumParts - 1)
{
startpoint = (int)p.Parts[i];
endpoint = p.NumPoints;
}
else
{
startpoint = (int)p.Parts[i];
endpoint = (int)p.Parts[i + 1];
}
sw1.WriteLine("多边形" + count.ToString() + ":");
for (int k = 0, j = startpoint; j < endpoint; j++, k++)
{
Point ps = (Point)p.Points[j];
sw1.WriteLine(" {0},{1},{2} ", ps.X, -1 * ps.Y, 0);
}
count++;
}
}
sw1.Close();
break;
}
}
}*/
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Terminal.Gui.CoreTests {
public class EscSeqReqTests {
[Fact]
public void Constructor_Defaults ()
{
var escSeqReq = new EscSeqReqProc ();
Assert.NotNull (escSeqReq.EscSeqReqStats);
Assert.Empty (escSeqReq.EscSeqReqStats);
}
[Fact]
public void Add_Tests ()
{
var escSeqReq = new EscSeqReqProc ();
escSeqReq.Add ("t");
Assert.Single (escSeqReq.EscSeqReqStats);
Assert.Equal ("t", escSeqReq.EscSeqReqStats [^1].Terminating);
Assert.Equal (1, escSeqReq.EscSeqReqStats [^1].NumRequests);
Assert.Equal (1, escSeqReq.EscSeqReqStats [^1].NumOutstanding);
escSeqReq.Add ("t", 2);
Assert.Single (escSeqReq.EscSeqReqStats);
Assert.Equal ("t", escSeqReq.EscSeqReqStats [^1].Terminating);
Assert.Equal (1, escSeqReq.EscSeqReqStats [^1].NumRequests);
Assert.Equal (1, escSeqReq.EscSeqReqStats [^1].NumOutstanding);
escSeqReq = new EscSeqReqProc ();
escSeqReq.Add ("t", 2);
Assert.Single (escSeqReq.EscSeqReqStats);
Assert.Equal ("t", escSeqReq.EscSeqReqStats [^1].Terminating);
Assert.Equal (2, escSeqReq.EscSeqReqStats [^1].NumRequests);
Assert.Equal (2, escSeqReq.EscSeqReqStats [^1].NumOutstanding);
escSeqReq.Add ("t", 3);
Assert.Single (escSeqReq.EscSeqReqStats);
Assert.Equal ("t", escSeqReq.EscSeqReqStats [^1].Terminating);
Assert.Equal (2, escSeqReq.EscSeqReqStats [^1].NumRequests);
Assert.Equal (2, escSeqReq.EscSeqReqStats [^1].NumOutstanding);
}
[Fact]
public void Remove_Tests ()
{
var escSeqReq = new EscSeqReqProc ();
escSeqReq.Add ("t");
escSeqReq.Remove ("t");
Assert.Empty (escSeqReq.EscSeqReqStats);
escSeqReq.Add ("t", 2);
escSeqReq.Remove ("t");
Assert.Single (escSeqReq.EscSeqReqStats);
Assert.Equal ("t", escSeqReq.EscSeqReqStats [^1].Terminating);
Assert.Equal (2, escSeqReq.EscSeqReqStats [^1].NumRequests);
Assert.Equal (1, escSeqReq.EscSeqReqStats [^1].NumOutstanding);
escSeqReq.Remove ("t");
Assert.Empty (escSeqReq.EscSeqReqStats);
}
[Fact]
public void Requested_Tests ()
{
var escSeqReq = new EscSeqReqProc ();
Assert.False (escSeqReq.Requested ("t"));
escSeqReq.Add ("t");
Assert.False (escSeqReq.Requested ("r"));
Assert.True (escSeqReq.Requested ("t"));
}
}
}
|
namespace Alabo.Framework.Tasks.Queues.Models {
public interface IModuleConfig {
/// <summary>
/// 配置存入数据库的主键Id
/// </summary>
long Id { get; set; }
/// <summary>
/// 配置名称
/// </summary>
string Name { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Xlns.BusBook.Core;
namespace Xlns.BusBook.UI.Web.Controllers
{
public class DepliantController : Controller
{
ViaggioManager vm = new ViaggioManager();
public ActionResult View(int idDepliant)
{
var viaggio = vm.GetViaggioByDepliant(idDepliant);
var dvm = new Models.DepliantViewModel()
{
Viaggio = viaggio
};
return PartialView("Edit", dvm);
}
public ActionResult Edit(int idDepliant, String htmlId)
{
var viaggio = vm.GetViaggioByDepliant(idDepliant);
var dvm = new Models.DepliantViewModel()
{
HtmlContainerId = htmlId,
Viaggio = viaggio,
ShowDeleteCommand = true
};
return PartialView(dvm);
}
public ActionResult Delete(int id)
{
vm.DeleteDepliant(id);
return PartialView("New");
}
public ActionResult New()
{
return PartialView();
}
}
}
|
using System;
using System.Runtime.InteropServices;
using Vlc.DotNet.Core.Interops;
using Vlc.DotNet.Core.Interops.Signatures;
namespace Vlc.DotNet.Core
{
public partial class VlcMedia
{
private EventCallback myOnMediaSubItemTreeAddedInternalEventCallback;
public event EventHandler<VlcMediaSubItemTreeAddedEventArgs> SubItemTreeAdded;
private void OnMediaSubItemTreeAddedInternal(IntPtr ptr)
{
var args = MarshalHelper.PtrToStructure<VlcEventArg>(ptr);
OnMediaSubItemTreeAdded(new VlcMedia(myVlcMediaPlayer, VlcMediaInstance.New(myVlcMediaPlayer.Manager, args.eventArgsUnion.MediaSubItemTreeAdded.MediaInstance)));
}
public void OnMediaSubItemTreeAdded(VlcMedia newSubItemAdded)
{
SubItemTreeAdded?.Invoke(this, new VlcMediaSubItemTreeAddedEventArgs(newSubItemAdded));
}
}
} |
//-----------------------------------------------------------------------
// <copyright file="InMemoryEventStore.cs" company="4Deep Technologies LLC">
// Copyright (c) 4Deep Technologies LLC. All rights reserved.
// <author>Darren Ford</author>
// <date>Thursday, April 30, 2015 3:00:44 PM</date>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Reflection;
namespace Dizzle.Cqrs.Core
{
public class StorageStream
{
public List<StorageFrame> Events;
public long Version { get; set; }
}
public sealed class StorageFrame
{
public List<IEvent> Events;
public long Version { get; set; }
public StorageFrame()
{
}
public StorageFrame(IEnumerable<IEvent> events, long version)
{
Events = events.ToList();
Version = version;
}
}
public class InMemoryEventStore : IEventStore
{
private ConcurrentDictionary<string, StorageStream> store =
new ConcurrentDictionary<string, StorageStream>();
public IEnumerable<IEvent> LoadEventsFor<TAggregate>(string id)
{
// Get the current event stream; note that we never mutate the
// Events array so it's safe to return the real thing.
StorageStream s;
if (store.TryGetValue(id, out s))
return s.Events.OrderBy(t => t.Version).SelectMany(t => t.Events);
else
return new List<IEvent>();
}
public IEnumerable<IEvent> LoadEventsFor<TAggregate>(string id, long afterVersion)
{
// Get the current event stream; note that we never mutate the
// Events array so it's safe to return the real thing.
StorageStream s;
if (store.TryGetValue(id, out s))
return s.Events.Where(t => t.Version > afterVersion).OrderBy(t => t.Version).SelectMany(t => t.Events);
else
return new List<IEvent>();
}
public void SaveEventsFor<TAggregate>(string aggregateId, long eventsLoaded, IEnumerable<IEvent> newEvents)
{
// Get or create stream.
var s = store.GetOrAdd(aggregateId, _ => new StorageStream());
// We'll use a lock-free algorithm for the update.
while (true)
{
// Read the current event list.
var eventList = s.Events;
// Ensure no events persisted since us.
var prevEvents = eventList == null ? 0 : eventList.Sum(t => t.Events.Count);
if (prevEvents != eventsLoaded)
throw new Exception("Concurrency conflict; cannot persist these events");
// Create a new event list with existing ones plus our new
// ones (making new important for lock free algorithm!)
var newEventList = eventList == null
? new List<StorageFrame>()
: (List<StorageFrame>)eventList.Clone();
newEventList.Add(new StorageFrame(newEvents, eventsLoaded + 1L));
// Try to put the new event list in place atomically.
if (Interlocked.CompareExchange(ref s.Events, newEventList, eventList) == eventList)
break;
}
}
private AbstractIdentity<Guid> GetAggregateIdFromEvent(object e)
{
var idField = e.GetType().GetTypeInfo().DeclaredFields.Single(t => t.Name.Equals("Id"));
if (idField == null)
throw new Exception("Event type " + e.GetType().Name + " is missing an Id field");
return (AbstractIdentity<Guid>)idField.GetValue(e);
}
}
public static class Extensions
{
public static List<IEvent> Clone(this List<IEvent> currentList)
{
List<IEvent> newList = new List<IEvent>();
newList.AddRange(currentList);
return newList;
}
public static List<StorageFrame> Clone(this List<StorageFrame> currentList)
{
List<StorageFrame> newList = new List<StorageFrame>();
foreach (StorageFrame frame in currentList)
{
StorageFrame frm = new StorageFrame();
frm.Version = frame.Version;
frm.Events = frame.Events.Clone();
}
newList.AddRange(currentList);
return newList;
}
}
}
|
public class Solution {
public IList<int> GetRow(int rowIndex) {
int[] dp = new int[rowIndex + 1];
dp[0] = 1;
int prev = 1, curr;
for (int i = 1; i <= rowIndex; i ++) {
dp[i] = 1;
for (int j = 1; j < i; j ++) {
curr = dp[j];
dp[j] += prev;
prev = curr;
}
}
return dp.ToList();
}
} |
using System;
namespace gView.GraphicsEngine.GdiPlus.Extensions
{
static class ImageFormatExtensions
{
static public System.Drawing.Imaging.ImageFormat ToImageFormat(this ImageFormat format)
{
switch (format)
{
case ImageFormat.Png:
return System.Drawing.Imaging.ImageFormat.Png;
case ImageFormat.Jpeg:
return System.Drawing.Imaging.ImageFormat.Jpeg;
case ImageFormat.Gif:
return System.Drawing.Imaging.ImageFormat.Gif;
case ImageFormat.Bmp:
return System.Drawing.Imaging.ImageFormat.Bmp;
default:
throw new Exception($"Save Bitmap: Format not supported: {format}");
}
}
}
}
|
using gMediaTools.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gMediaTools.Services.AviSynth.VideoSource
{
public class AviSynthLWLibavVideoSourceService : IAviSynthVideoSourceService
{
public string GetAviSynthVideoSource(string fileName, bool overWriteScriptFile)
{
// Find cache file
string cacheFileName = $"{fileName}.lwi";
if (!overWriteScriptFile)
{
cacheFileName = cacheFileName.GetNewFileName();
}
StringBuilder sb = new StringBuilder();
sb.Append($"LWLibavVideoSource(source = \"{fileName}\", ");
sb.Append($"stream_index = -1, cache = true, cachefile = \"{cacheFileName}\", ");
sb.Append($"fpsnum = 0, fpsden = 1, repeat = false, threads = 0, seek_mode = 0)");
return sb.ToString();
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace SysBase.Domain.Models
{
/// <summary>
/// 由于注入的问题 数据库连接先进行注入,延时加载微软已经不再启用
/// 需要的话需要扩展引用包启动延迟加载https://blog.csdn.net/xhl_james/article/details/93136893)
/// install-package Microsoft.EntityFrameworkCore.Proxies optionsBuilder.UseLazyLoadingProxies(); 或者用iloadLazyer
/// 封装会使用显示加载include
/// </summary>
public partial class SysBaseDbContext : DbContext
{
public SysBaseDbContext(DbContextOptions<SysBaseDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//if (!optionsBuilder.IsConfigured)
//{
// optionsBuilder.UseSqlServer("Data Source=DESKTOP-4UNR39U\\SQLEXPRESS;Initial Catalog=Sys_Base_Db;User ID=sa;Password=123456abcD;MultipleActiveResultSets=True;");
//}
}
public virtual DbSet<SysIcon> SysIcon { get; set; }
public virtual DbSet<SysMenu> SysMenu { get; set; }
public virtual DbSet<SysPermission> SysPermission { get; set; }
public virtual DbSet<SysRole> SysRole { get; set; }
public virtual DbSet<SysRolePermissionMapping> SysRolePermissionMapping { get; set; }
public virtual DbSet<SysUser> SysUser { get; set; }
public virtual DbSet<SysUserRoleMapping> SysUserRoleMapping { get; set; }
#region DbQuery
/// <summary>
///
/// </summary>
public DbQuery<SysPermissionWithAssignProperty> SysPermissionWithAssignProperty { get; set; }
/// <summary>
///
/// </summary>
public DbQuery<SysPermissionWithMenu> SysPermissionWithMenu { get; set; }
#endregion
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<SysIcon>(entity =>
{
entity.ToTable("Sys_Icon");
entity.Property(e => e.Code)
.IsRequired()
.HasMaxLength(50);
entity.Property(e => e.Color).HasMaxLength(50);
entity.Property(e => e.Custom).HasMaxLength(60);
entity.Property(e => e.Size).HasMaxLength(20);
});
modelBuilder.Entity<SysMenu>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("Sys_Menu");
entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Alias).HasMaxLength(255);
entity.Property(e => e.BeforeCloseFun).HasMaxLength(255);
entity.Property(e => e.Component).HasMaxLength(255);
entity.Property(e => e.Description).HasMaxLength(800);
entity.Property(e => e.Icon).HasMaxLength(128);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
entity.Property(e => e.Url).HasMaxLength(255);
});
modelBuilder.Entity<SysUser>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("Sys_User");
entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Avatar).HasMaxLength(255);
entity.Property(e => e.Description).HasMaxLength(800);
entity.Property(e => e.DisplayName).HasMaxLength(50);
entity.Property(e => e.UserName)
.IsRequired()
.HasMaxLength(50);
entity.Property(e => e.Password).HasMaxLength(255);
});
modelBuilder.Entity<SysRole>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("Sys_Role");
entity.Property(e => e.Id)
.HasMaxLength(50)
.ValueGeneratedNever();
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
});
modelBuilder.Entity<SysPermission>(entity =>
{
entity.HasKey(e => e.Id);
entity.ToTable("Sys_Permission");
entity.Property(e => e.Id)
.HasMaxLength(20)
.ValueGeneratedNever();
entity.Property(e => e.ActionCode)
.IsRequired()
.HasMaxLength(80);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
entity.HasOne(d => d.MenuGu)
.WithMany(p => p.SysPermission)
.HasForeignKey(d => d.MenuId)
.HasConstraintName("FK_DncPermission_DncMenu_MenuId");
});
modelBuilder.Entity<SysRolePermissionMapping>(entity =>
{
entity.HasKey(x => new
{
x.RoleId,
x.PermissionId
});
entity.ToTable("Sys_RolePermissionMapping");
entity.Property(e => e.RoleId).HasMaxLength(50);
entity.Property(e => e.PermissionId).HasMaxLength(20);
entity.HasOne(d => d.PermissionCodeNavigation)
.WithMany(p => p.SysRolePermissionMapping)
.HasForeignKey(d => d.PermissionId)
.HasConstraintName("FK_DncRolePermissionMapping_DncPermission_PermissionId");
entity.HasOne(d => d.RoleCodeNavigation)
.WithMany(p => p.SysRolePermissionMapping)
.HasForeignKey(d => d.RoleId)
.HasConstraintName("FK_DncRolePermissionMapping_DncRole_RoleId");
});
modelBuilder.Entity<SysUserRoleMapping>(entity =>
{
entity.HasKey(x => new
{
x.RoleId,
x.UserId
});
entity.ToTable("Sys_UserRoleMapping");
entity.Property(e => e.RoleId).HasMaxLength(50);
entity.Property(e => e.UserId).HasMaxLength(50);
entity.HasOne(x => x.RoleCodeNavigation)
.WithMany(x => x.SysUserRoleMapping)
.HasForeignKey(x => x.RoleId)
.HasConstraintName("FK_Sys_UserRoleMapping_RoleId");
entity.HasOne(x => x.UserGu)
.WithMany(x => x.SysUserRoleMapping)
.HasForeignKey(x => x.UserId)
.HasConstraintName("FK_Sys_UserRoleMapping_UserId");
});
}
}
}
|
using System;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StarlightRiver.Abilities;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace StarlightRiver.NPCs.Boss.VitricBoss
{
sealed partial class VitricBoss : ModNPC
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Glass Tax Returns");
}
public override void SetDefaults()
{
npc.aiStyle = -1;
npc.lifeMax = 3500;
npc.damage = 30;
npc.defense = 10;
npc.knockBackResist = 0f;
npc.width = 140;
npc.height = 140;
npc.value = Item.buyPrice(0, 20, 0, 0);
npc.npcSlots = 15f;
npc.boss = true;
npc.lavaImmune = true;
npc.noGravity = true;
npc.noTileCollide = true;
npc.HitSound = SoundID.NPCHit1;
npc.DeathSound = SoundID.NPCDeath1;
music = mod.GetSoundSlot(SoundType.Music, "Sounds/Music/GlassBoss");
}
public override void ScaleExpertStats(int numPlayers, float bossLifeScale)
{
npc.lifeMax = (int)(npc.lifeMax * 0.625f * bossLifeScale);
npc.damage = (int)(npc.damage * 0.6f);
}
public override bool CheckDead()
{
if (!LegendWorld.AnyBossDowned) LegendWorld.ForceStarfall = true;
LegendWorld.GlassBossDowned = true;
LegendWorld.AnyBossDowned = true;
return true;
}
public override bool PreDraw(SpriteBatch spriteBatch, Color drawColor)
{
npc.frame.Width = npc.width;
npc.frame.Height = npc.height;
spriteBatch.Draw(ModContent.GetTexture(Texture), npc.Center - Main.screenPosition, npc.frame, drawColor, npc.rotation, npc.frame.Size() / 2, npc.scale, 0, 0 );
return false;
}
//Used for the various differing passive animations of the different forms
private void SetFrameX(int frame)
{
npc.frame.X = npc.width * frame;
}
//Easily animate a phase with custom framerate and frame quantity
private void Animate(int ticksPerFrame, int maxFrames)
{
if (npc.frameCounter++ >= ticksPerFrame) { npc.frame.Y += npc.height; npc.frameCounter = 0; }
if ((npc.frame.Y / npc.height) > maxFrames - 1) npc.frame.Y = 0;
}
//resets animation and changes phase
private void ChangePhase(int phase, bool resetTime = false)
{
npc.frame.Y = 0;
npc.ai[1] = phase;
if (resetTime) npc.ai[0] = 0;
}
public override void AI()
{
/*
AI slots:
0: Timer
1: Phase
*/
//Ticks the timer
npc.ai[0]++;
switch (npc.ai[1])
{
//on spawn effects
case 0:
int count = 2 + Main.player.Count(p => Vector2.Distance(p.Center, npc.Center) <= 1000) * 2; //counts players in the fight
if (count > 6) count = 6; //caps at 6
for (int k = 0; k < count; k++) //spawns an appropriate amount of crystals for the players
{
int index = NPC.NewNPC((int)npc.Center.X, (int)npc.Center.Y, ModContent.NPCType<VitricBossCrystal>(), 0, 0, 0, 0, k);
Main.npc[index].velocity = new Vector2(-1, 0).RotatedBy((k / ((float)count - 1)) * 3.14f) * 2;
}
ChangePhase(1);
break;
//First phase
case 1:
//Attacks
if(npc.ai[0] >= 120)
{
Main.NewText("foo!");
npc.ai[0] = 0;
}
//vulnerability check
bool vulnerable = !Main.npc.Any(n => n.active && n.type == ModContent.NPCType<VitricBossCrystal>());
//Dash + vulnerability detection
if (Main.player.Any(p => AbilityHelper.CheckDash(p, npc.Hitbox)) && vulnerable) ChangePhase(2);
//Animation
if (vulnerable)
{
SetFrameX(1);
Animate(5, 3);
}
else Animate(5, 3);
break;
//First => Second phase transition
case 2:
Main.PlaySound(SoundID.Shatter);
for (int k = 0; k <= 100; k++) //reforming glass shards
{
Dust dus = Dust.NewDustPerfect(npc.Center + Vector2.One.RotatedBy(k) * 50,
ModContent.DustType<Dusts.Glass>(), Vector2.One.RotatedBy(k + Main.rand.NextFloat(-2, 2)) * Main.rand.Next(10, 20), 0, default, k / 40f);
dus.customData = npc.Center;
}
npc.scale = 0;
SetFrameX(2);
ChangePhase(3, true);
music = mod.GetSoundSlot(SoundType.Music, "VortexIsACunt");
break;
//Second phase
case 3:
music = mod.GetSoundSlot(SoundType.Music, "Sounds/Music/WhipAndNaenae");
//Visuals
float rot = Main.rand.NextFloat(6.28f);
Dust.NewDustPerfect(npc.Center + Vector2.One.RotatedBy(rot) * 80, ModContent.DustType<Dusts.Glass3>(), Vector2.One.RotatedBy(rot + 1.58f));
//Formation scaling
if (npc.ai[0] >= 20 && npc.ai[0] <= 60)
{
npc.scale = (npc.ai[0] - 20) / 40f;
}
//Animation
Animate(10, 3);
break;
}
}
}
}
|
/*
* Pedometer
* Copyright (c) 2017 Yusuf Olokoba
*/
namespace PedometerU.Platforms {
using System.Runtime.InteropServices;
using Utilities;
public sealed class PedometeriOS : IPedometer {
#region --Operations--
public event StepCallback OnStep {
add { PedometerHelper.Instance.OnStep += value; }
remove { PedometerHelper.Instance.OnStep -= value; }
}
public bool IsSupported {
get {
#if !UNITY_IOS || UNITY_EDITOR
return false;
#endif
#pragma warning disable 0162
return PDIsSupported();
#pragma warning restore 0162
}
}
public IPedometer Initialize () {
PDInitialize();
return this;
}
public void Release () {
PDRelease();
}
#endregion
#region --Bridge--
#if UNITY_IOS
[DllImport("__Internal")]
private static extern void PDInitialize ();
[DllImport("__Internal")]
private static extern void PDRelease ();
[DllImport("__Internal")]
private static extern bool PDIsSupported ();
#else // Keep IL2CPP happy
private static void PDInitialize () {}
private static void PDRelease () {}
private static bool PDIsSupported () {return false;}
#endif
#endregion
}
} |
using System;
using Tomelt.ContentManagement;
using Tomelt.ContentManagement.Drivers;
using Tomelt.Core.Navigation.Models;
using Tomelt.Core.Navigation.Settings;
using Tomelt.Localization;
using Tomelt.Security;
using Tomelt.UI.Navigation;
using Tomelt.Utility;
namespace Tomelt.Core.Navigation.Drivers {
public class AdminMenuPartDriver : ContentPartDriver<AdminMenuPart> {
private readonly IAuthorizationService _authorizationService;
private readonly INavigationManager _navigationManager;
private readonly ITomeltServices _tomeltServices;
public AdminMenuPartDriver(IAuthorizationService authorizationService, INavigationManager navigationManager, ITomeltServices tomeltServices) {
_authorizationService = authorizationService;
_navigationManager = navigationManager;
_tomeltServices = tomeltServices;
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
private string GetDefaultPosition(ContentPart part) {
var settings = part.Settings.GetModel<AdminMenuPartTypeSettings>();
var defaultPosition = settings == null ? "" : settings.DefaultPosition;
var adminMenu = _navigationManager.BuildMenu("admin");
if (!string.IsNullOrEmpty(defaultPosition)) {
int major;
return int.TryParse(defaultPosition, out major) ? Position.GetNextMinor(major, adminMenu) : defaultPosition;
}
return Position.GetNext(adminMenu);
}
protected override DriverResult Editor(AdminMenuPart part, dynamic shapeHelper) {
// todo: we need a 'ManageAdminMenu' too?
if (!_authorizationService.TryCheckAccess(Permissions.ManageMenus, _tomeltServices.WorkContext.CurrentUser, part)) {
return null;
}
if (string.IsNullOrEmpty(part.AdminMenuPosition)) {
part.AdminMenuPosition = GetDefaultPosition(part);
}
return ContentShape("Parts_Navigation_AdminMenu_Edit",
() => shapeHelper.EditorTemplate(TemplateName: "Parts.Navigation.AdminMenu.Edit", Model: part, Prefix: Prefix));
}
protected override DriverResult Editor(AdminMenuPart part, IUpdateModel updater, dynamic shapeHelper) {
if (!_authorizationService.TryCheckAccess(Permissions.ManageMenus, _tomeltServices.WorkContext.CurrentUser, part))
return null;
updater.TryUpdateModel(part, Prefix, null, null);
if (part.OnAdminMenu) {
if (string.IsNullOrEmpty(part.AdminMenuText)) {
updater.AddModelError("AdminMenuText", T("The AdminMenuText field is required"));
}
if (string.IsNullOrEmpty(part.AdminMenuPosition)) {
part.AdminMenuPosition = GetDefaultPosition(part);
}
}
else {
part.AdminMenuPosition = "";
}
return Editor(part, shapeHelper);
}
protected override void Importing(AdminMenuPart part, ContentManagement.Handlers.ImportContentContext context) {
// Don't do anything if the tag is not specified.
if (context.Data.Element(part.PartDefinition.Name) == null) {
return;
}
context.ImportAttribute(part.PartDefinition.Name, "AdminMenuText", adminMenuText =>
part.AdminMenuText = adminMenuText
);
context.ImportAttribute(part.PartDefinition.Name, "AdminMenuPosition", position =>
part.AdminMenuPosition = position
);
context.ImportAttribute(part.PartDefinition.Name, "OnAdminMenu", onAdminMenu =>
part.OnAdminMenu = Convert.ToBoolean(onAdminMenu)
);
}
protected override void Exporting(AdminMenuPart part, ContentManagement.Handlers.ExportContentContext context) {
context.Element(part.PartDefinition.Name).SetAttributeValue("AdminMenuText", part.AdminMenuText);
context.Element(part.PartDefinition.Name).SetAttributeValue("AdminMenuPosition", part.AdminMenuPosition);
context.Element(part.PartDefinition.Name).SetAttributeValue("OnAdminMenu", part.OnAdminMenu);
}
}
} |
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Action of type `GameObject`. Inherits from `AtomAction<GameObject>`.
/// </summary>
[EditorIcon("atom-icon-purple")]
public abstract class GameObjectAction : AtomAction<GameObject> { }
}
|
using Report_ClassLibrary;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ClosedXML.Excel;
using System.Text;
using DocumentFormat.OpenXml.Spreadsheet;
using CrystalDecisions.CrystalReports.Engine;
public partial class NewCustomerShelf : System.Web.UI.Page
{
ReportDocument rdoc1 = new ReportDocument();
ReportDocument rdoc2 = new ReportDocument();
Dictionary<string, bool> UserList = new Dictionary<string, bool>();
string conString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
string conString8 = ConfigurationManager.ConnectionStrings["myConnectionString_8"].ConnectionString;
Dictionary<string, string> permissionList = new Dictionary<string, string>();
static List<VanDetails> vanList = new List<VanDetails>();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["AllCashReportLogin"] != null)
{
UserList = (Dictionary<string, bool>)Session["AllCashReportLogin"];
if (UserList.First().Value.ToString() == "0")
{
Response.Redirect("~/index.aspx");
}
}
if (Session["AllCashReportLogin"] == null)
{
Response.Redirect("~/index.aspx");
}
if (!IsPostBack)
{
InitPage();
}
rdoc1 = new ReportDocument();
rdoc2 = new ReportDocument();
}
protected void Page_Unload(object sender, EventArgs e)
{
try
{
rdoc1 = new ReportDocument();
rdoc1.Close();
rdoc1.Dispose();
rdoc2 = new ReportDocument();
rdoc2.Close();
rdoc2.Dispose();
GC.Collect();
}
catch
{
}
}
private void InitPage()
{
var _date = DateTime.Now;
Dictionary<string, string> branchList = new Dictionary<string, string>();
Dictionary<string, string> custTypeList = new Dictionary<string, string>();
custTypeList.Add("All", "---All---");
custTypeList.Add("NewCustomer", "NewCustomer");
custTypeList.Add("OldCustomer", "OldCustomer");
ddlCustType.BindDropdownList(custTypeList);
//ddlMonth.PrepareMonthDropdown();
//ddlYear.PrepareYearDropdown();
ddlMonth_2.PrepareMonthDropdown();
ddlYear_2.PrepareYearDropdown();
DataTable dt = new DataTable();
dt = Helper.ExecuteProcedureToTable(conString, "proc_MonthlySalesSumReport_GetBranch", null);
DataRow cRow = dt.NewRow();
cRow["BranchID"] = "-1";
cRow["BranchName"] = "---All---";
dt.Rows.InsertAt(cRow, 0);
//ddlBranch.BindDropdownList(dt, "BranchName", "BranchID");
//ddlBranch.SelectedIndex = 0;
ddlBranch_2.BindDropdownList(dt, "BranchName", "BranchID");
ddlBranch_2.SelectedIndex = 0;
//ddlVan.Items.Clear();
ddlVan_2.Items.Clear();
DataTable dt2 = new DataTable();
string cmd = "";
cmd += " SELECT DISTINCT RIGHT(WHCode, 3) AS 'VAN_ID', RIGHT(WHCode, 3) AS 'VAN_CODE' FROM [dbo].[BranchWarehouse] WHERE RIGHT(WHCode, 3) LIKE 'V%'";
dt2 = Helper.ExecuteProcedureToTable(conString8, cmd, CommandType.Text, null);
//DataView dv = new DataView(dt2);
//dv.RowFilter = "BranchID = " + ddlBranch.SelectedValue;
//dt2 = dv.ToTable();
DataRow cRow2 = dt2.NewRow();
cRow2["VAN_ID"] = "-1";
cRow2["VAN_CODE"] = "---All---";
dt2.Rows.InsertAt(cRow2, 0);
//ddlVan.BindDropdownList(dt2, "VAN_CODE", "VAN_ID");
//ddlVan.SelectedIndex = 0;
ddlVan_2.BindDropdownList(dt2, "VAN_CODE", "VAN_ID");
ddlVan_2.SelectedIndex = 0;
}
protected void CrystalReportViewer1_Load(object sender, EventArgs e)
{
//int _month = Convert.ToInt32(ddlMonth.SelectedValue);
//int _year = Convert.ToInt32(ddlYear.SelectedValue);
//string branchID = ddlBranch.SelectedValue;
//string vanID = ddlVan.SelectedValue;
//GenPatternReport(rdoc1, CrystalReportViewer1, _month, _year, branchID, vanID, "proc_new_customer_shelf_get", "NewCustomerShelf.rpt");
}
protected void CrystalReportViewer1_Unload(object sender, EventArgs e)
{
}
private void GenPatternReport(ReportDocument rdoc, CrystalDecisions.Web.CrystalReportViewer crys, int month, int year, string branchID, string vanID, string storeName, string reportName)
{
ViewState["CrystalReport_Data"] = null;
try
{
Dictionary<string, object> _p = new Dictionary<string, object>();
_p.Add("Month", month);
_p.Add("Year", year);
_p.Add("BrandID", branchID);
_p.Add("VanID", vanID);
if (crys.ID == "CrystalReportViewer2")
{
_p.Add("CustType", ddlCustType.SelectedValue);
}
DataTable dt = new DataTable();
dt = Helper.ExecuteProcedureToTable(conString8, storeName, _p);
if (dt != null && dt.Rows.Count > 0)
{
ViewState["CrystalReport_Data"] = dt;
rdoc.Load(Server.MapPath(reportName));
rdoc.SetDataSource(dt);
//rdoc1.SetParameterValue("Month", branchID);
crys.RefreshReport();
crys.ReportSource = rdoc;
crys.DataBind();
}
}
catch (Exception ex)
{
Helper.WriteLog(ex.Message);
throw ex;
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
}
protected void ddlBranch_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnSearch_2_Click(object sender, EventArgs e)
{
}
protected void CrystalReportViewer2_Load(object sender, EventArgs e)
{
int _month = Convert.ToInt32(ddlMonth_2.SelectedValue);
int _year = Convert.ToInt32(ddlYear_2.SelectedValue);
string branchID = ddlBranch_2.SelectedValue;
string vanID = ddlVan_2.SelectedValue;
GenPatternReport(rdoc2, CrystalReportViewer2, _month, _year, branchID, vanID, "proc_customer_shelf_get", "CustomerShelf.rpt");
}
protected void CrystalReportViewer2_Unload(object sender, EventArgs e)
{
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
try
{
if (ViewState["CrystalReport_Data"] != null)
{
int _month = Convert.ToInt32(ddlMonth_2.SelectedValue);
int _year = Convert.ToInt32(ddlYear_2.SelectedValue);
string _branchName = ddlBranch_2.SelectedValue == "-1" ? "AllBranch" : ddlBranch_2.SelectedValue.ToString();
string docDateTemp = string.Join("-", _year.ToString(), _month.ToString(), "01");
string docDate = Convert.ToDateTime(docDateTemp).ToString("MMM-yyyy");
DataTable _dt = (DataTable)ViewState["CrystalReport_Data"];
var readDT = new DataTable();
readDT.Columns.Add("เดือน", typeof(string));
readDT.Columns.Add("ปี", typeof(string));
readDT.Columns.Add("รหัสสาขา", typeof(string));
readDT.Columns.Add("สาขา", typeof(string));
readDT.Columns.Add("รหัสร้านค้า", typeof(string));
readDT.Columns.Add("ร้านค้า", typeof(string));
readDT.Columns.Add("ที่อยู่", typeof(string));
readDT.Columns.Add("ตำบล", typeof(string));
readDT.Columns.Add("อำเภอ", typeof(string));
readDT.Columns.Add("จังหวัด", typeof(string));
readDT.Columns.Add("รหัสแวน", typeof(string));
readDT.Columns.Add("Latitude", typeof(string));
readDT.Columns.Add("Longitude", typeof(string));
readDT.Columns.Add("Shelf", typeof(string));
readDT.Columns.Add("Bill", typeof(string));
readDT.Columns.Add("*NAmt", typeof(string));
readDT.Columns.Add("ประเภทรายงาน", typeof(string));
foreach (DataRow r in _dt.Rows)
{
readDT.Rows.Add(r["MonthIn"].ToString(), r["YearIn"].ToString(), r["BranchID"].ToString(), r["BranchName"].ToString(), r["CustomerID"].ToString()
, r["CustName"].ToString(), r["AddressNo"].ToString(), r["DistrictName"].ToString(), r["AreaName"].ToString(), r["ProvinceName"].ToString()
, r["VanID"].ToString(), r["Latitude"].ToString(), r["Longitude"].ToString(), r["Shelf"].ToString(), r["Bill"].ToString(), r["NAmt"].ToString()
, r["CustType"].ToString());
}
DataView dv = readDT.DefaultView;
dv.Sort = "ประเภทรายงาน, รหัสแวน asc";
DataTable sortedDT = dv.ToTable();
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(sortedDT, docDate);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Customer_Shelf_Report_" + _branchName + "_" + docDate + ".xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
//Response.End();
}
}
}
}
catch (Exception)
{
throw;
}
}
} |
/*
Programming Pseudo 3D Planes aka MODE7 (C++)
Javidx9, Youtube
https://www.youtube.com/watch?v=ybLZyY655iY
Todo:
- use Burst for faster arithmetic
- bonus if you take the frustum diagram and
render it on top of the map
Notes:
- y coordinates are the other way around here
- wraparound depends on texture sampler/impporter settings
- 1/z=inf issue isn't handled yet
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Burst;
using Unity.Jobs;
using Unity.Collections;
using Unity.Mathematics;
public class Mode8 : MonoBehaviour {
[SerializeField] private Texture2D _ground;
[SerializeField] private Texture2D _sky;
[SerializeField] private bool _proceduralTextures;
[SerializeField] private float _fovHalf = Mathf.PI / 4f;
[SerializeField] private float _near = 0.01f;
[SerializeField] private float _far = 0.1f;
[SerializeField] private float _moveSpeed = 0.2f;
private Texture2D _screen;
private float2 _worldPos;
private float _worldRot;
private void Awake () {
_screen = new Texture2D(320, 240, TextureFormat.ARGB32, false, true);
if (_proceduralTextures) {
_ground = new Texture2D(1024, 1024, TextureFormat.ARGB32, false, true);
_sky = _ground;
CreateTexture(_ground);
}
_screen.filterMode = FilterMode.Point;
_ground.filterMode = FilterMode.Point;
_sky.filterMode = FilterMode.Point;
}
private void OnGUI() {
GUI.DrawTexture(new Rect(0f, 0f, Screen.width, Screen.height), _screen, ScaleMode.ScaleToFit);
}
private void Update() {
Simulate();
Render();
}
private void Simulate() {
float turn = Input.GetAxis("Horizontal");
float walk = Input.GetAxis("Vertical");
_worldRot += turn * Time.deltaTime;
float2 move;
math.sincos(_worldRot, out move.x, out move.y);
_worldPos += move * walk * _moveSpeed * Time.deltaTime;
}
private void Render() {
// Calculate frustum points
float rotL = _worldRot - _fovHalf;
float rotR = _worldRot + _fovHalf;
float2 frustumL;
float2 frustumR;
math.sincos(rotL, out frustumL.x, out frustumL.y);
math.sincos(rotR, out frustumR.x, out frustumR.y);
float2 farL = _worldPos + frustumL * _far;
float2 farR = _worldPos + frustumR * _far;
float2 nearL = _worldPos + frustumL * _near;
float2 nearR = _worldPos + frustumR * _near;
// Sample pixels per horizontal scanline
// Ground takes up half the screen, with vanishing point in the middle
// Sky is the same idea, but flipped upside down
int halfHeight = _screen.height / 2;
for (int y = 0; y < halfHeight; y++) {
float z = 1f - (float)y / ((float)halfHeight);
float2 start = nearL + (farL - nearL) / z;
float2 end = nearR + (farR - nearR) / z;
for (int x = 0; x < _screen.width; x++) {
float sampleWidth = (float)x / (float)_screen.width;
float2 sample = (end - start) * sampleWidth + start;
Color gcol = _ground.GetPixel((int)(sample.x * _ground.width), (int)(sample.y * _ground.height));
Color scol = _sky.GetPixel((int)(sample.x * _sky.width), (int)(sample.y * _sky.height));
_screen.SetPixel(x, y, gcol);
_screen.SetPixel(x, _screen.height - y, scol);
}
}
_screen.Apply();
}
private void CreateTexture(Texture2D map) {
for (int x = 0; x < map.width; x += 32) {
for (int y = 0; y < map.height; y++) {
// Draw horizontal lines
map.SetPixel(x, y, Color.magenta);
map.SetPixel(x + 1, y, Color.magenta);
map.SetPixel(x - 1, y, Color.magenta);
// Draw vertical lines (note: only works if map.width == map.height)
map.SetPixel(y, x, Color.blue);
map.SetPixel(y, x + 1, Color.blue);
map.SetPixel(y, x - 1, Color.blue);
}
}
map.Apply();
}
}
|
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 Lab06_RemoteControl
{
public partial class RemoteControl : Form
{
#region 4 Slots
//Slot 1
private ICommand Slot1ON = NoCommand.GetInstance();
private ICommand Slot1OFF = NoCommand.GetInstance();
//Slot 2
private ICommand Slot2ON = NoCommand.GetInstance();
private ICommand Slot2OFF = NoCommand.GetInstance();
//Slot 3...
#endregion
#region 7 Devices
//Light
private Light light;
private ICommand LightON;
private ICommand LightOFF;
//TV
private TV tv;
private ICommand TVON;
private ICommand TVOFF;
//Door
private Door door;
private ICommand DoorOn;
private ICommand DoorOff;
//Air conditioner
//Fan
//Main Door
#endregion
public RemoteControl()
{
InitializeComponent();
//Light
light = new Light(this.txtStatus1);
LightON = new LightOn(light);
LightOFF = new LightOff(light);
//TV
tv = new TV(this.btnTV);
TVON = new TVOn(tv);
TVOFF = new TVOff(tv);
//Door ...
door = new Door(this.pictureBoxDoor);
DoorOn = new DoorON(door);
DoorOff = new DoorOFF(door);
}
#region Slot 1
private void btnOn1_Click(object sender, EventArgs e)
{
Slot1ON.Execute();
}
private void btnOFF1_Click(object sender, EventArgs e)
{
Slot1OFF.Execute();
}
private void cboSlot1_SelectedIndexChanged(object sender, EventArgs e)
{
String option = cboSlot1.SelectedItem.ToString();
ChoiceDevice(option, 1);
}
#endregion
#region Slot 2
private void btnON2_Click(object sender, EventArgs e)
{
this.Slot2ON.Execute();
}
private void btnOFF2_Click(object sender, EventArgs e)
{
this.Slot2OFF.Execute();
}
private void cboSlot2_SelectedIndexChanged(object sender, EventArgs e)
{
String option = cboSlot2.SelectedItem.ToString();
ChoiceDevice(option, 2);
}
#endregion
private void AssignCommandOnOFF(String deviceName, ref ICommand ONCmd, ref ICommand OFFCmd)
{
if (deviceName.Equals("Light"))
{
OFFCmd = LightOFF;
ONCmd = LightON;
}
else if (deviceName.Equals("TV"))
{
OFFCmd = TVOFF;
ONCmd = TVON;
}
else if (deviceName.Equals("None"))
{
OFFCmd = NoCommand.GetInstance();
ONCmd = NoCommand.GetInstance();
}
else if (deviceName.Equals("Door"))
{
OFFCmd = DoorOff;
ONCmd = DoorOn;
}
}
private void ChoiceDevice(String deviceName, int slotNum)
{
if (slotNum == 1) //Slot 1
{
AssignCommandOnOFF(deviceName, ref Slot1ON, ref Slot1OFF);
}
else if(slotNum == 2) //Slot 2
{
AssignCommandOnOFF(deviceName, ref Slot2ON, ref Slot2OFF);
}
// Slot 3...
}
}
}
|
using SFML.Window;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modulus2D.Input
{
public static class Xbox
{
public const uint A = 0;
public const uint B = 1;
public const uint X = 2;
public const uint Y = 3;
public const uint LeftButton = 4;
public const uint RightButton = 5;
public const uint LeftTrigger = 6;
public const uint RightTrigger = 7;
public const uint Back = 8;
public const uint Select = 9;
public const uint LeftJoystick = 10;
public const uint RightJoystick = 11;
public const uint Up = 12;
public const uint Down = 13;
public const uint Left = 14;
public const uint Right = 15;
}
public class InputManager
{
List<BasicInput> values = new List<BasicInput>();
public void Add(BasicInput value)
{
values.Add(value);
}
public void Remove(BasicInput value)
{
values.Remove(value);
}
public void OnKeyPressed(object sender, KeyEventArgs e)
{
for (int i = 0; i < values.Count; i++)
{
values[i].OnKeyPressed(e.Code);
}
}
public void OnKeyReleased(object sender, KeyEventArgs e)
{
for (int i = 0; i < values.Count; i++)
{
values[i].OnKeyReleased(e.Code);
}
}
public void OnJoystickButtonPressed(object sender, JoystickButtonEventArgs e)
{
for (int i = 0; i < values.Count; i++)
{
values[i].OnJoystickButtonPressed(e.Button);
}
}
public void OnJoystickButtonReleased(object sender, JoystickButtonEventArgs e)
{
for (int i = 0; i < values.Count; i++)
{
values[i].OnJoystickButtonReleased(e.Button);
}
}
}
}
|
using System;
using System.Collections.Generic;
using Challenge_05_Repository;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Challenge_05_Tests
{
[TestClass]
public class EmailTests
{
[TestMethod]
public void AddCustomerToEmailList()
{
private EmailRepository _emailRepo = new emailRepository();
Email contentOne = new Email(CustomerType.Current, "Pitt", "Brad", "Thank you for your work with us. We appreciate your loyalty. Here's a coupon.");
Email contentTwo = new Email();
emailRepository.AddCustomerToEmailList(contentOne);
emailRepository.AddCustomerrToList(contentTwo);
List<Email> newCustomerInformation = emailRepository.GetListOfCustomers();
int actual = newCustomerInformation.Count;
int expected = 2;
Assert.AreEqual(expected, actual);
Assert.IsTrue(newCustomrInformation.Contains(customerrTwo));
}
[TestMethod]
public void RemoveCustomer()
{
EmailRepository _emailRepo = new EmailRepository();
Email customerr = new Email();
Email customerOne = new Email(CustomerType.Current, "Pitt", "Brad", "Thank you for your work with us. We appreciate your loyalty. Here's a coupon.");
_emailRepo.AddCustomerToEmailList();
_emailRepo.AddCustomerToEmailList(contentOne);
_emailRepo.RemoveCustomer(contentTne);
int actual = _emailRepo.GetListOfCustomers().Count;
int expected = 1;
Assert.AreEqual(expected, actual);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace DarkSample
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public static BindableProperty CurrentModeProperty = BindableProperty.Create(
nameof(CurrentMode),
typeof(string),
typeof(MainPage),
default(string),
defaultBindingMode: BindingMode.OneWay
);
public string CurrentMode
{
get { return (string)GetValue(CurrentModeProperty); }
set { SetValue(CurrentModeProperty, value); }
}
public MainPage()
{
InitializeComponent();
CurrentMode = GetCurrentMode((Theme)Xamarin.Essentials.Preferences.Get("mode", (int)Theme.Light));
}
string GetCurrentMode(Theme theme)
{
return theme switch
{
Theme.Light => "Light Theme",
Theme.Dark => "Dark Theme",
_ => "Auto"
};
}
void Light_Clicked(System.Object sender, System.EventArgs e)
{
CurrentMode = GetCurrentMode(Theme.Light);
ThemeResource.ChangeTheme(Theme.Light);
}
void Dark_Clicked(System.Object sender, System.EventArgs e)
{
CurrentMode = GetCurrentMode(Theme.Dark);
ThemeResource.ChangeTheme(Theme.Dark);
}
void Auto_Clicked(System.Object sender, System.EventArgs e)
{
CurrentMode = GetCurrentMode(Theme.Auto);
ThemeResource.ChangeTheme(Theme.Auto);
}
}
}
|
using Backend.Model;
using Backend.Service.RoomAndEquipment;
using ScheduleService.CustomException;
using ScheduleService.Model;
using ScheduleService.Repository.BackendMapper;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ScheduleService.Repository.Implementation
{
public class RoomRepository : IRoomRepository
{
private MyDbContext _context;
private Backend.Service.RoomAndEquipment.IRoomService _roomService;
public RoomRepository(MyDbContext context, IRoomService roomService)
{
_context = context;
_roomService = roomService;
}
public Room Get(int id)
{
try
{
var room = _context.Rooms.Find(id);
if (room is null)
throw new NotFoundException("Room with id " + id + " not found.");
return new Room(id, room.Usage.ToRoomType());
}
catch (ScheduleServiceException)
{
throw;
}
catch (Exception e)
{
throw new DataStorageException(e.Message);
}
}
public Room Get(int id, DateTime startDate, DateTime endDate)
{
try
{
var room = _context.Rooms.Find(id);
if (room is null)
throw new NotFoundException("Room with id " + id + " not found.");
var unavailable = GetUnavailableAppointments(id, startDate, endDate);
return new Room(id, room.Usage.ToRoomType(), unavailable);
}
catch (ScheduleServiceException)
{
throw;
}
catch (Exception e)
{
throw new DataStorageException(e.Message);
}
}
public IEnumerable<Room> GetByEquipmentTypes(RoomType type, IEnumerable<int> equipmentTypeIds, DateTime startDate, DateTime endDate)
{
try
{
var rooms = _roomService.GetRoomsByUsageAndEquipment(type.ToBackendRoomType(), equipmentTypeIds.ToList());
return rooms.Select(r => new Room(
r.Id, r.Usage.ToRoomType(), GetUnavailableAppointments(r.Id, startDate, endDate)));
}
catch (Exception e)
{
throw new DataStorageException(e.Message);
}
}
private IEnumerable<DateTime> GetUnavailableAppointments(int id, DateTime start, DateTime end)
{
try
{
return _context.Examinations.Where(
e => e.IdRoom.Equals(id)
&& e.DateAndTime <= end
&& e.DateAndTime >= start
&& e.ExaminationStatus != Backend.Model.Enums.ExaminationStatus.CANCELED).Select(
e => e.DateAndTime);
}
catch (Exception e)
{
throw new DataStorageException(e.Message);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class Menu : MonoBehaviour {
void Start () {
}
void Update () {
}
public void StartGame()
{
Application.LoadLevel("Tutorial");
}
public void LoadGame()
{
Caapora.GameManager.next_scene = "TestMap";
Application.LoadLevel("Loader");
}
public void ExitGame()
{
Application.Quit();
}
}
|
// Copyright (c) Bruno Brant. All rights reserved.
using System;
namespace RestLittle.UI.Plumbing
{
/// <summary>
/// Extensions of <see cref="TimeSpan"/>.
/// </summary>
public static class TimeSpanExtensions
{
/// <summary>
/// Prints a friendly elapsed time string.
/// </summary>
/// <param name="ts">
/// The amount of time elapsed.
/// </param>
/// <returns>
/// A friendly string describing the elapsed time.
/// </returns>
public static string ToFriendlyString(this TimeSpan ts)
{
if (ts < TimeSpan.Zero)
{
throw new Exception("TimeSpan can't be negative");
}
if (ts.TotalSeconds < 1)
{
return "0 seconds";
}
if (ts.TotalMinutes < 1)
{
var seconds = (int)ts.TotalSeconds;
return ToFriendlyString(seconds);
}
if (ts.TotalHours < 1)
{
var remainderSeconds = ts.TotalSeconds % 60;
var wholeMinutes = (ts.TotalSeconds - remainderSeconds) / 60;
return ToFriendlyString((int)wholeMinutes, (int)remainderSeconds);
}
var remainderMinutes = (int)ts.TotalMinutes % 60;
var wholeHours = (int)(ts.TotalMinutes - remainderMinutes) / 60;
return ToFriendlyStringHours(wholeHours, remainderMinutes);
}
private static string ToFriendlyStringHours(int hours, int minutes = 0)
{
if (minutes == 0)
{
return $"{hours} hour{Plural(hours)}";
}
return $"{hours} hour{Plural(hours)} {minutes} minute{Plural(minutes)}";
}
private static string ToFriendlyString(int seconds)
{
return $"{seconds} second{Plural(seconds)}";
}
private static string ToFriendlyString(int minutes, int seconds = 0)
{
if (seconds == 0)
{
return $"{minutes} minute{Plural(minutes)}";
}
return $"{minutes} minute{Plural(minutes)} {seconds} second{Plural(seconds)}";
}
private static string Plural(int value)
{
if (value != 1)
{
return "s";
}
return string.Empty;
}
}
}
|
using System.Reflection;
[assembly: AssemblyTitle("FurnitureAnywhere")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyVersion("1.1.7")]
[assembly: AssemblyFileVersion("1.1.7")]
|
using System.Linq;
using System.Collections.Generic;
using System;
using System.Reflection;
namespace SchemaObjectMapper
{
public abstract class BaseMapping
{
public PropertyInfo PropertyInfo { get; set; }
}
} |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace BootcampTwitterKata
{
public class EventsLoader : IEventsLoader
{
public void Load()
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DataLayer.Models
{
public class ContactMethod
{
[Key]
public int CMId { get; set; }
public string Value { get; set; }
public int ContactId { get; set; }
public int KeywordId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace SGpostMailData.Models
{
public class DatabaseContext : DbContext
{
public DbSet<Admin> admins { get; set; }
public DbSet<User> users { get; set; }
public DbSet<SgData> sgDatas { get; set; }
}
} |
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
namespace CheckLinkConsole
{
public static class Logs
{
public static LoggerFactory Factory = new LoggerFactory();
public static void Init(IConfiguration configuration)
{
//Factory.AddConsole( LogLevel.Trace, includeScopes: true );
Factory.AddConsole(configuration.GetSection("Logging"));
Factory.AddFile("logs/checklinks-{Date}.json",
isJson: true,
minimumLevel: LogLevel.Trace);
}
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using FiiiCoin.Utility;
using FiiiCoin.Wallet.Win.ViewModels;
using HtmlAgilityPack;
using System;
using System.Net;
using System.Text;
namespace FiiiCoin.Wallet.Win.Biz.Monitor
{
public class AppUdateMonitor : ServiceMonitorBase<bool?>
{
private static AppUdateMonitor _default;
public static AppUdateMonitor Default
{
get
{
if (_default == null)
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
_default = new AppUdateMonitor();
}
return _default;
}
}
protected override bool? ExecTaskAndGetResult()
{
return CheckVersion();
}
public const string AppUrl = "https://github.com/FiiiLab/FiiiCoin/releases";
public string GetRemoteVersion()
{
try
{
WebClient webClient = new WebClient();
webClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
byte[] pageData = webClient.DownloadData(AppUrl);
string pageHtml = Encoding.UTF8.GetString(pageData);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(pageHtml);
Logger.Singleton.Debug(pageHtml);
HtmlNodeCollection hrefList = doc.DocumentNode.SelectNodes("//div[@class='f1 flex-auto min-width-0 text-normal']/a");
if (hrefList != null && hrefList.Count > 0)
{
return hrefList[0].InnerHtml;
}
}
catch (Exception ex)
{
Logger.Singleton.Warn(ex.ToString());
}
return null;
}
bool? CheckVersion()
{
var remoteVersion = GetRemoteVersion();
Logger.Singleton.Debug($"GetVersion Result = {(remoteVersion == null ? "NULL" : remoteVersion)}");
if (remoteVersion == null)
return true;
if (StaticViewModel.GlobalViewModel.VERSION != remoteVersion)
{
return false;
}
else
{
return true;
}
}
}
} |
using System;
namespace Fragenkatalog.Model
{
class AttributeNotNullException : ArgumentNullException
{
}
}
|
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace skyConverter.ModelStructure
{
class Mesh : ISerializer
{
private String _name = "";
private int _countVertices;
private List<Face> _faces;
private Material _material;
public Mesh(String _name)
{
this._name = _name;
_faces = new List<Face>();
this._material = new Material("Materials/Phong.mat", "PHONG");
this._material.specular = new double[] { 1.0, 1.0, 1.0, 1.0 };
this._material.specularIntensity = 0.0;
this._material.diffuse = new double[] { 1.0, 1.0, 1.0, 1.0 };
}
public void AddFace(Face face)
{
_faces.Add(face);
}
public void SetCountVertices()
{
this._countVertices = _faces.Count * 3;
}
public JObject serializeObject()
{
JObject obj = new JObject();
obj.Add("Name", _name);
obj.Add("Vertices", _countVertices);
if (_faces.Count > 0)
{
JArray facesNode = new JArray();
for (int i = 0; i < _faces.Count; i++)
{
facesNode.Add(_faces[i].serializeArray());
}
obj.Add("Faces", facesNode);
obj.Add("Material", this._material.serializeObject());
return obj;
}
return null;
}
public JArray serializeArray()
{
return null;
}
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using EdjCase.JsonRpc.Client;
using EdjCase.JsonRpc.Core;
using FiiiCoin.Utility;
using FiiiCoin.Utility.Api;
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace FiiiCoin.ServiceAgent
{
public class WalletManagement
{
/// <summary>
///
/// </summary>
/// <param name="filePath">contains file extend name</param>
/// <returns></returns>
public async Task BackupWallet(string filePath)
{
AuthenticationHeaderValue authHeaderValue = null;
RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json");
RpcRequest request = RpcRequest.WithParameterList("BackupWallet", new[] { filePath }, 1);
RpcResponse response = await client.SendRequestAsync(request);
if (response.HasError)
{
throw new ApiCustomException(response.Error.Code, response.Error.Message);
}
}
/// <summary>
///
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public async Task RestoreWalletBackup(string filePath, string password = null)
{
AuthenticationHeaderValue authHeaderValue = null;
RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json");
RpcRequest request = RpcRequest.WithParameterList("RestoreWalletBackup", new[] { filePath, password }, 1);
RpcResponse response = await client.SendRequestAsync(request);
if (response.HasError)
{
throw new ApiCustomException(response.Error.Code, response.Error.Message);
}
}
public async Task EncryptWallet(string password)
{
AuthenticationHeaderValue authHeaderValue = null;
RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json");
RpcRequest request = RpcRequest.WithParameterList("EncryptWallet", new[] { password }, 1);
RpcResponse response = await client.SendRequestAsync(request);
if (response.HasError)
{
throw new ApiCustomException(response.Error.Code, response.Error.Message);
}
}
public async Task<bool> WalletPassphrase(string password)
{
AuthenticationHeaderValue authHeaderValue = null;
RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json");
RpcRequest request = RpcRequest.WithParameterList("WalletPassphrase", new[] { password }, 1);
RpcResponse response = await client.SendRequestAsync(request);
if (response.HasError)
{
throw new ApiCustomException(response.Error.Code, response.Error.Message);
}
bool result = response.GetResult<bool>();
return result;
}
public async Task WalletLock()
{
AuthenticationHeaderValue authHeaderValue = null;
RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json");
RpcRequest request = RpcRequest.WithNoParameters("WalletLock", 1);
RpcResponse response = await client.SendRequestAsync(request);
if (response.HasError)
{
throw new ApiCustomException(response.Error.Code, response.Error.Message);
}
}
/// <summary>
/// change password
/// </summary>
/// <param name="oldPassword"></param>
/// <param name="newPassword"></param>
/// <returns></returns>
public async Task WalletPassphraseChange(string oldPassword, string newPassword)
{
AuthenticationHeaderValue authHeaderValue = null;
RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json");
RpcRequest request = RpcRequest.WithParameterList("WalletPassphraseChange", new List<object> { oldPassword, newPassword }, 1);
RpcResponse response = await client.SendRequestAsync(request);
if (response.HasError)
{
throw new ApiCustomException(response.Error.Code, response.Error.Message);
}
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DEV_13.Test
{
[TestClass]
public class CheckerOfConditionTests
{
//TestMethod checks Method IfCorrectCash which returns true
//if the value of cash is greater than the junior salary
[TestMethod]
public void IfCorrectCashWithValueBiggerThanSalaryOfJuniorReturnedTrue()
{
CheckerOfCondition checkerOfCondition = new CheckerOfCondition();
InitialCondition initialCondition = new InitialCondition();
initialCondition.cash = 1000;
Assert.IsTrue(checkerOfCondition.IfCorrectCash(initialCondition));
}
//TestMethod checks Method IfCorrectCash which returns true
//if the value of cash is equal the junior salary
[TestMethod]
public void IfCorrectCashWithValueEqualSalaryOfJuniorReturnedTrue()
{
CheckerOfCondition checkerOfCondition = new CheckerOfCondition();
InitialCondition initialCondition = new InitialCondition();
initialCondition.cash = 500;
Assert.IsTrue(checkerOfCondition.IfCorrectCash(initialCondition));
}
//TestMethod checks Method IfCorrectCash which returns false
//if the value of cash is less than the junior salary
[TestMethod]
public void IfCorrectCashWithLessThanSalaryOfJuniorReturnedFalse()
{
CheckerOfCondition checkerOfCondition = new CheckerOfCondition();
InitialCondition initialCondition = new InitialCondition();
initialCondition.cash = 300;
Assert.IsFalse(checkerOfCondition.IfCorrectCash(initialCondition));
}
//TestMethod checks Method IfCorrectCash which returns false
//if the value of cash is null
[TestMethod]
public void IfCorrectCashWithNullVallueJuniorReturnedFalse()
{
CheckerOfCondition checkerOfCondition = new CheckerOfCondition();
InitialCondition initialCondition = new InitialCondition();
initialCondition.cash = 0;
Assert.IsFalse(checkerOfCondition.IfCorrectCash(initialCondition));
}
//TestMethod checks Method IfCorrectCash which returns false
//if the value of cash is negative
[TestMethod]
public void IfCorrectCashWithNegativeValueReturnedFalse()
{
CheckerOfCondition checkerOfCondition = new CheckerOfCondition();
InitialCondition initialCondition = new InitialCondition();
initialCondition.cash = -5;
Assert.IsFalse(checkerOfCondition.IfCorrectCash(initialCondition));
}
//TestMethod checks Method IfCorrectCash which returns false
//if the value of cash is Maximum of Int32
[TestMethod]
public void IfCorrectCashWithValueMaxThanIntReturnedFalse()
{
CheckerOfCondition checkerOfCondition = new CheckerOfCondition();
InitialCondition initialCondition = new InitialCondition();
initialCondition.cash = Int32.MaxValue;
Assert.IsFalse(checkerOfCondition.IfCorrectCash(initialCondition));
}
//TestMethod checks Method IfCorrectCash which returns true
//if the value of productivity is greater than null
[TestMethod]
public void IfCorrectProductivityWithValueBiggerThanNullReturnedTrue()
{
CheckerOfCondition checkerOfCondition = new CheckerOfCondition();
InitialCondition initialCondition = new InitialCondition();
initialCondition.productivity = 1000;
Assert.IsTrue(checkerOfCondition.IfCorrectProductivity(initialCondition));
}
//TestMethod checks Method IfCorrectCash which returns true
//if the value of cash is null
[TestMethod]
public void IfCorrectProductivityWithNullValueReturnedTrue()
{
CheckerOfCondition checkerOfCondition = new CheckerOfCondition();
InitialCondition initialCondition = new InitialCondition();
initialCondition.productivity = 0;
Assert.IsTrue(checkerOfCondition.IfCorrectProductivity(initialCondition));
}
//TestMethod checks Method IfCorrectCash which returns false
//if the value of cash is negative
public void IfCorrectProductivityWithNegativeValueReturnedFalse()
{
CheckerOfCondition checkerOfCondition = new CheckerOfCondition();
InitialCondition initialCondition = new InitialCondition();
initialCondition.productivity = -5;
Assert.IsFalse(checkerOfCondition.IfCorrectProductivity(initialCondition));
}
//TestMethod checks Method IfCorrectCash which returns false
//if the value of cash is Maximum Int32
public void IfCorrectProductivityWithMaxIntValueReturnedFalse()
{
CheckerOfCondition checkerOfCondition = new CheckerOfCondition();
InitialCondition initialCondition = new InitialCondition();
initialCondition.productivity = Int32.MaxValue;
Assert.IsFalse(checkerOfCondition.IfCorrectProductivity(initialCondition));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercicio32
{
class MultiplicacaoDeMatrizes
{
static void Main(string[] args)
{
{
int[,] A = { { 1, 2, 3 }, { 4, 0, 2 } };
int N1 = A.GetLength(0);
int M1 = A.GetLength(1);
int[,] B = { { 1, 0 }, { 2, 2 }, { 3, 3 } };
int N2 = B.GetLength(0);
int M2 = B.GetLength(1);
int[,] C = new int[N1, M2];
int Total = 0;
for (int I = 0; I <= N1 - 1; I++)
{
for (int K = 0; K <= M2 - 1; K++)
{
Total = 0;
for (int J = 0; J <= M1 - 1; J++)
Total = Total + A[I, J] * B[J, K];
C[I, K] = Total;
}
}
for (int I = 0; I <= N1 - 1; I++)
{
for (int J = 0; J <= M2 - 1; J++)
Console.Write("{0, 4}", C[I, J]);
Console.WriteLine();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using InhaMate.Sources_Core.IGEC;
namespace InhaMate.Sources_Core
{
public class InhaLogin
{
private static InhaLogin _instance;
public static InhaLogin Instance()
{// make new instance if null
return _instance ?? (_instance = new InhaLogin());
}
protected InhaLogin()
{
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, policyErrors) => { return true; };
InitWebsites();
}
// IGEC에 POST 날릴 때 쓰이는 파라미터 저장용
private readonly IGECParams _IGECParams = IGECParams.Instance();
// IGEC 로그인 시 받아와지는 수강 과목 정보를 저장함
public List<IGECSubject> IGECSubjects = new List<IGECSubject>();
public IGECParams igecParams = IGECParams.Instance();
// 긁어온 웹페이지를 저장함
public Dictionary<string, string> pagesIGEC = new Dictionary<string, string>();
public Dictionary<string, string> pagesPlaza = new Dictionary<string, string>();
public CookieCollection cookies = new CookieCollection();
public CookieContainer cookie = new CookieContainer();
// HTML parser
private HtmlDocument htmlDoc = new HtmlDocument();
// HTML파싱용 객체
public HtmlDocument HTMLDoc
{
get { return htmlDoc; }
set { htmlDoc = value; }
}
// SSO 리다이렉트 주소
public string IGECredirect = "";
// SSO 파라미터
public string SSO = "";
private bool loggedin = false;
public static Dictionary<string, Tuple<string, int>> websites;
public bool isNull()
{
return _id == "" && _pass == "";
}
// 각 사이트 POST 데이터
public string PostABEEK()
{
var template =
"__VIEWSTATE=" + "%2FwEPDwUJNjIwMTUzMTE2D2QWAmYPZBYEAgQPZBYCAgUPDxYCHg1PbkNsaWVudENsaWNrBSRyZXR1cm4gQ2hlY2tGb3JtKCd0eHRJRCcsICd0eHRQd2QnKTtkZAIGDw8WAh4HVmlzaWJsZWhkZBgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18WAQUIYnRuTG9naW7wzR3dwjp4dipm4Q%2BLNXJPGqU0OiOmNG0Mvz%2B8wzn1nw%3D%3D"
+ "&__VIEWSTATEGENERATOR=" + "CA0B0334"
+ "&__EVENTVALIDATION=" + "%2FwEdAAYJs729xFbUAI4vKyRF73DbWGxGOeI%2FqksaXRgyrlUKASo8hE5ZXwcR0kPF8CxQfbRZ3KM44mNrnq0%2BH8oX8i7LM9KW7XpjHhBuINT5110rU6KeKEbp39eHc9mbdvkCgxA4TAiGCw5sVK1I2suKJfVwpfKb7dZSBLIx9c3zXmtPLQ%3D%3D"
+ "&hdn1=" + "&hdn2="
+ "&txtID=" + ID
+ "&txtPwd=" + Password
+ "&btnLogin.x=40&btnLogin.y=23";
return template;
}
public string PostPlaza(string id = "", string pw = "")
{
if (id.Equals("") || pw.Equals(""))
{
var template =
"dest=" + "http%3A%2F%2Fwww.inha.ac.kr%2Fplaza.asp%3Fcon_chk%3Dno"
+ "&uid=" + EncodedID()
+ "&pwd=" + EncodedPW()
+ "&uidinput=&pwdinput=";
return template;
}
else
{
var template =
"dest=" + "http%3A%2F%2Fwww.inha.ac.kr%2Fplaza.asp%3Fcon_chk%3Dno"
+ "&uid=" + EncodedID(id)
+ "&pwd=" + EncodedPW(pw)
+ "&uidinput=&pwdinput=";
return template;
}
}
public string PostIGEC1()
{
var template =
"p_grcode=N000001"
+ "&p_userid=" + EncodedID()
+ "&p_passwd=" + EncodedPW();
return template;
}
public string PostIGEC2(string post1)
{
var pos = post1.IndexOf("[", StringComparison.Ordinal);
post1 = post1.Substring(pos, post1.Length - pos);
return _IGECParams.GeneratePost(post1);
}
public Dictionary<string, Tuple<string, int>> Websites
{
get { return websites; }
}
private void InitWebsites()
{
websites = new Dictionary<string, Tuple<string, int>>
{
{"ABEEK", Tuple.Create("https://abeek.inha.ac.kr", 65001)},
{"ABEEKMain", Tuple.Create("https://abeek.inha.ac.kr/STMain.aspx", 65001)},
{"SugangHome", Tuple.Create("http://sugang.inha.ac.kr/sugang/Home.aspx", 949)},
{"SugangMenu", Tuple.Create("http://sugang.inha.ac.kr/sugang/Menu.aspx", 949)},
{"SugangConfirm", Tuple.Create("http://sugang.inha.ac.kr/sugang/SU_53002/Sugang_Confirm.aspx", 949)},
//{"Inha", Tuple.Create("http://www.inha.ac.kr/common/asp/login/loginProcess.asp?con_chk=serv", 949)},
{"Plaza", Tuple.Create("http://plaza.inha.ac.kr/plaza.asp", 949)},
{"PlazaLogin", Tuple.Create("https://plaza.inha.ac.kr/common/asp/login/loginProcess.asp", 949)},
{"PlazaBest", Tuple.Create("http://plaza.inha.ac.kr/talktalk/talktalkList.asp?pBType=1&pGubun=2", 949)},
{"PlazaArticle", Tuple.Create("http://plaza.inha.ac.kr/talktalk/talktalkView.asp", 949)},
{"IGEC1", Tuple.Create("http://igec.inha.ac.kr/jsp/include/ajax.login.jsp", 65001)},
{"IGEC2", Tuple.Create("http://igec.inha.ac.kr/servlet/controller.homepage.MainServlet", 65001)},
{"IGECSubjects", Tuple.Create("http://igec.inha.ac.kr/jsp/include/ajax.subj2.jsp", 65001)},
{
"IGECeClassMain",
Tuple.Create("http://igec.inha.ac.kr/servlet/controller.learn.ClassMainServlet?p_process=mainList",
65001)
}
};
}
public void connectIGEC()
{
string loginData = PostIGEC1();
string post = RequestWebPage(Websites["IGEC1"].Item1
, loginData
, cookie
, Encoding.GetEncoding(Websites["IGEC1"].Item2));
loginData = PostIGEC2(post);
//string result = loginData;
RequestWebPage(Websites["IGEC2"].Item1
, loginData
, cookie
, Encoding.GetEncoding(Websites["IGEC2"].Item2));
}
public void connectPlaza()
{
// 지금은 로그인 체크 루틴이 광장 로그인이기 때문에 한 번 더 할 필요는 없다
if (!loggedin)
{
string loginData = PostPlaza();
string result = RequestWebPage(Websites["PlazaLogin"].Item1
, loginData
, cookie
, Encoding.GetEncoding(Websites["PlazaLogin"].Item2));
Match match = Regex.Match(result, @"do\?t=(.*)&id=");
SSO = match.Groups[1].Value;
result = MoveToAnotherPage("http://plaza.inha.ac.kr/plaza.asp?con_chk=serv", cookie, Encoding.GetEncoding(949));
}
}
public void getIGECPages()
{
string loginData = PostIGEC1();
string post = RequestWebPage(Websites["IGEC1"].Item1
, loginData
, cookie
, Encoding.GetEncoding(Websites["IGEC1"].Item2));
loginData = PostIGEC2(post);
//string result = loginData;
string result = RequestWebPage(Websites["IGEC2"].Item1
, loginData
, cookie
, Encoding.GetEncoding(Websites["IGEC2"].Item2));
if (!pagesIGEC.ContainsKey("IGECMain"))
{
pagesIGEC.Add("IGECMain", result);
}
//igecDebugTextBox.Text += pagesIGEC["IGECMain"];
// 처음 로그인 했을 때 추가로 들어오는 유저 정보를 뽑아내야함
getIGECUserParam();
getIGECSubjects();
// IGECMain 페이지에서 정보를 IGECParams에 더 긁어넣고 요청해야했음
result = RequestWebPage(Websites["IGECeClassMain"].Item1
, igecParams.GeneratePostForMainList()
, cookie
, Encoding.GetEncoding(Websites["IGECeClassMain"].Item2)
, "http://igec.inha.ac.kr/servlet/controller.homepage.MainServlet"
, "http://igec.inha.ac.kr"
, "igec.inha.ac.kr");
if (!pagesIGEC.ContainsKey("IGECEclassMain"))
{
pagesIGEC.Add("IGECeClassMain", result);
}
// 불러오는데 성공 ㅎㅅㅎ
//igecDebugTextBox.Text += pagesIGEC["IGECeClassMain"];
}
public void getIGECUserParam()
{
HTMLDoc.LoadHtml(pagesIGEC["IGECMain"]);
// SelectNodes: WPF; Descendants: WP8, Mono
foreach (var item in HTMLDoc.DocumentNode.Descendants(@"//script[not(@src)]"))
{
var data = item.ChildNodes[0].InnerHtml;
var start = data.IndexOf("$(function(){", StringComparison.Ordinal);
if (start == -1) continue;
data = data.Substring(start, data.IndexOf("$form = $(\"#mainForm\");", StringComparison.Ordinal) - start);
Match match = Regex.Match(data, @"_INHA.Init = (.*);");
var Init = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.Session = ""(.*)"";");
var Session = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.Grcode = ""(.*)"";");
var Grcode = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.Systemgubun = ""(.*)"";");
var Systemgubun = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.Levels = ""(.*)"";");
var Levels = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.Language = ""(.*)"";");
var language = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.Mtype = ""(.*)"";");
var Mtype = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.MenuTop = ""(.*)"";");
var MenuTop = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.passwdCheck = ""(.*)"";");
var passwdCheck = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.Ip = ""(.*)"";");
var Ip = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.Userid = ""(.*)"";");
var Userid = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.UserName = ""(.*)"";");
var UserName = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.UserName_kor = ""(.*)"";");
var UserName_kor = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.UserName_eng = ""(.*)"";");
var UserName_eng = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.UserName_jpn = ""(.*)"";");
var UserName_jpn = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.UserName_chn = ""(.*)"";");
var UserName_chn = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.Comp = ""(.*)"";");
var Comp = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.Auth = ""(.*)"";");
var Auth = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.Subj = ""(.*)"";");
var Subj = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.Year = ""(.*)"";");
var Year = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.SubjSeq = ""(.*)"";");
var SubjSeq = match.Groups[1].Value;
match = Regex.Match(data, @"_INHA.SubjClass = ""(.*)"";");
var SubjClass = match.Groups[1].Value;
//igecParams.process =
igecParams.grcode = Grcode;
igecParams.subj = Subj;
igecParams.year_ = Year;
igecParams.subjseq = SubjSeq;
igecParams.class_ = SubjClass;
igecParams.systemgubun = Systemgubun;
igecParams.levels = Levels;
igecParams.userid = Userid;
igecParams.comp = Comp;
igecParams.ip = Ip;
igecParams.name = UserName;
igecParams.name_kor = UserName_kor;
igecParams.name_eng = UserName_eng;
igecParams.name_chn = UserName_chn;
igecParams.name_jpn = UserName_jpn;
igecParams.auth = Auth;
igecParams.mtype = Mtype;
igecParams.language = language;
igecParams.menutop = MenuTop;
igecParams.passwdcheck = passwdCheck;
}
}
public void getIGECSubjects()
{
// 수강하는 과목 정보를 뽑아내야함
string result = RequestWebPage(Websites["IGECSubjects"].Item1
, igecParams.GeneratePostForMainList()
, cookie
, Encoding.GetEncoding(Websites["IGECSubjects"].Item2)
, IGECredirect);
//igecDebugTextBox.Text += result;
// 여러 개의 match를 얻으려면 Matches를 써야함
foreach (Match m in Regex.Matches(result
, @"({auth:'.', authnm:escape\('학생'\), grcode:'.{7}', subj:'.{0,7}', year:'\d{4}', subjseq:'\d{2}', grcode_subjseq:'\d{2} \[.{2}\]', subjclass:'.{3}', subjnm:'.{0,30}'})"))
{
string subject_s = m.Groups[1].Value;
Match match = Regex.Match(subject_s
, @"{auth:('.'), authnm:(escape\('학생'\)), grcode:'(.{7})', subj:'(.{0,7})', year:'(\d{4})', subjseq:'(\d{2})', grcode_subjseq:'(\d{2} \[.{2}\])', subjclass:'(.{3})', subjnm:'(.{0,30})'}");
IGECSubject subject = new IGECSubject(
match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value
, match.Groups[4].Value, match.Groups[5].Value, match.Groups[6].Value
, match.Groups[7].Value, match.Groups[8].Value, match.Groups[9].Value);
IGECSubjects.Add(subject);
}
igecParams.grcode = IGECSubjects.ElementAt(0).grcode;
igecParams.subj = IGECSubjects.ElementAt(0).subj;
igecParams.year_ = IGECSubjects.ElementAt(0).year;
igecParams.subjseq = IGECSubjects.ElementAt(0).subjseq;
igecParams.class_ = IGECSubjects.ElementAt(0).subjclass;
igecParams.menutop = "009000000";
}
public void getPlazaPages()
{
// 최다추천글, referer 필요
string result = MoveToAnotherPage(Websites["PlazaBest"].Item1
, cookie
, Encoding.GetEncoding(Websites["PlazaBest"].Item2)
, Websites["Plaza"].Item1);
if (!pagesPlaza.ContainsKey("PlazaBest"))
{
pagesPlaza.Add("PlazaBest", result);
}
else
{
pagesPlaza["PlazaBest"] = result;
}
}
// 계정 정보
private string _id;
private string _pass;
public string ID
{
get { return _id; }
set { _id = value; }
}
public string Password
{
get { return _pass; }
set { _pass = value; }
}
public string EncodedID(string id = "")
{
Encoding oEncoding = Encoding.UTF8;
if (!id.Equals(""))
{
var arr = oEncoding.GetBytes(id);
return Convert.ToBase64String(arr);
}
else
{
var arr = oEncoding.GetBytes(ID);
return Convert.ToBase64String(arr);
}
}
public string EncodedPW(string pw = "")
{
var oEncoding = Encoding.UTF8;
if (!pw.Equals(""))
{
var arr = oEncoding.GetBytes(pw);
return Convert.ToBase64String(arr);
}
else
{
var arr = oEncoding.GetBytes(Password);
return Convert.ToBase64String(arr);
}
}
// 입력 받은 계정으로 로그인이 되는지 확인
// 로그인이 되면 ID와 PW가 객체에 저장되고 아니면 저장안함
public bool isValid(string id, string pw)
{
if (!loggedin)
{
RequestWebPage(Websites["PlazaLogin"].Item1
, PostPlaza(id, pw)
, cookie
, Encoding.GetEncoding(Websites["PlazaLogin"].Item2));
string result = MoveToAnotherPage("http://plaza.inha.ac.kr/plaza.asp?con_chk=serv"
, cookie
, Encoding.GetEncoding(Websites["PlazaLogin"].Item2));
if (result.IndexOf("님, 환영합니다.", StringComparison.Ordinal) > -1)
{
// 광장 메인 홈 저장
if (!pagesPlaza.ContainsKey("PlazaMain"))
{
pagesPlaza.Add("PlazaMain", result);
}
else
{
pagesPlaza["PlazaMain"] = result;
}
loggedin = true;
ID = id;
Password = pw;
return true;
}
if (result.IndexOf("ERR", StringComparison.Ordinal) > -1)
{
return false;
}
return false;
}
return loggedin;
}
public byte[] GetProfileImageData()
{
string link = "http://igec.inha.ac.kr/jsp/library/zu_photo.jsp?p_userid=" + EncodedID();
var hwr = (HttpWebRequest)WebRequest.Create(link);
hwr.Method = "GET";
hwr.Accept = @"image/png,image/*";
hwr.KeepAlive = false;
hwr.CookieContainer = cookie;
var resp = hwr.GetResponse();
var respStream = resp.GetResponseStream();
byte[] outData;
using (var tempMemStream = new MemoryStream())
{
byte[] buffer = new byte[128];
while (true)
{
if (respStream != null)
{
int read = respStream.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
outData = tempMemStream.ToArray();
break;
}
tempMemStream.Write(buffer, 0, read);
}
}
}
return outData;
}
public bool SaveIGECPDSFile(Attachment file, string savePath)
{
string link = "http://igec.inha.ac.kr/servlet/controller.library.DownloadServlet";
var req = (HttpWebRequest)WebRequest.Create(link);
req.Method = "POST";
req.Accept = @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
req.Headers.Add(@"Accept-Encoding", @"gzip, deflate");
req.Headers.Add(@"Accept-Language", @"ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4");
req.UserAgent =
@"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36";
req.KeepAlive = false;
req.CookieContainer = cookie;
req.ContentLength = file.Param.GeneratePost().Length;
req.ContentType = @"application/x-www-form-urlencoded";
req.Headers.Add(@"Origin", @"http://igec.inha.ac.kr");
req.Referer = @"http://igec.inha.ac.kr/servlet/controller.learn.AssPdsStuServlet";
try
{
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.Write(file.Param.GeneratePost());
writer.Close();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
//long total = 0;
int received = 0;
FileStream fileStream = File.OpenWrite(savePath);
using (var respStream = resp.GetResponseStream())
{
byte[] buffer = new byte[128];
if (respStream != null)
{
//total = respStream.Length;
int size = respStream.Read(buffer, 0, buffer.Length);
while (size > 0)
{
fileStream.Write(buffer, 0, size);
received += size;
size = respStream.Read(buffer, 0, buffer.Length);
}
}
}
fileStream.Flush();
fileStream.Close();
return true;
}
catch (Exception e)
{
return false;
}
}
/* HTTP 요청 함수들 */
public string RequestWebPage(string url, string sendData, CookieContainer cook, Encoding encoding, string referer = "", string origin = "", string host = "")
{
var req = (HttpWebRequest)WebRequest.Create(url);
if (!host.Equals("")) { req.Host = host; }
req.Headers.Add(@"Cache-Control", @"max-age=0");
if (!origin.Equals("")) { req.Headers.Add(@"Origin", origin); }
req.Headers.Add(@"Accept-Encoding", @"gzip,deflate");
req.UserAgent = @"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36";
req.Accept = @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
req.Method = @"POST";
req.ContentLength = sendData.Length;
req.ContentType = @"application/x-www-form-urlencoded";
req.KeepAlive = true;
req.CookieContainer = cook; // 세션 저장 쿠키
req.ServicePoint.UseNagleAlgorithm = false;
req.ServicePoint.Expect100Continue = false;
// 속도 개선
if (!isProxyEnabled()) { req.Proxy = WebRequest.DefaultWebProxy; }
if (!referer.Equals("")) { req.Referer = referer; }
// req.Credentials = CredentialCache.DefaultCredentials;
try
{
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.Write(sendData);
writer.Close();
using (HttpWebResponse result = (HttpWebResponse)req.GetResponse())
{
result.Cookies = req.CookieContainer.GetCookies(req.RequestUri);
// SSO 및 SSO 포함된 링크 저장용 루틴
if (url.Equals("http://igec.inha.ac.kr/servlet/controller.homepage.MainServlet"))
{
IGECredirect = result.ResponseUri.AbsoluteUri;
string value = result.ResponseUri.Query;
value = value.Replace("?t=", "");
SSO = value;
}
// 요청이 성공적일 때
if (result.StatusCode.Equals(HttpStatusCode.OK))
{
cookies.Add(result.Cookies);
//Encoding encode = Encoding.GetEncoding("UTF-8");
using (Stream strReceiveStream = result.GetResponseStream())
{
if (strReceiveStream != null)
{
StreamReader reqStreamReader = new StreamReader(strReceiveStream, encoding);
string strResult = reqStreamReader.ReadToEnd(); // 데이터 읽어옴
req.Abort();
strReceiveStream.Close();
reqStreamReader.Close();
return strResult;
}
}
}
else
{
return "ERR";
}
}
return "ERR";
}
catch (WebException e)
{
if (e.Status.Equals(WebExceptionStatus.NameResolutionFailure))
{
//MessageBox.Show("인터넷 연결을 확인해주세요");
return "ERR";
}
if (e.Status.Equals(WebExceptionStatus.ProtocolError))
{
return "ERR";
}
throw;
}
}
public string MoveToAnotherPage(string url, CookieContainer cook, Encoding encoding, string referer = "")
{
if (cook == null) throw new ArgumentNullException("cook");
var req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = cook; // 보관된 cookie 이용
req.Referer = referer;
req.ServicePoint.Expect100Continue = false;
req.ServicePoint.UseNagleAlgorithm = false;
if (!isProxyEnabled()) { req.Proxy = null; }
//req.Credentials = CredentialCache.DefaultCredentials;
try
{
using (HttpWebResponse result = (HttpWebResponse)req.GetResponse())
{
result.Cookies = req.CookieContainer.GetCookies(req.RequestUri);
cookies.Add(result.Cookies); // 추가적인 cookie 보관
using (Stream strm = result.GetResponseStream())
{
if (strm != null)
{
StreamReader sr = new StreamReader(strm, encoding, true);
string responseHtml = sr.ReadToEnd();
sr.Close();
strm.Close();
return responseHtml;
}
}
}
}
catch (WebException e)
{
if (e.Status.Equals(WebExceptionStatus.NameResolutionFailure))
{
//MessageBox.Show("인터넷 연결을 확인해주세요");
return "ERR";
}
if (e.Status.Equals(WebExceptionStatus.ProtocolError))
{
return "ERR";
}
throw;
}
return "ERR";
}
private bool isProxyEnabled()
{
if (WebRequest.DefaultWebProxy.Credentials == null)
{
return false;
}
return true;
}
}
}
|
namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts
{
public interface IGraphDeleteItemSyncContext : IItemSyncContext, IGraphDeleteContext
{
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;
namespace Caserraria
{
public class MyPlayer : ModPlayer
{
public bool Ornate = false;
public bool MoonWalk = false;
public bool Oof = false;
public bool hoardCalled = false;
public override void ResetEffects()
{
Ornate = false;
MoonWalk = false;
Oof = false;
}
public override void UpdateEquips(ref bool wallSpeedBuff, ref bool tileSpeedBuff, ref bool tileRangeBuff)
{
if (Ornate)
{
MyPlayer p = player.GetModPlayer<MyPlayer>();
if (player.velocity.Y != 0)
{
if (player.velocity.X > 0)
{
player.fullRotationOrigin = player.Center - player.position;
player.fullRotation += 0.25f;
}
if (player.velocity.X < 0)
{
player.fullRotationOrigin = player.Center - player.position;
player.fullRotation -= 0.25f;
}
}
else
{
player.fullRotation = 0f;
}
}
}
public override void PreUpdateMovement()
{
if (MoonWalk == true)
{
if (player.controlRight == true)
{
player.direction = 0;
}
if (player.controlLeft == true)
{
player.direction = 1;
}
}
}
public override bool PreHurt(bool pvp, bool quiet, ref int damage, ref int hitDirection, ref bool crit, ref bool customDamage, ref bool playSound, ref bool genGore, ref PlayerDeathReason damageSource)
{
if (Oof)
{
playSound = false;
}
return true;
}
public override void Hurt(bool pvp, bool quiet, double damage, int hitDirection, bool crit)
{
if (Oof)
{
Main.PlaySound(SoundLoader.customSoundType, (int)player.position.X, (int)player.position.Y, mod.GetSoundSlot(SoundType.Custom, "Sounds/OOF"));
}
}
}
} |
namespace SoftUniStore.Client.Api.CommonModels.ViewModels.Games
{
using System.Text;
public class AdminGameViewModel
{
public int GameId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public decimal Size { get; set; }
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("<tr>");
sb.Append($"<td>{this.Title}</td>");
sb.Append($"<td>{this.Size} GB</td>");
sb.Append($"<td>{this.Price} €</td>");
sb.Append("<td>");
sb.Append($"<a href=\"/catalog/EditGame?gameId={this.GameId}\" class=\"btn btn-warning btn-sm\">Edit</a>");
sb.Append($"<a href=\"/catalog/DeleteGame?gameId={this.GameId}\" class=\"btn btn-danger btn-sm\">Delete</a>");
sb.Append("</td>");
sb.Append("</tr>");
return sb.ToString();
}
}
} |
using Alabo.Properties;
using Microsoft.AspNetCore.Identity;
namespace Alabo.Security.Identity.Describers {
/// <summary>
/// Identity中文错误描述
/// </summary>
public class IdentityErrorChineseDescriber : IdentityErrorDescriber {
/// <summary>
/// 密码太短
/// </summary>
public override IdentityError PasswordTooShort(int length) {
return new IdentityError {
Code = nameof(PasswordTooShort),
Description = string.Format(SecurityResource.PasswordTooShort, length)
};
}
/// <summary>
/// 密码应包含非字母和数字的特殊字符
/// </summary>
public override IdentityError PasswordRequiresNonAlphanumeric() {
return new IdentityError {
Code = nameof(PasswordRequiresNonAlphanumeric),
Description = SecurityResource.PasswordRequiresNonAlphanumeric
};
}
/// <summary>
/// 密码应包含大写字母
/// </summary>
public override IdentityError PasswordRequiresUpper() {
return new IdentityError {
Code = nameof(PasswordRequiresUpper),
Description = SecurityResource.PasswordRequiresUpper
};
}
/// <summary>
/// 密码应包含数字
/// </summary>
public override IdentityError PasswordRequiresDigit() {
return new IdentityError {
Code = nameof(PasswordRequiresDigit),
Description = SecurityResource.PasswordRequiresDigit
};
}
/// <summary>
/// 密码应包含不重复的字符数
/// </summary>
public override IdentityError PasswordRequiresUniqueChars(int uniqueChars) {
return new IdentityError {
Code = nameof(PasswordRequiresUniqueChars),
Description = string.Format(SecurityResource.PasswordRequiresUniqueChars, uniqueChars)
};
}
/// <summary>
/// 无效用户名
/// </summary>
public override IdentityError InvalidUserName(string userName) {
return new IdentityError {
Code = nameof(InvalidUserName),
Description = string.Format(SecurityResource.InvalidUserName, userName)
};
}
/// <summary>
/// 用户名重复
/// </summary>
public override IdentityError DuplicateUserName(string userName) {
return new IdentityError {
Code = nameof(DuplicateUserName),
Description = string.Format(SecurityResource.DuplicateUserName, userName)
};
}
/// <summary>
/// 电子邮件重复
/// </summary>
public override IdentityError DuplicateEmail(string email) {
return new IdentityError {
Code = nameof(DuplicateEmail),
Description = string.Format(SecurityResource.DuplicateEmail, email)
};
}
/// <summary>
/// 无效令牌
/// </summary>
public override IdentityError InvalidToken() {
return new IdentityError {
Code = nameof(InvalidToken),
Description = SecurityResource.InvalidToken
};
}
/// <summary>
/// 密码错误
/// </summary>
public override IdentityError PasswordMismatch() {
return new IdentityError {
Code = nameof(PasswordMismatch),
Description = SecurityResource.PasswordMismatch
};
}
/// <summary>
/// 角色名无效
/// </summary>
public override IdentityError InvalidRoleName(string role) {
return new IdentityError {
Code = nameof(InvalidRoleName),
Description = string.Format(SecurityResource.InvalidRoleName, role)
};
}
/// <summary>
/// 角色名重复
/// </summary>
public override IdentityError DuplicateRoleName(string role) {
return new IdentityError {
Code = nameof(DuplicateRoleName),
Description = string.Format(SecurityResource.DuplicateRoleName, role)
};
}
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace AdoExam
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public static bool admin=false;
public static string conStr = @"Data Source=localhost; Initial Catalog=AdoExam; Integrated Security=true; Pooling=true";
public static string userName;
}
}
|
// Copyright 2011-2013 Anodyne.
//
// 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 Kostassoid.Anodyne.Common.Reflection
{
using System;
public static class TypeEx
{
public static bool IsSubclassOfRawGeneric(this Type type, Type generic)
{
while (type != null & type != typeof(object))
{
var intermediate = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
if (generic == intermediate)
{
return true;
}
type = type.BaseType;
}
return false;
}
public static bool IsRawGeneric(this Type type, Type generic)
{
if (type == null || generic == null) return false;
return type.IsGenericType && type.GetGenericTypeDefinition() == generic;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace _07.SequenceOfFibonacci
{
class SequenceOfFibonacci
{
static void Main()
{
Console.WriteLine("Enter how many numbers of the Sequence Of Fibonacci you want to see:");
int userInput = int.Parse(Console.ReadLine());
BigInteger firstMem = 0;
BigInteger secondMem = 1;
BigInteger thirdMem = 0;
for (int index = 1; index <= userInput; index++)
{
Console.WriteLine("{0}: {1}", index, thirdMem);
firstMem = secondMem;
secondMem = thirdMem;
thirdMem = firstMem + secondMem;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZY.OA.Model.Enum
{
public enum DelFlagEnum
{
/// <summary>
/// 正常未删除状态
/// </summary>
Normal=0,
/// <summary>
/// 已删除状态
/// </summary>
deleted=1
}
}
|
namespace PizzaMore.BindingModels
{
public abstract class BindingUserModel
{
public string Email { get; set; }
public string Password { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace HomeWork_7
{
class Repository
{
/// <summary>
/// Массив для хранения данных о записях
/// </summary>
private Field[] fields;
/// <summary>
/// Путь к файлу
/// </summary>
private string path;
/// <summary>
/// Переменная, аоказывающая количество записей
/// </summary>
int index;
/// <summary>
/// Массив для заголовок
/// </summary>
string[] titles;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="Path"></param>
public Repository(string Path)
{
this.path = Path;
this.index = 0;
this.titles = new string[5];
this.fields = new Field[2];
}
/// <summary>
/// Метод для расширения массива
/// </summary>
/// <param name="Flag"></param>
private void Resize(bool Flag)
{
if (Flag)
{
Array.Resize(ref this.fields, this.fields.Length * 2);
}
}
/// <summary>
/// Метод, для добавления записей в массив
/// </summary>
/// <param name="field">Запись</param>
public void Add(Field field)
{
this.Resize(index >= this.fields.Length);
this.fields[index] = field;
this.index++;
}
/// <summary>
/// Поиск индекса записи по полю
/// </summary>
/// <param name="label"></param>
public bool Remove(string label)
{
bool flag = false;
for (int i = 0; i < this.index; i++)
{
if (this.fields[i].FirstName.Trim() == label)
{
RemByIndex(i--);
flag = true;
}
else if (this.fields[i].LastName.Trim() == label)
{
RemByIndex(i--);
flag = true;
}
else if (this.fields[i].Record.Trim() == label)
{
RemByIndex(i--);
flag = true;
}
else if (int.TryParse(label, out int result) && this.fields[i].Age == result)
{
RemByIndex(i--);
flag = true;
}
}
return flag;
}
/// <summary>
/// Удаления записи
/// </summary>
/// <param name="RemoveIndex">Индекс записи для удаления</param>
public void RemByIndex(int RemoveIndex)
{
Field[] newfields = new Field[this.fields.Length - 1];
index--;
for (int i = 0; i < RemoveIndex; i++)
{
newfields[i] = this.fields[i];
}
for (int i = RemoveIndex; i < index; i++)
{
newfields[i] = this.fields[i + 1];
}
this.fields = newfields;
}
/// <summary>
/// Редактирвоание
/// </summary>
/// <param name="label">Значение, по которому надо редактировать запись</param>
public bool Edit(string label, Field field)
{
bool flag = false;
for (int i = 0; i < this.index; i++)
{
if (this.fields[i].FirstName.Trim() == label)
{
this.fields[i--] = field;
flag = true;
}
else if (this.fields[i].LastName.Trim() == label)
{
this.fields[i--] = field;
flag = true;
}
else if (this.fields[i].Record.Trim() == label)
{
this.fields[i--] = field;
flag = true;
}
else if (int.TryParse(label, out int result) && this.fields[i].Age == result)
{
this.fields[i--] = field;
flag = true;
}
}
return flag;
}
public void Sort(string select)
{
Field temp;
bool flag = true;
switch (select)
{
case "1":
while (flag)
{
flag = false;
for (int i = 0; i < this.index - 1; ++i)
if (this.fields[i].FirstName.CompareTo(this.fields[i + 1].FirstName) > 0)
{
temp = this.fields[i];
this.fields[i] = this.fields[i + 1];
this.fields[i + 1] = temp;
flag = true;
}
}
break;
case "2":
while (flag)
{
flag = false;
for (int i = 0; i < this.index - 1; ++i)
if (this.fields[i].LastName.CompareTo(this.fields[i + 1].LastName) > 0)
{
temp = this.fields[i];
this.fields[i] = this.fields[i + 1];
this.fields[i + 1] = temp;
flag = true;
}
}
break;
case "3":
for (int i = 0; i < this.index - 1; i++)
{
for (int j = i + 1; j < this.index; j++)
{
if (this.fields[i].Age > this.fields[j].Age)
{
temp = this.fields[i];
this.fields[i] = this.fields[j];
this.fields[j] = temp;
}
};
}
break;
default:
Console.WriteLine("Такой команды нет...");
break;
}
}
/// <summary>
/// Вывод по диапозону дат
/// </summary>
/// <param name="a">1я дата</param>
/// <param name="b">2я дата</param>
public void PrintSort(DateTime a,DateTime b)
{
for (int i = 0; i < this.index; i++)
{
if (this.fields[i].Date >= a && this.fields[i].Date<=b)
{
Console.WriteLine(fields[i].Print());
}
}
}
/// <summary>
/// Печать в консоль
/// </summary>
public void PrintToConsole()
{
Console.WriteLine($"{this.titles[0],10}|{this.titles[1],10}|{this.titles[2],8}|{this.titles[3],8}|{this.titles[4],17}");
for (int i = 0; i < index; i++)
{
Console.WriteLine(this.fields[i].Print());
}
}
/// <summary>
/// Загрузка из файла
/// </summary>
public void Load()
{
using(StreamReader sr = new StreamReader(this.path))
{
titles = sr.ReadLine().Split('|');
while (!sr.EndOfStream)
{
string[] args = sr.ReadLine().Split('|');
Add(new Field(args[0], args[1], int.Parse(args[2]), args[3]));
}
}
}
/// <summary>
/// Загрузка в файл
/// </summary>
public void UnLoad()
{
using (StreamWriter sw = new StreamWriter(this.path))
{
sw.WriteLine($"{this.titles[0],10}|{this.titles[1],10}|{this.titles[2],8}|{this.titles[3],8}|{this.titles[4],17}");
for (int i = 0; i < this.index; i++)
{
sw.WriteLine(this.fields[i].Print());
}
}
}
}
}
|
//*************************************************************************
//@header EventTypeSet
//@abstract Set EventType.
//@discussion New EventType with number and name.Number must be different.
//@version v1.0.0
//@author Felix Zhang
//@copyright Copyright (c) 2017 FFTAI Co.,Ltd.All rights reserved.
//**************************************************************************
namespace FZ.HiddenObjectGame
{
public static class EventTypeSet
{
public static EventType NextMusic = new EventType(0, "NextMusic");
public static EventType GameStart = new EventType(10, "GameStart");
public static EventType TargetCreated = new EventType(11, "TargetCreated");
//public static EventType GameOver = new EventType(12, "GameOver");
public static EventType FinishGame = new EventType(13, "FinishGame");
//public static EventType NextFlow = new EventType(14, "NextFlow");
}
}
|
using System.Threading.Tasks;
using CryptoLab.Domain.Domain;
using CryptoLab.Infrastructure.Commands;
using CryptoLab.Infrastructure.Commands.Transaction;
using CryptoLab.Infrastructure.CryptoCompareApi;
using CryptoLab.Infrastructure.IServices;
namespace CryptoLab.Infrastructure.Handlers.Transaction
{
public class FastSellHandler : ICommandHandler<FastSell>
{
private readonly ITransactionService _transactionService;
private readonly IHistoryService _historyService;
public FastSellHandler(ITransactionService transactionService, IHistoryService historyService)
{
_transactionService = transactionService;
_historyService = historyService;
}
public async Task HandlerAsync(FastSell command)
{
await _transactionService.FastSellTransactionAsync(command.FromCurrency, command.Amount, command.UserId);
var price = await CryptoCompare.GetCryptoPriceInUsd(command.FromCurrency);
await _historyService.AddAsync(OperationType.Sell, command.FromCurrency, command.Amount, price, command.UserId);
}
}
} |
using HPYL.BLL;
using HPYL.Model;
using HPYL_API.App_Start.Attribute;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using XL.Application.Code;
using XL.Model.Message;
namespace HPYL_API.Controllers.DoctorAdvice
{
/// <summary>
/// 医嘱计划
/// </summary>
[TokenAttribute] //针对当前类验证签名
public class DoctorAdviceController : ApiController
{
private DoctorAdviceBLL FBLL = new DoctorAdviceBLL();
#region 获取数据
/// <summary>
/// 获取诊疗项目医嘱内容模板列表
/// </summary>
/// <param name="HFT_ID">诊疗项目Id</param>
/// <returns></returns>
[HttpGet]
public CallBackResult GetAdviceArticleList(long HFT_ID)
{
CallBackResult apiResult = new CallBackResult();
try
{
var data = FBLL.GetAdviceArticleList(HFT_ID);
apiResult.Data = data;
apiResult.Result = 1;
apiResult.Message = "加载成功";
}
catch (Exception ex)
{
apiResult.Result = 0;
apiResult.Message = "加载失败";
new CCBException("获取诊疗项目医嘱计划模板:", ex);
}
return apiResult;
}
/// <summary>
/// 获取单条医嘱内容及计划
/// </summary>
/// <param name="HAA_ID">文章ID(内容模板列表返回)</param>
/// <returns></returns>
[HttpGet]
public CallBackResult GetDoctorFollowContent(long HAA_ID)
{
CallBackResult apiResult = new CallBackResult();
try
{
var data = FBLL.GetModel(HAA_ID);
var JsonData = new
{
ArticleInfo = data,
FollowList = FBLL.FollowList(HAA_ID)
};
apiResult.Data = JsonData;
apiResult.Result = 1;
apiResult.Message = "加载成功";
}
catch (Exception ex)
{
apiResult.Result = 0;
apiResult.Message = "加载失败";
new CCBException("获取单条医嘱内容及计划:", ex);
}
return apiResult;
}
#endregion
#region 提交数据
/// <summary>
/// 新增医嘱随访计划(如果发送医嘱选择关联随访计划请调用此接口写入)
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
[HttpPost]
[ValidateModel]
public CallBackResult InFollowPlan(BaseDoctorFollowPlan info)
{
CallBackResult apiResult = new CallBackResult();
try
{
if (FBLL.InFollowPlan(info))
{
apiResult.Result = 1;
apiResult.Message = "已成功添加随访计划";
}
else
{
apiResult.Result = 0;
apiResult.Message = "新增随访计划失败";
}
}
catch (Exception ex)
{
apiResult.Result = 0;
apiResult.Message = "新增随访计划失败";
new CCBException(" 新增随访计划", ex);
}
return apiResult;
}
#endregion
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class WindowsManager : MonoBehaviour
{
private List<BaseWindow> windows;
public static Action<string> OnWindowOpened = delegate { };
public static Action<string> OnWindowClosed = delegate { };
private static WindowsManager _instance;
public static WindowsManager Instance { get { return _instance; } }
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
}
else
{
_instance = this;
}
}
private void Start()
{
StartCoroutine(LoadWindows());
}
IEnumerator LoadWindows()
{
windows = new List<BaseWindow>();
foreach (var window in GetComponentsInChildren<BaseWindow>())
{
windows.Add(window);
}
while (windows.Any(x => !x.isBound))
{
yield return null;
}
OpenWindow("MainMenu");
}
public void OpenWindow(string windowName)
{
foreach (var window in windows)
CloseWindow(window.currentWindowName);
OnWindowOpened(windowName);
}
public void CloseWindow(string windowName)
{
OnWindowClosed(windowName);
}
}
|
using System;
using System.Diagnostics.CodeAnalysis;
using Atc.CodeAnalysis.CSharp.SyntaxFactories;
// ReSharper disable once CheckNamespace
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public static class MethodDeclarationSyntaxExtensions
{
public static MethodDeclarationSyntax AddSuppressMessageAttribute(this MethodDeclarationSyntax methodDeclaration, SuppressMessageAttribute suppressMessage)
{
if (methodDeclaration == null)
{
throw new ArgumentNullException(nameof(methodDeclaration));
}
if (suppressMessage == null)
{
throw new ArgumentNullException(nameof(suppressMessage));
}
if (string.IsNullOrEmpty(suppressMessage.Justification))
{
throw new ArgumentPropertyNullException(nameof(suppressMessage), "Justification is invalid.");
}
var attributeArgumentList = SyntaxFactory.AttributeArgumentList(
SyntaxFactory.SeparatedList<AttributeArgumentSyntax>(SyntaxFactory.NodeOrTokenList(
SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(suppressMessage.Category)),
SyntaxTokenFactory.Comma(),
SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(suppressMessage.CheckId)),
SyntaxTokenFactory.Comma(),
SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(suppressMessage.Justification!))
.WithNameEquals(
SyntaxNameEqualsFactory.Create(nameof(SuppressMessageAttribute.Justification))
.WithEqualsToken(SyntaxTokenFactory.Equals())))));
return methodDeclaration
.AddAttributeLists(SyntaxAttributeListFactory.Create(nameof(SuppressMessageAttribute), attributeArgumentList));
}
}
} |
using Expenses.MVCIoC.simpleinjector;
using System.Web.Mvc;
using System.Web.Routing;
using Expenses.Services;
using System.Data.Entity;
using Expenses.Data;
namespace Expenses
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
//Ioc S I M P L E I N J E C T O R
Injector.Initialise(); //if you want to user Unity,coment this line and discoment the lines below
//If you want to use Unity discoment this line .Initialize IoC container/Unity
// Bootstrapper.Initialise();
//Register our custom controller factory
// ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.DataModel;
using Client_WPF.View;
using System.Windows.Input;
using Client_WPF.Utils;
using System.Windows;
using System.ComponentModel;
using Common.Utils;
namespace Client_WPF.ViewModel
{
class MenuViewModel : BindableObject
{
#region Properties
private string search;
public string Search
{
get { return search; }
set
{
search = value;
RaisePropertyChange("Search");
SearchDataModel.Instance.Search = search;
}
}
public ICommand CloseCommand { get; private set; }
public ICommand Logout { get; private set; }
public ICommand ShowConnectionDialog { get; private set; }
public ICommand OpenAdmin { get; private set; }
public LoginModal ConnectionModal { get; private set; }
public ErrorViewModel ErrorModel { get; private set; }
private bool isAdmin;
public bool IsAdmin
{
get { return isAdmin; }
set { isAdmin = value; RaisePropertyChange("IsAdmin"); }
}
private PropertyChangedEventHandler PropertyChangedHandler { get; set; }
#endregion
#region CTor
public MenuViewModel()
{
CloseCommand = new RelayCommand((param) => Application.Current.Shutdown());
ShowConnectionDialog = new RelayCommand((param) =>
{
ShowConnectionModel_IFN();
});
Logout = new RelayCommand((param) => UserDataModel.Instance.Logout());
PropertyChangedHandler = new System.ComponentModel.PropertyChangedEventHandler(UserData_PropertyChanged);
OpenAdmin = new RelayCommand((param) =>
{
new AdminWindow().Show();
});
UserDataModel.Instance.PropertyChanged += PropertyChangedHandler;
search = SearchDataModel.Instance.Search;
IsAdmin = UserDataModel.Instance.IsConnected;
IsAdmin = false;
ErrorModel = new ErrorViewModel();
}
~MenuViewModel()
{
UserDataModel.Instance.PropertyChanged -= PropertyChangedHandler;
}
void UserData_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsConnected")
{
if (!(sender as UserDataModel).IsConnected)
{
if (ConnectionModal == null)
{
ConnectionModal = new LoginModal();
ConnectionModal.ShowDialog();
ConnectionModal = null;
}
FeedManagerDataModel.Instance.GetAllRootFeeds();
IsAdmin = false;
}
else
{
if (ConnectionModal != null)
ConnectionModal.Close();
ConnectionModal = null;
if (UserDataModel.Instance.User != null)
IsAdmin = UserDataModel.Instance.User.IsSuperUser;
}
}
IsAdmin = true;
}
#endregion
#region private methods
void ShowConnectionModel_IFN()
{
if (!UserDataModel.Instance.IsConnected)
{
if (ConnectionModal == null)
{
ConnectionModal = new LoginModal();
ConnectionModal.ShowDialog();
ConnectionModal = null;
}
}
}
#endregion
}
}
|
using SimpleLogin.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleLogin.Infra.Data.Context
{
public class SimpleLoginContext : DbContext
{
// public SimpleLoginContext()
// : base(@"Data Source=.;Initial Catalog=SimpleLoginContext;Integrated Security=True;MultipleActiveResultSets=True")
//{
// Debug.Write(Database.Connection.ConnectionString);
//}
public SimpleLoginContext( )
: base(@"Server=.;Database=SimpleLoginContext;Integrated Security=True; Trusted_Connection=True;MultipleActiveResultSets=true")
{
}
DbSet<UserProfile> UserProfiles { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.