text stringlengths 13 6.01M |
|---|
using UnityEngine;
using System.Collections;
using System;
/**
* Classe Général qui convertit les stats globals d'un personnage en stats interne.
*
* Auteur : Nicolas Rauflet rauflet.nicolas@outlook.fr
*/
public class Player
{
private int life;
private int mana;
private double sortPower;
private double armor;
private double attackPoint;
private double resistance;
private double attackSpeed;
private double criticalChance;
private double manaRegeneration;
public Player(int endurance, int strength, int intelligence,
int agility, int ability, int mind, int playerAttributesPoints)
{
this.life = 20 + endurance * 2;
this.mana = 100;
this.attackPoint = 2.5 + strength / 2;
this.armor = 5 + strength;
this.sortPower = 5 + intelligence;
this.resistance = 5 + intelligence;
this.attackSpeed = 85 * (agility * 0.02 + 1);
this.criticalChance = ability * 0.01;
this.manaRegeneration = 100 * (mind * 0.02 + 1);
}
public int Life
{
get{ return this.life; }
set{ this.life = value; }
}
public int Mana
{
get{ return this.mana; }
set{ this.mana = value; }
}
public double SortPower
{
get{ return this.sortPower; }
set{ this.sortPower = value; }
}
public double Armor
{
get{ return this.armor; }
set{ this.armor = value; }
}
public double AttackPoint
{
get{ return this.attackPoint; }
set{ this.attackPoint = value; }
}
public double Resistance
{
get{ return this.resistance; }
set{ this.resistance = value; }
}
public double AttackSpeed
{
get{ return this.attackSpeed; }
set{ this.attackSpeed = value; }
}
public double CriticalChance
{
get{ return this.criticalChance; }
set{ this.criticalChance = value; }
}
public double ManaRegeneration
{
get{ return this.manaRegeneration; }
set{ this.manaRegeneration = value; }
}
public override String ToString()
{
return String.Format("Nombre de Points de vie : {0} \n Nombre de points de mana : {1} \n"
+ "Nombre de points d'attaque : {2} \n Nombre de points d'amure : {3} \n"
+ "Nombre de puissance magique : {4} \n Nombre de points de resistance : {5} \n"
+ "Vitesse d'attaque : {6} \n Chance de coups critique : {7} Regeneration de mana : {8} \n",
this.Life,
this.Mana,
this.AttackPoint,
this.Armor,
this.SortPower,
this.Resistance,
this.AttackSpeed,
this.CriticalChance,
this.ManaRegeneration);
}
public int manaRegenation()
{
}
}
public enum PlayerState
{
NORMAL,
FIGHT,
DEAD
} |
using LibraryCoder.Numerics;
using System;
using Windows.UI.Xaml.Controls;
namespace SampleUWP.ConsoleCodeSamples
{
internal partial class Samples
{
/// <summary>
/// If you pass the Double.TryParse method a string that is created by calling the Double.ToString method, the original
/// Double value is returned. However, because of a loss of precision, the values may not be equal. In addition,
/// attempting to parse the string representation of either MinValue or MaxValue throws an OverflowException, as the
/// following example illustrates. Use round-trip specifier "R" to avoid that situation.
/// Code from this link: https://msdn.microsoft.com/en-us/library/3s27fasw(v=vs.110).aspx
/// </summary>
/// <param name="outputBlock"></param>
internal static void Sample03_TryParse_Methods(TextBlock outputBlock)
{
outputBlock.Text = "\nSample03_TryParse_Methods:\n";
string minValue;
string maxValue;
string minValuePlusEpsilon;
string maxValueMinusEpsilon;
/*
* Double.Epsilon is sometimes used as an absolute measure of the distance between two Double values when testing for equality.
* However, Double.Epsilon measures the smallest possible value that can be added to, or subtracted from, a Double whose value
* is zero. For most positive and negative Double values, the value of Double.Epsilon is too small to be detected. Therefore,
* except for values that are zero, we do not recommend its use in tests for equality.
*/
double epsilon = double.Epsilon; // https://msdn.microsoft.com/en-us/library/system.double.epsilon(v=vs.110).aspx
double minNumber;
double maxNumber;
double minNumberPlusEpsilon;
double maxNumberMinusEpsilon;
minNumber = double.MinValue;
maxNumber = double.MaxValue;
minNumberPlusEpsilon = minNumber + epsilon;
maxNumberMinusEpsilon = maxNumber - epsilon;
// The Round-trip ("R") Format Specifier: https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
minValue = minNumber.ToString("r");
maxValue = maxNumber.ToString("r");
minValuePlusEpsilon = minNumberPlusEpsilon.ToString("r");
maxValueMinusEpsilon = maxNumberMinusEpsilon.ToString("r");
outputBlock.Text += string.Format("\nepsilon = {0} for doubles.\n", epsilon);
outputBlock.Text += string.Format("\nNone of the following strings would have converted back into doubles \nif the Round-trip (\"R\") Format Specifier had not been used.\n");
if (double.TryParse(minValue, out _))
outputBlock.Text += string.Format("\nminValue = {0} IS valid double.", minValue);
else
outputBlock.Text += string.Format("\nminValue = {0} IS NOT valid double.", minValue);
if (double.TryParse(maxValue, out _))
outputBlock.Text += string.Format("\nmaxValue = {0} IS valid double.", maxValue);
else
outputBlock.Text += string.Format("\nmaxValue = {0} IS NOT valid double.", maxValue);
if (double.TryParse(minValuePlusEpsilon, out _))
outputBlock.Text += string.Format("\nminValuePlusEpsilon = {0} IS valid double.", minValuePlusEpsilon);
else
outputBlock.Text += string.Format("\nminValuePlusEpsilon = {0} IS NOT valid double.", minValuePlusEpsilon);
if (double.TryParse(maxValueMinusEpsilon, out _))
outputBlock.Text += string.Format("\nmaxValueMinusEpsilon = {0} IS valid double.", maxValueMinusEpsilon);
else
outputBlock.Text += string.Format("\nmaxValueMinusEpsilon = {0} IS NOT valid double.", maxValueMinusEpsilon);
//
// Following example from: https://msdn.microsoft.com/en-us/library/system.double(v=vs.110).aspx
//
double value1 = 100.10142;
value1 = Math.Sqrt(Math.Pow(value1, 2));
double value2 = Math.Pow(value1 * 3.51, 2);
value2 = Math.Sqrt(value2) / 3.51;
outputBlock.Text += string.Format("\n\n{0} = {1} is {2}", value1, value2, value1.Equals(value2)); // Returns True/False.
outputBlock.Text += string.Format("\n{0:R} = {1:R} is {2}", value1, value2, value1.Equals(value2));
outputBlock.Text += string.Format("\n{0:R} - {1:R} = {2}\n", value1, value2, value1 - value2);
//
// Following example from: https://msdn.microsoft.com/en-us/library/system.double(v=vs.110).aspx
//
double one1 = 0.1 * 10;
double one2 = 0;
for (int ctr = 1; ctr <= 10; ctr++)
one2 += .1;
outputBlock.Text += string.Format("\n\n{0:R} = {1:R} is {2}", one1, one2, one1.Equals(one2));
outputBlock.Text += string.Format("\n{0:R} is approximately equal to {1:R} is {2}\n", one1, one2, LibNum.EqualWithinDifference(one1, one2, .000000001)); ;
//
// Following example from: https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx#Midpoint
//
float value = 16.325f;
outputBlock.Text += string.Format("\n\nWidening Conversion of {0:R} (type {1}) to {2:R} (type {3}): ", value, value.GetType().Name, (double)value, ((double)(value)).GetType().Name);
outputBlock.Text += string.Format("\n" + (Math.Round(value, 2)));
outputBlock.Text += string.Format("\n" + Math.Round(value, 2, MidpointRounding.AwayFromZero));
decimal decValue = (decimal)value;
outputBlock.Text += string.Format("\nCast of {0:R} (type {1}) to {2} (type {3}): ", value, value.GetType().Name, decValue, decValue.GetType().Name);
outputBlock.Text += string.Format("\n" + (Math.Round(decValue, 2)));
outputBlock.Text += string.Format("\n" + (Math.Round(decValue, 2, MidpointRounding.AwayFromZero)) + "\n");
//
//
float v1 = 16.325f;
float v2 = 16.3254f;
// Note: Casting float to double does not result in new number with just more zeros as expected! Must cast float to decimal to get that result.
double v1Double = (double)v1;
double v2Double = (double)v2;
decimal v1Decimal = (decimal)v1;
decimal v2Decimal = (decimal)v2;
outputBlock.Text += string.Format("\n\nInitial float values: v1=[" + v1 + "], v2=[" + v2 + "]");
outputBlock.Text += string.Format("\nCheck casting of floats! v1Double=[" + v1Double + "], v2Double=[" + v2Double + "]\nv1Decimal=[" + v1Decimal + "], v2Decimal=[" + v2Decimal + "]");
bool EqualCheck = LibNum.EqualByRounding(v1, v2, 3);
outputBlock.Text += string.Format("\nComparision to 3 digits: EqualCheck=" + EqualCheck + "\n");
}
}
}
|
using Newtonsoft.Json;
using System.IO;
using System.Threading.Tasks;
namespace SerializationDemo
{
public class JsonFormatter : IFormatter
{
public JsonSerializer Serializer { get; } = new JsonSerializer()
{
Formatting = Formatting.Indented
};
public Task<T> ReadAsync<T>(Stream stream)
{
using (var txtReader = new StreamReader(stream))
{
using (var jsonReader = new JsonTextReader(txtReader))
{
var value = Serializer.Deserialize<T>(jsonReader);
return Task.FromResult(value);
}
}
}
public Task WriteAsync<T>(T obj, Stream stream)
{
using (var txtWriter = new StreamWriter(stream))
{
using (var jsonWriter= new JsonTextWriter(txtWriter))
{
Serializer.Serialize(jsonWriter, obj, typeof(T));
return Task.CompletedTask;
}
}
}
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using DistributedCollections.Redis;
using FluentAssertions;
using NUnit.Framework;
using StackExchange.Redis;
namespace DistributedCollections.Tests
{
[TestFixture]
public class DictTests : DictTestBase
{
private IBackplane backplane;
private DistributedDictionary<string, string> dict1;
private DistributedDictionary<string, string> dict2;
private string key;
private string value;
[SetUp]
public void SetUp()
{
backplane = new RedisBackplane(DateTime.Now.Ticks.ToString(), Connection);
dict1 = new DistributedDictionary<string, string>(backplane);
dict2 = new DistributedDictionary<string, string>(backplane);
key = "testK";
value = "testV";
}
[Test]
public void AddTest()
{
dict1.Add(key, value);
dict1[key].Should().Be(value);
dict2[key].Should().Be(value);
}
[Test]
public void AddTwoTest()
{
dict1.Add("21", "32");
dict2.Count.Should().Be(1);
dict1.Add("22", "22");
dict2.Count.Should().Be(2);
}
[Test]
public void RemoveTest()
{
dict2.Add(key, value);
dict1.Remove(key);
dict1.Count.Should().Be(0);
dict2.Count.Should().Be(0);
}
[Test]
public void ClearTest()
{
dict1.Add(key, value);
dict2.Clear();
dict1.Count.Should().Be(0);
}
[Test]
public void StressTest_set()
{
var tasks = Enumerable.Range(0, 10).Select(t => Task.Run(() =>
{
for (var i = 0; i < 15; i++)
{
var id = Guid.NewGuid();
var intKey = id.GetHashCode() % 15;
dict1.Set(intKey.ToString(), id.ToString());
}
}));
Task.WaitAll(tasks.ToArray());
foreach (var pair in dict2)
{
dict1[pair.Key].Should().Be(pair.Value);
}
}
[Test]
public void StressTest_Add()
{
var tasks = Enumerable.Range(0, 10).Select(t => Task.Run(() =>
{
for (var i = 0; i < 15; i++)
{
var id = Guid.NewGuid();
var intKey = id.GetHashCode() % 15;
var dict = intKey % 2 == 0 ? dict1 : dict2;
dict.TryAdd(intKey.ToString(), id.ToString());
}
}));
Task.WaitAll(tasks.ToArray());
foreach (var pair in dict2)
{
dict1[pair.Key].Should().Be(pair.Value);
}
}
}
} |
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities.Core;
using System;
using System.Linq;
using System.Linq.Expressions;
namespace Alabo.Datas.Stores.Exist.EfCore {
public abstract class ExistsEfCoreStore<TEntity, TKey> : ExistsAsyncEfCoreStore<TEntity, TKey>,
IExistsStore<TEntity, TKey>
where TEntity : class, IKey<TKey>, IVersion, IEntity {
protected ExistsEfCoreStore(IUnitOfWork unitOfWork) : base(unitOfWork) {
}
/// <summary>
/// 判断是否存在
/// </summary>
/// <param name="predicate">条件</param>
public bool Exists(Expression<Func<TEntity, bool>> predicate) {
if (predicate == null) {
return false;
}
return Set.Any(predicate);
}
public bool Exists() {
return Set.Any();
}
}
} |
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YoloCampersTwoPointO.Lib;
namespace YoloCampersTwoPointO.Web.Data
{
public class YoloContext : DbContext
{
public YoloContext(DbContextOptions<YoloContext> options) : base(options)
{
}
public DbSet<Camper> Campers { get; set; }
public DbSet<Boeking> Boekingen { get; set; }
public DbSet<ReservatieDatum> ReservatieData { get; set; }
public DbSet<Afbeelding> YoloAfbeeldingen { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bb.Wordings
{
/// <summary>
/// word in the referential
/// </summary>
[System.Diagnostics.DebuggerDisplay("{Text} - {Multiplicity} - {Kind} - {TypeString}")]
public class WordItem
{
/// <summary>
/// Gets or sets the text.
/// </summary>
/// <value>
/// The text.
/// </value>
public string Text { get; set; }
/// <summary>
/// Gets or sets the types of the words (name, verb, ...).
/// </summary>
/// <value>
/// The types.
/// </value>
public IEnumerable<WordType> Types { get; set; }
/// <summary>
/// Gets or sets the multiplicity (singular, plurial).
/// </summary>
/// <value>
/// The multiplicity.
/// </value>
public MultiplicityEnum Multiplicity { get; set; }
/// <summary>
/// Gets or sets the kind (male, female).
/// </summary>
/// <value>
/// The kind.
/// </value>
public KindEnum Kind { get; set; }
/// <summary>
/// Gets the types sequence in string.
/// </summary>
/// <value>
/// The types to string.
/// </value>
public string TypeString
{
get
{
return string.Join(", ", this.Types.Select(c => c.Text));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DSInterfaces
{
//There doesn't seem to be a proper constraint for strictly numeric type values, so we'll try to get as close as possible
public interface IHeap<T> {
void Add(T value);
int GetSize();
bool IsEmpty();
T Poll();
T Peek();
}
}
|
using AppointmentManagement.Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AppointmentManagement.DataAccess.Abstract
{
public interface IPostedTypeDal
{
IQueryable<PostedType> GetPostedTypes();
}
}
|
using System;
using R5T.Cambridge.Types;
namespace R5T.Solgene.VS2017
{
public class VisualStudioSolutionFileGenerator : IVisualStudioSolutionFileGenerator
{
private IVisualStudio2017SolutionFileGenerator VisualStudio2017SolutionFileGenerator { get; }
public VisualStudioSolutionFileGenerator(IVisualStudio2017SolutionFileGenerator visualStudio2017SolutionFileGenerator)
{
this.VisualStudio2017SolutionFileGenerator = visualStudio2017SolutionFileGenerator;
}
public SolutionFile GenerateVisualStudioSolutionFile()
{
var solutionFile = this.VisualStudio2017SolutionFileGenerator.GenerateVisualStudio2017SolutionFile();
return solutionFile;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace Schyntax.Internals
{
public abstract class Node
{
private readonly List<Token> _tokens = new List<Token>();
public IReadOnlyList<Token> Tokens => _tokens.AsReadOnly();
public int Index => Tokens[0].Index;
internal void AddToken(Token token)
{
_tokens.Add(token);
}
}
public class ProgramNode : Node
{
private readonly List<GroupNode> _groups = new List<GroupNode>();
private readonly List<ExpressionNode> _expressions = new List<ExpressionNode>();
public IReadOnlyList<GroupNode> Groups => _groups.AsReadOnly();
public IReadOnlyList<ExpressionNode> Expressions => _expressions.AsReadOnly();
public void AddGroup(GroupNode group)
{
_groups.Add(group);
}
public void AddExpression(ExpressionNode exp)
{
_expressions.Add(exp);
}
}
public class GroupNode : Node
{
private readonly List<ExpressionNode> _expressions = new List<ExpressionNode>();
public IReadOnlyList<ExpressionNode> Expressions => _expressions.AsReadOnly();
public void AddExpression(ExpressionNode exp)
{
_expressions.Add(exp);
}
}
public enum ExpressionType
{
IntervalValue, // used internally by the parser (not a real expression type)
Seconds,
Minutes,
Hours,
DaysOfWeek,
DaysOfMonth,
DaysOfYear,
Dates,
}
public class ExpressionNode : Node
{
private readonly List<ArgumentNode> _arguments = new List<ArgumentNode>();
public ExpressionType ExpressionType { get; }
public IReadOnlyList<ArgumentNode> Arguments => _arguments.AsReadOnly();
internal ExpressionNode(ExpressionType type)
{
ExpressionType = type;
}
internal void AddArgument(ArgumentNode arg)
{
_arguments.Add(arg);
}
}
public class ArgumentNode : Node
{
public bool IsExclusion { get; internal set; }
public bool HasInterval => Interval != null;
public IntegerValueNode Interval { get; internal set; }
public int IntervalValue => Interval.Value;
public bool IsWildcard { get; internal set; }
public bool IsRange => Range?.End != null;
public RangeNode Range { get; internal set; }
public ValueNode Value => Range?.Start;
public int IntervalTokenIndex => Tokens.First(t => t.Type == TokenType.Interval).Index;
}
public class RangeNode : Node
{
public ValueNode Start { get; internal set; }
public ValueNode End { get; internal set; }
public bool IsHalfOpen { get; internal set; }
}
public abstract class ValueNode : Node
{
}
public class IntegerValueNode : ValueNode
{
public int Value { get; internal set; }
}
public class DateValueNode : ValueNode
{
public int? Year { get; internal set; }
public int Month { get; internal set; }
public int Day { get; internal set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SunBehaviour : MonoBehaviour
{
private float initialRotation;
public float rotationSpeed;
// Start is called before the first frame update
void Start()
{
float initialRotation = Random.Range(0.0f, 360.0f);
transform.eulerAngles = new Vector3(0.0f, initialRotation, 0.0f);
}
// Update is called once per frame
void Update()
{
transform.Rotate(transform.up * rotationSpeed * Time.deltaTime);
}
}
|
using Grpc.Core;
using GrpcServer.Protos;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using GrpcServer.Models;
namespace GrpcServer.Services
{
public class ChattingService : chat.chatBase
{
public IConfiguration Configuration { get; }
public ChattingService(IConfiguration configuration)
{
Configuration = configuration;
}
public override async Task Chatting(IAsyncStreamReader<clientMessage> requestStream, IServerStreamWriter<serverMessage> responseStream, ServerCallContext context)
{
try
{
while (await requestStream.MoveNext())
{
if (!string.IsNullOrEmpty(requestStream.Current.Message))
{
if (string.Equals(requestStream.Current.Message, "stop", StringComparison.OrdinalIgnoreCase))
{
break;
}
Console.WriteLine(requestStream.Current);
await Task.Delay(1000);
await responseStream.WriteAsync(new serverMessage { Message = "Got it!" });
}
}
}
catch (IOException)
{
}
}
}
}
|
using System.Threading.Tasks;
using ApiTemplate.Common.Markers.DependencyRegistrar;
using ApiTemplate.Core.Entities.Users;
using ApiTemplate.Service.Users;
using Microsoft.AspNetCore.Http;
namespace ApiTemplate.Factory.WorkContexts
{
public class WorkContext : IWorkContext, IScopedDependency
{
#region Fields
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IUserService _userService;
#endregion
#region Constrcutors
public WorkContext(IHttpContextAccessor httpContextAccessor, IUserService userService)
{
_httpContextAccessor = httpContextAccessor;
_userService = userService;
}
#endregion
#region Methods
public AppUser CurrentUser
{
get
{
if (_httpContextAccessor.HttpContext?.User is null || !_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
{
return null;
}
return _userService.GetUserByHttpContextUser(_httpContextAccessor.HttpContext.User).GetAwaiter().GetResult();
}
}
#endregion
}
} |
using System;
class Program
{
static void Main(string[] args)
{
double a = double.Parse(Console.ReadLine());
double b = double.Parse(Console.ReadLine());
double c = double.Parse(Console.ReadLine());
double discriminant = Math.Pow(b, 2) - 4 * a * c;
if (discriminant == 0)
{
double x = (-b + Math.Sqrt(discriminant)) / (2 * a);
Console.WriteLine("{0:F2}", x);
}
else if (discriminant > 0)
{
double leftX = (-b + Math.Sqrt(discriminant)) / (2 * a);
double rightX = (-b - Math.Sqrt(discriminant)) / (2 * a);
double biggerX = Math.Max(leftX, rightX);
double smallerX = Math.Min(leftX, rightX);
Console.WriteLine("{0:F2}", smallerX);
Console.WriteLine("{0:F2}",biggerX);
}
else if (discriminant < 0)
{
Console.WriteLine("no real roots");
}
}
}
|
#region USINGS
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using GradConnect.Models;
using GradConnect.ViewModels;
using GradConnect.Data;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using DinkToPdf;
using DinkToPdf.Contracts;
#endregion
namespace GradConnect.Controllers
{
public class CvController : Controller
{
#region CONSTRUCTOR
private readonly IHostingEnvironment _hostingEnvironment;
private readonly ApplicationDbContext _context;
private readonly IConverter _converter;
private readonly IHttpContextAccessor _httpContextAccessor;
public CvController(ApplicationDbContext context, IConverter converter, IHttpContextAccessor httpContextAccessor, IHostingEnvironment hostingEnvironment)
{
_context = context;
_converter = converter;
_httpContextAccessor = httpContextAccessor;
_hostingEnvironment = hostingEnvironment;
}
#endregion
#region CRUD
public async Task<IActionResult> Index()
{
var user = GetUser();
var allCvs = await _context.CVs.Where(x => x.UserId == user.Id).ToListAsync();
return View(allCvs);
}
public IActionResult BlankEducation()
{
return PartialView("_EducationEditor", new Education());
}
public IActionResult BlankExperience()
{
return PartialView("_ExperienceEditor", new Experience());
}
public IActionResult BlankSkill()
{
return PartialView("_SkillsEditor", new Skill());
}
public IActionResult BlankReference()
{
return PartialView("_ReferencesEditor", new Reference());
}
public IActionResult Create()
{
return View();
}
[HttpPost]
[ActionName("Create")]
public async Task<IActionResult> CreateCv(CreateCvViewModel model)
{
var user = GetUser();
foreach (var edu in model.Educations)
{
edu.UserId = user.Id;
edu.User = user;
}
foreach (var exp in model.Experiences)
{
exp.UserId = user.Id;
exp.User = user;
}
var cv = new CV
{
CvName = model.CvName,
FirstName = model.FirstName,
LastName = model.LastName,
UserId = user.Id,
User = user,
Street = model.Street,
City = model.City,
Postcode = model.Postcode,
PhoneNumber = model.PhoneNumber,
Email = model.Email,
DateOfBirth = model.DateOfBirth,
PersonalStatement = model.PersonalStatement,
Experiences = model.Experiences,
Educations = model.Educations,
References = model.References,
Skills = model.Skills
};
user.CVs.Append(cv);
_context.Users.Update(user);
await _context.CVs.AddAsync(cv);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
[HttpGet]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var cv = await _context.CVs.FirstOrDefaultAsync(x => x.Id == id);
var experiences = await _context.Experiences.Where(x => x.CvId == id).ToListAsync();
var educations = await _context.Educations.Where(x => x.CvId == id).ToListAsync();
var references = await _context.References.Where(x => x.CvId == id).ToListAsync();
var skills = await _context.Skills.Where(x => x.CvId == id).ToListAsync();
var model = new UpdateCvViewModel();
model.CvName = cv.CvName;
model.FirstName = cv.FirstName;
model.LastName = cv.LastName;
model.Street = cv.Street;
model.City = cv.City;
model.Postcode = cv.Postcode;
model.PhoneNumber = cv.PhoneNumber;
model.Email = cv.Email;
model.DateOfBirth = cv.DateOfBirth;
model.PersonalStatement = cv.PersonalStatement;
model.Experiences = experiences;
model.Educations = educations;
model.References = references;
model.Skills = skills;
return View(model);
}
[HttpPost]
[ActionName("Edit")]
public async Task<IActionResult> Edit(int id, UpdateCvViewModel updateModel)
{
if (ModelState.IsValid)
{
var cv = await _context.CVs.FirstOrDefaultAsync(x => x.Id == id);
var experiences = await _context.Experiences.Where(x => x.CvId == id).ToListAsync();
var educations = await _context.Educations.Where(x => x.CvId == id).ToListAsync();
var references = await _context.References.Where(x => x.CvId == id).ToListAsync();
var skills = await _context.Skills.Where(x => x.CvId == id).ToListAsync();
cv.CvName = updateModel.CvName;
cv.FirstName = updateModel.FirstName;
cv.LastName = updateModel.LastName;
cv.Street = updateModel.Street;
cv.City = updateModel.City;
cv.Postcode = updateModel.Postcode;
cv.PhoneNumber = updateModel.PhoneNumber;
cv.Email = updateModel.Email;
cv.DateOfBirth = updateModel.DateOfBirth;
cv.PersonalStatement = updateModel.PersonalStatement;
cv.Experiences = updateModel.Experiences;
cv.Educations = updateModel.Educations;
cv.References = updateModel.References;
cv.Skills = updateModel.Skills;
_context.CVs.Update(cv);
await _context.SaveChangesAsync();
}
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var cv = await _context.CVs.FirstOrDefaultAsync(x => x.Id == id);
var experiences = await _context.Experiences.Where(x => x.CvId == id).ToListAsync();
var educations = await _context.Educations.Where(x => x.CvId == id).ToListAsync();
var references = await _context.References.Where(x => x.CvId == id).ToListAsync();
var skills = await _context.Skills.Where(x => x.CvId == id).ToListAsync();
var model = new UpdateCvViewModel();
model.CvName = cv.CvName;
model.FirstName = cv.FirstName;
model.LastName = cv.LastName;
model.Street = cv.Street;
model.City = cv.City;
model.Postcode = cv.Postcode;
model.PhoneNumber = cv.PhoneNumber;
model.Email = cv.Email;
model.DateOfBirth = cv.DateOfBirth;
model.PersonalStatement = cv.PersonalStatement;
model.Experiences = experiences;
model.Educations = educations;
model.References = references;
model.Skills = skills;
return View(model);
}
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var cv = await _context.CVs.FirstOrDefaultAsync(x => x.Id == id);
var experiences = await _context.Experiences.Where(x => x.CvId == id).ToListAsync();
var educations = await _context.Educations.Where(x => x.CvId == id).ToListAsync();
var references = await _context.References.Where(x => x.CvId == id).ToListAsync();
var skills = await _context.Skills.Where(x => x.CvId == id).ToListAsync();
var model = new UpdateCvViewModel();
model.CvName = cv.CvName;
model.FirstName = cv.FirstName;
model.LastName = cv.LastName;
model.Street = cv.Street;
model.City = cv.City;
model.Postcode = cv.Postcode;
model.PhoneNumber = cv.PhoneNumber;
model.Email = cv.Email;
model.DateOfBirth = cv.DateOfBirth;
model.PersonalStatement = cv.PersonalStatement;
model.Experiences = experiences;
model.Educations = educations;
model.References = references;
model.Skills = skills;
return View(model);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
//find fitness class in db using passed in id
var cv = await _context.CVs.FirstOrDefaultAsync(x => x.Id == id);
var experiences = await _context.Experiences.Where(x => x.CvId == id).ToListAsync();
var educations = await _context.Educations.Where(x => x.CvId == id).ToListAsync();
var references = await _context.References.Where(x => x.CvId == id).ToListAsync();
var skills = await _context.Skills.Where(x => x.CvId == id).ToListAsync();
cv.Experiences = experiences;
cv.Educations = educations;
cv.Skills = skills;
cv.References = references;
//if class in null
if (cv == null)
{
//display error
return NotFound();
}
else
{
//remove class from db
_context.CVs.Remove(cv);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
#endregion
#region PDF
public IActionResult GeneratePDF(int id)
{
var user = GetUser();
var converter = new SynchronizedConverter(new PdfTools());
var host = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";
//byte[] pdf = converter.Convert(doc);
var doc = new HtmlToPdfDocument()
{
GlobalSettings = {
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.A4,
Margins = new MarginSettings() { Top = 10 },
DocumentTitle = "cv"
//Out = @"C:\DinkToPdf\src\DinkToPdf.TestThreadSafe\test.pdf",
},
Objects = {
new ObjectSettings()
{
Page = host + "/CV/Details/" + id,
},
}
};
var file = converter.Convert(doc);
return File(file, "application/pdf", "cv" + "." + user.Forename + "." + user.Surname + ".pdf");
}
#endregion
#region UTILS
public User GetUser()
{
var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
var user = _context.Users.FirstOrDefault(x => x.Id == userId);
return user;
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SpelunkyPracticeTool
{
enum AllEntities
{
PLAYER = 0,
MINE = 92,
WHIP = 109,
CHEST = 100,
CRATE = 101,
GOLD_BAR = 102,
STACK_OF_GOLD_BARS = 103,
LARGE_EMERALD = 104,
LARGE_SAPPHIRE = 105,
LARGE_RUBY = 106,
LIVE_BOMB = 107,
ATTACHED_ROPE = 108,
BLOOD = 110,
DIRT_BREAK = 111,
STONE = 112,
POT = 113,
SKULL = 114,
SPIDER_WEB = 115,
HONEY = 116,
SHOTGUN_SHOT = 117,
LARGE_GOLD_NUGGET = 118,
BOULDER = 120,
PUSHABLE_STONE_BLOCK = 121,
ARROW = 122,
SMALL_GOLD_NUGGET = 124,
SMALL_EMERALD = 125,
SMALL_SAPPHIRE = 126,
SMALL_RUBY = 127,
ROPE_PART = 137,
SPIDER_WEB_SHOT = 142,
GOLD_CHEST = 153,
GOLD_KEY = 154,
USED_PARACHUTE = 156,
SCRATCH = 158,
ALIEN_SHOT = 159,
UFO_SHOT = 160,
FALLING_PLATFORM = 161,
LAMP = 162,
FLARE = 163,
SNOWBALL = 164,
FLY = 165,
BLACK_BOX = 166,
SPRITESHEET_1 = 167,
FLYING_TRAP_BLOCK = 168,
FLYING_LAVA = 169,
WIN_GAME = 170,
WHITE_FLAG = 171,
FISH_SKELETON = 172,
NATURAL_DIAMOND = 173,
WORM_ENTRANCE = 174,
WORM_ACTIVATED = 175,
IMP_COULDRON = 176,
BRIGHT_LIGHT = 177,
SPIKE_BALL = 178,
METAL_BREAK = 179,
JOURNAL = 180,
PAPER = 181,
WORM_BLOCK = 182,
ICE_PLATFORM = 183,
LEAF = 184,
STATIC_CHEST = 187,
PRIZE_WHEEL = 188,
PRIZE_WHEEL_FLIPPER = 189,
PRIZE_DOOR = 190,
ACID_BOBBLE = 192,
ACID_DROP = 193,
FALLING_ICE = 194,
ICE_BREAK = 195,
SMOKE_1 = 196,
FORCE_FIELD = 197,
FORCE_FIELD_BEAM = 198,
ICE_ENERGY_SHOT = 203,
BROKEN_MATTOCK = 210,
COFFIN = 211,
UNKNOWN_1 = 212,
TURRET_SHOT = 213,
SPACESHIP_PLATFORM = 214,
SPACESHIP_ELEVATOR = 215,
BROKEN_ARROW = 216,
OLMEC_ORB = 217,
FALLING_WATER = 218,
BLACK_BOX_ACCESSORY = 219,
BLACK_BOX_PICKUP = 219,
CHAIN_BALL = 220,
SMOKE_2 = 221,
OLMEC_INTRO = 223,
CAMEL = 224,
ALIEN_TARGET = 225,
ALIEN_TARGET_SHOT = 226,
SPACESHIP_LIGHT = 227,
SPIDER_WEB_BALL = 228,
ANKH_RESPAWN = 229,
ANKH_GLOW = 230,
BEE_PARTS = 232,
FIRE = 233,
ANUBIS_II = 234,
POWDER_BOX = 235,
STRING = 236,
SMALL_SPIDER_WEB = 237,
SPRITESHEET_2 = 238,
YANG = 239,
COIN = 240,
FIREWORK = 242,
BLACK_BOX_ROPE = 244,
UNLIT_WALL_TORCH = 245,
UNLIT_TORCH = 246,
ALIEN_QUEEN_RING = 247,
MYSTERY_BOX = 248,
INVISABLE_BLOCK = 249,
SKULL_CROWN = 250,
SPRITESHEET_3 = 251,
EGGPLANT = 252,
BALLOON = 253,
EXPLOSION = 301,
RED_BALL = 302,
TINY_FIRE = 303,
SPRING_RINGS = 304,
SPELUNKER_TELEPORT = 305,
TORCH_FIRE = 306,
SMALL_FIRE = 307,
GLASS_BLOCK = 455,
ROPES = 500,
BOMB_BAG = 501,
BOMB_BOX = 502,
SPECTACLE = 503,
CLIMBING_GLOVES = 504,
PITCHERS_MITT = 505,
SPRING_SHOES = 506,
SPIKE_SHOES = 507,
BOMB_PASTE = 508,
COMPASS = 509,
MATTOCK = 510,
BOOMERANG = 511,
MACHETE = 512,
CRYSKNIFE = 513,
WEB_GUN = 514,
SHOTGUN = 515,
FREEZE_RAY = 516,
PLASMA_CANNON = 517,
CAMERA = 518,
TELEPORTER = 519,
PARACHUTE = 520,
CAPE = 521,
JETPACK = 522,
SHIELD = 523,
ROYAL_JELLY = 524,
IDOL = 525,
KAPALA = 526,
UDJAT_EYE = 527,
ANKH = 528,
HEDJET = 529,
SCEPTER = 530,
BOOK_OF_THE_DEAD = 531,
VLADS_CAPE = 532,
VLADS_AMULET = 533,
SNAKE = 1001,
SPIDER = 1002,
BAT = 1003,
CAVEMAN = 1004,
DAMSEL = 1005,
SHOPKEEPER = 1006,
FROG = 1007,
MANTRAP = 1008,
YETI = 1009,
UFO = 1010,
HAWK_MAN = 1011,
SKELETON = 1012,
PIRANHA = 1013,
MUMMY = 1014,
MONKEY = 1015,
ALIEN_LORD = 1016,
GHOST = 1017,
GIANT_SPIDER = 1018,
JIAN_SHI = 1019,
VAMPIRE = 1020,
FIRE_FROG = 1021,
TUNNEL_MAN = 1022,
OLD_BITEY = 1023,
SCARAB = 1024,
YETI_KING = 1025,
ALIEN = 1026,
UNKNOWN_2 = 1027,
VLAD = 1028,
SCORPION = 1029,
IMP = 1030,
DEVIL = 1031,
BEE = 1032,
ANUBIS = 1033,
QUEEN_BEE = 1034,
BACTERIUM = 1035,
COBRA = 1036,
SPINNER_SPIDER = 1037,
GIANT_FROG = 1038,
MAMMOTH = 1039,
ALIEN_TANK = 1040,
TIKI_MAN = 1041,
SCORPION_FLY = 1042,
SNAIL = 1043,
CROC_MAN = 1044,
GREEN_KNIGHT = 1045,
WORM_EGG = 1046,
WORM_BABY = 1047,
ALIEN_QUEEN = 1048,
THE_BLACK_KNIGHT = 1049,
GOLDEN_MONKEY = 1050,
SUCCUBUS = 1051,
HORSE_HEAD = 1052,
OX_FACE = 1053,
OLMEC = 1055,
KING_YAMA = 1056,
KING_YAMAS_HAND = 1057,
TURRET = 1058,
BABY_FROG = 1059,
WATCHING_BALL = 1060,
SPIDERLING = 1061,
FISH = 1062,
RAT = 1063,
PENGUIN = 1064,
BACKGROUND_ALIEN = 1065,
BIRDS = 1066,
LOCUST = 1067,
MAGGOT = 1068
};
public partial class entity_list : Form
{
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int GetScrollPos(IntPtr hWnd, int nBar);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);
private const int SB_HORZ = 0x0;
private const int SB_VERT = 0x1;
Dictionary<int, EntityData> Entities = new Dictionary<int, EntityData>();
public entity_list()
{
InitializeComponent();
typeof(Panel).InvokeMember("DoubleBuffered",
BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
null, panel, new object[] { true });
ListFont = new Font("Arial", 9);
YOff = Font.Height + 1;
}
private void fetchlistbutton_Click(object sender, EventArgs e)
{
RefreshTree();
}
public void RefreshTree()
{
if (Memory.Process == null || Memory.Process.HasExited) return;
int address = Memory.getPointerAddress(Memory.BaseAddress + 0x1384B4, 0x30, 0), ptr, i = 0;
EntityData en;
var c = new Dictionary<int, EntityData>();
while ((ptr = Memory.ReadInt32(address + i++ * 4)) != 0)
if(!c.ContainsKey(ptr))
c.Add(ptr, Entities.TryGetValue(ptr, out en) ? en.UpdateValues() : new EntityData(ptr));
Entities = c;
panel.Invalidate();
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
Updater.Enabled = !Updater.Enabled;
toolStripButton2.Text = (Updater.Enabled ? "Disable" : "Enable")+" Auto-Update";
}
private void Updater_Tick(object sender, EventArgs e)
{
RefreshTree();
}
int YOff = 20;
Font ListFont;
const int XOff = 15;
const int NodeOff = 30;
private void panel_Paint(object sender, PaintEventArgs e)
{
var g = e.Graphics;
var b = new SolidBrush(Color.Black);
int y = panel.AutoScrollPosition.Y;
g.Clear(Color.White);
foreach(var Entity in Entities.Values)
{
y += YOff;
g.DrawString((Entity.ShowValues ? '-' : '+' ) + Entity.Name, Font, b, XOff, y);
if (!Entity.ShowValues) continue;
foreach(var value in Entity.Values)
{
y += YOff;
g.DrawString(value,DefaultFont,b,NodeOff, y);
}
}
panel.AutoScroll = true;
AutoScrollLabel.Location = new Point(0,y+YOff);
}
private void panel_Click(object sender, EventArgs e)
{
}
private void panel_MouseUp(object sender, MouseEventArgs e)
{
int y = panel.AutoScrollPosition.Y;
foreach (var Entity in Entities.Values)
{
y += YOff;
if(y < e.Y && y+YOff > e.Y)
{
Entity.ShowValues = !Entity.ShowValues;
panel.Invalidate();
return;
}
if (!Entity.ShowValues) continue;
foreach (var value in Entity.Values)
y += YOff;
}
}
}
}
|
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 CursoWindowsForms
{
public partial class frm_DemonstracaoKey : Form
{
public frm_DemonstracaoKey()
{
InitializeComponent();
}
private void frm_DemonstracaoKey_Load(object sender, EventArgs e)
{
}
//Método para limpar toda a tela
private void btn_Reset_Click(object sender, EventArgs e)
{
//Atribuindo o valor vazio para os campos do formulário.
txt_Msg.Text = "";
txt_Input.Text = "";
lbl_Lower.Text = "";
lbl_Upper.Text = "";
}
//Capturando o valor digitado no txt_Input e passando para o txt_Msg
private void txt_Input_KeyDown(object sender, KeyEventArgs e)
{
// txt_Msg.AppendText recebe o valor passado no método pelo e.KeyCode, que é o valor digitado no campo.
txt_Msg.AppendText("\r\n"+ "Pressionei a tecla " + e.KeyCode +"\r\n");
txt_Msg.AppendText("\t" + "Código da tecla " + ((int)e.KeyCode) + "\r\n");
txt_Msg.AppendText("\t" + "Nome da tecla " + e.KeyData + "\r\n");
//O texto/conteúdo da label lbl_Upper recebe o valor do campo maiúsculo
lbl_Upper.Text = e.KeyCode.ToString().ToUpper();
//O texto/conteúdo da label lbl_Lower recebe o valor do campo minúsculo
lbl_Lower.Text = e.KeyCode.ToString().ToLower();
}
//Criando método para sair/fechar a aplicação
private void btn_fechar_Click(object sender, EventArgs e)
{
//Chamando o método Close para fechar apenas o formulário demonstração.
this.Close();
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Pobs.Domain.Entities;
using Pobs.Domain.QueryObjects;
namespace Pobs.Domain
{
public class HonestQDbContext : DbContext
{
public HonestQDbContext(DbContextOptions<HonestQDbContext> options) : base(options)
{
}
// Entities
public DbSet<Notification> Notifications { get; set; }
public DbSet<PushToken> PushTokens { get; set; }
public DbSet<Question> Questions { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Watch> Watches { get; set; }
// Query objects
public DbQuery<QuestionSearchResult> QuestionSearch { get; set; }
public DbQuery<QuestionNotificationToPush> QuestionNotificationsToPush { get; set; }
public DbQuery<AnswerNotificationToPush> AnswerNotificationsToPush { get; set; }
public DbQuery<CommentNotificationToPush> CommentNotificationsToPush { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
// Tables take DbSet property name by default. Let's stick to Entity name
entityType.Relational().TableName = entityType.DisplayName();
}
// Unique contraints
modelBuilder.Entity<Tag>().HasIndex(x => x.Slug).IsUnique();
modelBuilder.Entity<User>().HasIndex(x => x.Username).IsUnique();
modelBuilder.Entity<Reaction>().HasIndex(x => new { x.AnswerId, x.PostedByUserId, x.Type }).IsUnique();
modelBuilder.Entity<Reaction>().HasIndex(x => new { x.CommentId, x.PostedByUserId, x.Type }).IsUnique();
modelBuilder.Entity<Watch>().HasIndex(x => new { x.UserId, x.TagId }).IsUnique();
modelBuilder.Entity<Watch>().HasIndex(x => new { x.UserId, x.QuestionId }).IsUnique();
modelBuilder.Entity<Watch>().HasIndex(x => new { x.UserId, x.AnswerId }).IsUnique();
modelBuilder.Entity<Watch>().HasIndex(x => new { x.UserId, x.CommentId }).IsUnique();
// NOTE: Question Slug could also be unique by TagId, but don't worry for now, we need far more clever de-duplication anyway
// Emoji-enabled columns. TODO: can this be done by an Attribute? Also probably needs Database and Tables altered before Columns...
modelBuilder.Entity<Tag>(x =>
{
x.Property(p => p.Name).HasCharSetForEmoji();
x.Property(p => p.Description).HasCharSetForEmoji();
});
modelBuilder.Entity<Question>(x =>
{
x.Property(p => p.Text).HasCharSetForEmoji();
x.Property(p => p.Context).HasCharSetForEmoji();
});
modelBuilder.Entity<Answer>(x =>
{
x.Property(p => p.Text).HasCharSetForEmoji();
});
modelBuilder.Entity<Comment>(x =>
{
x.Property(p => p.Text).HasCharSetForEmoji();
x.Property(p => p.Source).HasCharSetForEmoji();
});
modelBuilder.Entity<User>(x =>
{
x.Property(p => p.Email).HasCharSetForEmoji();
x.Property(p => p.Username).HasCharSetForEmoji();
});
// Cascade all the deletes
modelBuilder.Entity<Comment>().HasOne(x => x.ParentComment).WithMany(x => x.ChildComments)
.Metadata.DeleteBehavior = DeleteBehavior.Cascade;
modelBuilder.Entity<Notification>().HasOne(x => x.Answer).WithMany(x => x.Notifications)
.Metadata.DeleteBehavior = DeleteBehavior.Cascade;
modelBuilder.Entity<Notification>().HasOne(x => x.Comment).WithMany(x => x.Notifications)
.Metadata.DeleteBehavior = DeleteBehavior.Cascade;
modelBuilder.Entity<Notification>().HasOne(x => x.Question).WithMany(x => x.Notifications)
.Metadata.DeleteBehavior = DeleteBehavior.Cascade;
modelBuilder.Entity<PushToken>().HasOne(x => x.User).WithMany(x => x.PushTokens)
.Metadata.DeleteBehavior = DeleteBehavior.Cascade;
modelBuilder.Entity<Reaction>().HasOne(x => x.Answer).WithMany(x => x.Reactions)
.Metadata.DeleteBehavior = DeleteBehavior.Cascade;
modelBuilder.Entity<Reaction>().HasOne(x => x.Comment).WithMany(x => x.Reactions)
.Metadata.DeleteBehavior = DeleteBehavior.Cascade;
modelBuilder.Entity<Watch>().HasOne(x => x.Answer).WithMany(x => x.Watches)
.Metadata.DeleteBehavior = DeleteBehavior.Cascade;
modelBuilder.Entity<Watch>().HasOne(x => x.Comment).WithMany(x => x.Watches)
.Metadata.DeleteBehavior = DeleteBehavior.Cascade;
modelBuilder.Entity<Watch>().HasOne(x => x.Question).WithMany(x => x.Watches)
.Metadata.DeleteBehavior = DeleteBehavior.Cascade;
modelBuilder.Entity<Watch>().HasOne(x => x.Tag).WithMany(x => x.Watches)
.Metadata.DeleteBehavior = DeleteBehavior.Cascade;
// Many-to-many relationships
modelBuilder.Entity<QuestionTag>().HasKey(x => new { x.QuestionId, x.TagId });
modelBuilder.Entity<QuestionTag>().HasOne(x => x.Question).WithMany(x => x.QuestionTags);
modelBuilder.Entity<QuestionTag>().HasOne(x => x.Tag).WithMany(x => x.QuestionTags);
// Full text indexes for searching
modelBuilder.Entity<Question>().HasIndex(x => x.Text).ForMySqlIsFullText();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JDWinService.Model
{
public class Json_Bill_Page4
{
public page4 Page4 { get; set; }
public class page4
{
public string FIndex4 { get; set; }
public string FIsOld { get; set; }
public Fbominterid FBomInterID { get; set; }
public string FModifyType { get; set; }
public string FModifyContent { get; set; }
public Fitemid FItemID { get; set; }
public string FItemName { get; set; }
public string FModel { get; set; }
public string FItemClsID { get; set; }
public string FEntryItemOldIndex { get; set; }
public Funitid FUnitID { get; set; }
public string FAuxQty { get; set; }
public string FQty { get; set; }
public string FEntryBeginDay { get; set; }
public string FEntryEndDay { get; set; }
public Fheadroutingid FHeadRoutingID { get; set; }
public string FHeadRoutingName { get; set; }
public string FHeadVersion { get; set; }
public string FEntryScrap { get; set; }
public string FHeadYield { get; set; }
public string FEntryPositionNo { get; set; }
public Fheadbomskip FHeadBOMSkip { get; set; }
public string FHeadNote { get; set; }
public string FEntryItemSize { get; set; }
public string FEntryItemSuite { get; set; }
public Fentrymarshaltype FEntryMarshalType { get; set; }
public string FEntryPercent { get; set; }
public string FEntryOperSN { get; set; }
public Fentryoperid FEntryOperID { get; set; }
public string FEntryMachinePos { get; set; }
public Fentrymaterieltype FEntryMaterielType { get; set; }
public string FEntryOffSetDay { get; set; }
public Fentrybackflush FEntryBackFlush { get; set; }
public string FEntryIsKeyItem { get; set; }
public string FEntryUseState { get; set; }
public string FEntryForbitUse { get; set; }
public Fentrystockid FEntryStockID { get; set; }
public Fentryspid FEntrySPID { get; set; }
public string FEntryNOTE { get; set; }
public string FEntryNOTE1 { get; set; }
public string FEntryNOTE2 { get; set; }
public string FEntryNOTE3 { get; set; }
}
public class Fbominterid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fitemid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Funitid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fheadroutingid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fheadbomskip
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fentrymarshaltype
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fentryoperid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fentrymaterieltype
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fentrybackflush
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fentrystockid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fentryspid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
}
}
|
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 QLDSV
{
public partial class frmSinhVien : Form
{
int vitri = 0, i = 0;
String maKhoa = "";
bool kt;
public frmSinhVien()
{
InitializeComponent();
}
private void lOPBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.bdsLop.EndEdit();
this.tableAdapterManager.UpdateAll(this.dS);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dS.LOP' table. You can move, or remove it, as needed.
dS.EnforceConstraints = false; // tắt ràng buộc khóa ngoại
//this.sINHVIENTableAdapter.Fill(this.DS.SINHVIEN); //gọi danh sách lớp vào trong table
this.lOPTableAdapter.Connection.ConnectionString = Program.connstr;
this.lOPTableAdapter.Fill(this.dS.LOP);
// TODO: This line of code loads data into the 'DS.SINHVIEN' table. You can move, or remove it, as needed.
this.sINHVIENTableAdapter.Connection.ConnectionString = Program.connstr;
this.sINHVIENTableAdapter.Fill(this.dS.SINHVIEN);
// TODO: This line of code loads data into the 'DS.DIEM' table. You can move, or remove it, as needed.
this.dIEMTableAdapter.Connection.ConnectionString = Program.connstr;
this.dIEMTableAdapter.Fill(this.dS.DIEM);
//DS.EnforceConstraints = true;
maKhoa = ((DataRowView)bdsLop[0])["MAKH"].ToString();
cmbKhoa.DataSource = Program.bds_dspm;
cmbKhoa.DisplayMember = "TENCN";
cmbKhoa.ValueMember = "TENSERVER";
cmbKhoa.SelectedIndex = Program.mKhoa;
if (Program.mGroup == "PGV")
{
cmbKhoa.Enabled = true;
btnPhucHoi.Enabled = false;
btnGhi.Enabled = false;
btnTaiLai.Enabled = true;
btnGhiSV.Enabled = true;
btnTaiLaiSV.Enabled = true;
}
else
{
cmbKhoa.Enabled = false;
}
if (Program.mGroup == "Khoa" || Program.mGroup == "PKeToan")
{
btnThem.Enabled = false;
btnXoa.Enabled = false;
btnPhucHoi.Enabled = false;
btnHieuChinh.Enabled = false;
btnGhi.Enabled = false;
btnTaiLaiSV.Enabled = btnTaiLaiSV.Enabled = true;
btnThemSV.Enabled = false;
btnXoaSV.Enabled = false;
btnGhiSV.Enabled = false;
}
groupBox1.Enabled = false;
}
private void btnHieuChinh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
vitri = bdsLop.Position;
groupBox1.Enabled = true;
cmbKhoa.Enabled = false;
lOPGridControl.Enabled = sINHVIENGridControl.Enabled = false;
kt = true;
btnThem.Enabled = btnHieuChinh.Enabled = btnXoa.Enabled = btnTaiLai.Enabled = false;
btnGhi.Enabled = btnPhucHoi.Enabled = true;
}
private void btnXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
if (bdsSV.Count != 0)
{
MessageBox.Show("Lớp đã có sinh viên không thể xóa \n", "",
MessageBoxButtons.OK);
return;
}
String malop = "";
if (MessageBox.Show("Bạn có thật sự muốn xóa lớp " + ((DataRowView)bdsLop[bdsLop.Position])["MALOP"].ToString() + " ?? ", "Xác nhận",
MessageBoxButtons.OKCancel) == DialogResult.OK)
{
try
{
malop = ((DataRowView)bdsLop[bdsLop.Position])["MALOP"].ToString();// giữ lại để khi xóa bị lỗi thì ta sẽ quay về lại
bdsLop.Position = bdsLop.Find("MALOP", malop);
MessageBox.Show("Đã xóa lớp" + malop);
bdsLop.RemoveCurrent(); //xóa đi hàng hiện tại ra khỏi dataSet
this.lOPTableAdapter.Connection.ConnectionString = Program.connstr;
this.lOPTableAdapter.Update(this.dS.LOP);
}
catch (Exception ex)
{
MessageBox.Show("Lớp đã có sinh viên không thể xóa \n" + ex.Message, "",
MessageBoxButtons.OK);
this.lOPTableAdapter.Fill(this.dS.LOP);
bdsLop.Position = bdsLop.Find("MALOP", malop);
return;
}
}
if (bdsLop.Count == 0) btnXoa.Enabled = false;
}
private void dbsDiem_CurrentChanged(object sender, EventArgs e)
{
}
private void btnPhucHoi_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
bdsLop.CancelEdit();
if (btnThem.Enabled == false) bdsLop.Position = vitri;
groupBox1.Enabled = false;
lOPGridControl.Enabled = sINHVIENGridControl.Enabled = true;
btnThem.Enabled = btnHieuChinh.Enabled = btnXoa.Enabled = btnTaiLai.Enabled = btnThoat.Enabled = true;
btnGhi.Enabled = btnPhucHoi.Enabled = false;
if (Program.mGroup == "PGV")
{
cmbKhoa.Enabled = true;
}
}
private void btnGhi_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
if (txtMaKhoa.Text.Trim() == "")
{
MessageBox.Show("Mã khoa không được thiếu!", "", MessageBoxButtons.OK);
txtMaKhoa.Focus();
return;
}
if (txtMaLop.Text.Trim() == "")
{
MessageBox.Show("Mã lớp không được thiếu!", "", MessageBoxButtons.OK);
txtMaLop.Focus();
return;
}
try
{
string strLenh = "EXEC sp_KTraLop '" + txtMaLop.Text + "'";
Program.myReader = Program.ExecSqlDataReader(strLenh);
Program.myReader.Read();
int s = Program.myReader.GetInt32(0);
if (s == 1)
{
MessageBox.Show("Mã lớp đã bị trùng!", "", MessageBoxButtons.OK);
txtMaLop.Focus();
Program.myReader.Close();
return;
}
Program.myReader.Close();
}
catch (Exception ex)
{
MessageBox.Show("kiểm tra lớp bị lỗi!", "", MessageBoxButtons.OK);
}
if (txtTenLop.Text.Trim() == "")
{
MessageBox.Show("Tên lớp không được thiếu!", "", MessageBoxButtons.OK);
txtTenLop.Focus();
return;
}
try
{
bdsLop.EndEdit();
bdsLop.ResetCurrentItem();
this.lOPTableAdapter.Connection.ConnectionString = Program.connstr;
this.lOPTableAdapter.Update(this.dS.LOP);
if (Program.mGroup == "PGV")
{
cmbKhoa.Enabled = true;
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi ghi lớp.\n" + ex.Message, "", MessageBoxButtons.OK);
return;
}
btnThem.Enabled = btnHieuChinh.Enabled = btnXoa.Enabled = btnTaiLai.Enabled = true;
btnGhi.Enabled = btnPhucHoi.Enabled = false;
lOPGridControl.Enabled = sINHVIENGridControl.Enabled = true;
groupBox1.Enabled = false;
}
private void btnTaiLai_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
try
{
this.lOPTableAdapter.Fill(this.dS.LOP);
this.sINHVIENTableAdapter.Fill(this.dS.SINHVIEN);
this.dIEMTableAdapter.Fill(this.dS.DIEM);
lOPGridControl.Enabled = sINHVIENGridControl.Enabled = true;
if (Program.mGroup == "PGV")
{
cmbKhoa.Enabled = true;
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi tải lại :" + ex.Message, "", MessageBoxButtons.OK);
return;
}
}
private void btnThoat_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
cmbKhoa.DataSource = null;
this.Close();
}
private void btnThemSV_Click(object sender, EventArgs e)
{
vitri = bdsSV.Position;
bdsSV.AddNew();
i = 1;
((DataRowView)bdsSV[bdsSV.Position])["NGHIHOC"] = false;
((DataRowView)bdsSV[bdsSV.Position])["PHAI"] = false;
btnThemSV.Enabled = btnXoaSV.Enabled = false;
btnGhiSV.Enabled = btnTaiLaiSV.Enabled = true;
}
private void btnTaiLaiSV_Click(object sender, EventArgs e)
{
try
{
this.sINHVIENTableAdapter.Connection.ConnectionString = Program.connstr;
this.sINHVIENTableAdapter.Fill(this.dS.SINHVIEN);
// TODO: This line of code loads data into the 'DS.DIEM' table. You can move, or remove it, as needed.
this.dIEMTableAdapter.Connection.ConnectionString = Program.connstr;
this.dIEMTableAdapter.Fill(this.dS.DIEM);
i = 0;
if (Program.mGroup == "PGV")
{
btnThemSV.Enabled = btnXoaSV.Enabled = true;
btnGhiSV.Enabled = btnTaiLaiSV.Enabled = true;
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi tải lại :" + ex.Message, "", MessageBoxButtons.OK);
return;
}
}
private void btnXoaSV_Click(object sender, EventArgs e)
{
if (bdsDIEM.Count != 0)
{
MessageBox.Show("Sinh viên không thể xóa do đã có điểm!", "", MessageBoxButtons.OK);
return;
}
String masv = "";
masv = ((DataRowView)bdsSV[bdsSV.Position])["MASV"].ToString();
string strLenh = "EXEC sp_KTraHP '" + masv + "'";
Program.myReader = Program.ExecSqlDataReader(strLenh);
Program.myReader.Read();
int s = Program.myReader.GetInt32(0);
if (s == 1)
{
MessageBox.Show("Sinh viên không thể xóa do đã đóng học phí!", "", MessageBoxButtons.OK);
Program.myReader.Close();
return;
}
Program.myReader.Close();
if (MessageBox.Show("Bạn có thật sự muốn xóa sinh viên " + masv + " ?? ", "Xác nhận",
MessageBoxButtons.OKCancel) == DialogResult.OK)
{
try
{
masv = ((DataRowView)bdsSV[bdsSV.Position])["MASV"].ToString();
//bdsSV.Position = bdsSV.Find("MASV", masv);
bdsSV.RemoveCurrent();
this.sINHVIENTableAdapter.Connection.ConnectionString = Program.connstr;
this.sINHVIENTableAdapter.Update(this.dS.SINHVIEN);
MessageBox.Show("Đã xóa sinh viên" + masv);
i = 0;
}
catch (Exception ex)
{
MessageBox.Show("Lỗi xóa sinh viên \n" + ex.Message, "",
MessageBoxButtons.OK);
this.sINHVIENTableAdapter.Fill(this.dS.SINHVIEN);
//bdsSV.Position = bdsSV.Find("MASV", masv);
return;
}
}
}
private void btnGhiSV_Click(object sender, EventArgs e)
{
String masv = "";
masv = ((DataRowView)bdsSV[bdsSV.Position])["MASV"].ToString();
String ho = "";
ho = ((DataRowView)bdsSV[bdsSV.Position])["HO"].ToString();
String ten = "";
ten = ((DataRowView)bdsSV[bdsSV.Position])["TEN"].ToString();
String malop = "";
malop = ((DataRowView)bdsSV[bdsSV.Position])["MALOP"].ToString();
if (masv.Equals(""))
{
MessageBox.Show("Mã sinh viên không được để trống!", "", MessageBoxButtons.OK);
return;
}
if (malop.Equals(""))
{
MessageBox.Show("Mã lớp không được để trống!", "", MessageBoxButtons.OK);
return;
}
string strLenh;
int s;
if (!malop.Equals(txtMaLop.Text))
{
MessageBox.Show("Mã lớp khác với lớp bạn đang trọn!", "", MessageBoxButtons.OK);
return;
}
if (i == 1)
{
strLenh = "EXEC sp_KTraSV '" + masv + "'";
Program.myReader = Program.ExecSqlDataReader(strLenh);
Program.myReader.Read();
s = Program.myReader.GetInt32(0);
if (s == 1)
{
MessageBox.Show("Mã sinh viên đã bị trùng hoặc bạn phải để con trỏ chuột chọn tại vị trí thêm mới!", "", MessageBoxButtons.OK);
Program.myReader.Close();
return;
}
Program.myReader.Close();
}
try
{
bdsSV.EndEdit();
bdsSV.ResetCurrentItem();
this.sINHVIENTableAdapter.Connection.ConnectionString = Program.connstr;
this.sINHVIENTableAdapter.Update(this.dS.SINHVIEN);
//cmbKhoa.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show("Lỗi ghi sinh viên.\n" + ex.Message, "", MessageBoxButtons.OK);
return;
}
i = 0;
btnThemSV.Enabled = btnXoaSV.Enabled = btnTaiLaiSV.Enabled = true;
btnGhiSV.Enabled = true;
}
private void cmbKhoa_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbKhoa.SelectedValue != null)
{
if (cmbKhoa.SelectedValue.ToString() == "System.Data.DataRowView")
return;
Program.servername = cmbKhoa.SelectedValue.ToString();
if (Program.mGroup == "PGV" && cmbKhoa.SelectedIndex == 2)
{
MessageBox.Show("Bạn không có quyền truy cập cái này", "", MessageBoxButtons.OK);
cmbKhoa.SelectedIndex = 1;
cmbKhoa.SelectedIndex = 0;
return;
}
if (cmbKhoa.SelectedIndex != Program.mKhoa)
{
Program.mlogin = Program.remotelogin;
Program.password = Program.remotepassword;
}
else
{
Program.mlogin = Program.mloginDN;
Program.password = Program.passwordDN;
}
if (Program.KetNoi() == 0)
MessageBox.Show("Lỗi kết nối về chi nhánh mới", "", MessageBoxButtons.OK);
else
{
if (Program.mGroup == "PGV" || Program.mGroup == "Khoa")
{
this.lOPTableAdapter.Connection.ConnectionString = Program.connstr;
this.lOPTableAdapter.Fill(this.dS.LOP);
this.sINHVIENTableAdapter.Connection.ConnectionString = Program.connstr;
this.sINHVIENTableAdapter.Fill(this.dS.SINHVIEN);
}
}
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void btnThem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
vitri = bdsLop.Position;
groupBox1.Enabled = true;
bdsLop.AddNew();
txtMaLop.Focus();
txtMaKhoa.Text = gridView1.GetRowCellValue(0, "MAKH").ToString();
txtMaKhoa.Enabled = lOPGridControl.Enabled = false;
kt = false;
cmbKhoa.Enabled = sINHVIENGridControl.Enabled = false;
btnThem.Enabled = btnHieuChinh.Enabled = btnXoa.Enabled = btnTaiLai.Enabled = false;
btnGhi.Enabled = btnPhucHoi.Enabled = true;
}
}
}
|
using gView.Framework.Carto;
using gView.Framework.Data;
using gView.Framework.Data.Cursors;
using gView.Framework.Data.Filters;
using gView.Framework.Geometry;
using gView.Framework.system;
using gView.Framework.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace gView.Plugins.MapTools.Dialogs
{
internal partial class FormQuery : Form, IDockableWindow
{
private FormIdentify _parent = null;
private BackgroundWorker _worker = new BackgroundWorker();
private BackgroundWorker _worker2 = new BackgroundWorker();
private CancelTracker _cancelTracker = new CancelTracker();
private QueryThemeCombo _combo = null;
private object lockThis = new object();
public FormQuery(FormIdentify parent)
{
if (parent == null)
{
return;
}
InitializeComponent();
_parent = parent;
if (!Modal)
{
//this.TopLevel = false;
//this.TopMost = true;
//this.Parent = parent._doc.Application.ApplicationWindow;
if (parent._doc.Application is IMapApplication)
{
this.Owner = ((IMapApplication)parent._doc.Application).ApplicationWindow as Form;
}
}
_combo = this.QueryCombo;
if (_combo == null)
{
return;
}
_combo.SelectedItemChanged += new QueryThemeCombo.SelectedItemChangedEvent(QueryCombo_SelectedItemChanged);
this.ThemeMode = _combo.ThemeMode;
_worker.DoWork += new DoWorkEventHandler(worker_DoWork);
_worker2.DoWork += new DoWorkEventHandler(worker2_DoWork);
}
public QueryThemeMode ThemeMode
{
set
{
if (value == QueryThemeMode.Default)
{
panelCustom.Visible = false;
panelStandard.Visible = true;
panelStandard.Dock = DockStyle.Fill;
}
else
{
panelStandard.Visible = false;
panelCustom.Visible = true;
panelCustom.Dock = DockStyle.Fill;
BuildQueryForm();
}
}
}
#region Worker DefaultQuery
private enum SearchType { allfields, field, displayfield }
private SearchType _searchType = SearchType.allfields;
private IdentifyMode _mode = IdentifyMode.visible;
private string _queryField = "";
private string _queryVal = "";
private bool _useWildcards = false;
private IMap _focusMap = null;
async private void worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
if (_parent == null || _parent.MapDocument == null ||
_parent.MapDocument.FocusMap == null ||
_parent.MapDocument.FocusMap.Display == null)
{
return;
}
ISpatialReference sRef =
(_parent.MapDocument.FocusMap.Display.SpatialReference != null) ?
_parent.MapDocument.FocusMap.Display.SpatialReference.Clone() as ISpatialReference :
null;
StartProgress();
List<IDatasetElement> elements = e.Argument as List<IDatasetElement>;
if (elements == null)
{
return;
}
foreach (IDatasetElement element in elements)
{
if (!(element is IFeatureLayer))
{
continue;
}
IFeatureLayer layer = element as IFeatureLayer;
if (!(element.Class is IFeatureClass))
{
continue;
}
IFeatureClass fc = element.Class as IFeatureClass;
if (fc.Fields == null)
{
continue;
}
string val = _queryVal.Replace("*", "%");
string sval = _useWildcards ? AppendWildcards(val) : val;
//
// Collect Fields
//
FieldCollection queryFields = new FieldCollection();
foreach (IField field in fc.Fields.ToEnumerable())
{
if (field.type == FieldType.binary || field.type == FieldType.Shape)
{
continue;
}
if (field.name.Contains(":"))
{
continue; // No Joined Fields
}
if (_searchType == SearchType.allfields)
{
queryFields.Add(field);
}
else if (_searchType == SearchType.field)
{
if (field.aliasname == _queryField)
{
queryFields.Add(field);
}
}
else if (_searchType == SearchType.displayfield)
{
}
}
if (queryFields.Count == 0)
{
continue;
}
//
// Build SQL Where Clause
//
StringBuilder sql = new StringBuilder();
foreach (IField field in queryFields.ToEnumerable())
{
switch (field.type)
{
case FieldType.character:
case FieldType.String:
case FieldType.NString:
if (sql.Length > 0)
{
sql.Append(" OR ");
}
sql.Append(field.name);
sql.Append(sval.IndexOf("%") == -1 ? "=" : " like ");
sql.Append("'" + sval + "'");
break;
case FieldType.integer:
case FieldType.smallinteger:
case FieldType.biginteger:
case FieldType.Double:
case FieldType.Float:
if (IsNumeric(val))
{
if (sql.Length > 0)
{
sql.Append(" OR ");
}
sql.Append(field.name + "=" + val);
}
break;
}
}
if (sql.Length == 0)
{
continue;
}
if (!_cancelTracker.Continue)
{
return;
}
string title = fc.Name;
if (_focusMap != null && _focusMap.TOC != null)
{
ITOCElement tocElement = _focusMap.TOC.GetTOCElement(element as ILayer);
if (tocElement != null)
{
title = tocElement.Name;
}
}
//
// Query
//
QueryFilter filter = new QueryFilter();
filter.SubFields = "*";
filter.WhereClause = sql.ToString();
filter.FeatureSpatialReference = _parent.MapDocument.FocusMap.Display.SpatialReference;
SetMsgText("Query Table " + title, 1);
SetMsgText("", 2);
using (IFeatureCursor cursor = (await fc.Search(filter)) as IFeatureCursor)
{
if (cursor == null)
{
continue;
}
int counter = 0;
IFeature feature;
List<IFeature> features = new List<IFeature>();
while ((feature = await cursor.NextFeature()) != null)
{
if (!_cancelTracker.Continue)
{
return;
}
//this.AddFeature(feature, fc.SpatialReference, title);
features.Add(feature);
counter++;
if (counter % 100 == 0)
{
SetMsgText(counter + " Features...", 2);
this.AddFeature(features, sRef, layer, title, null, null, null);
features = new List<IFeature>();
}
}
if (features.Count > 0)
{
this.AddFeature(features, sRef, layer, title, null, null, null);
}
if (_mode == IdentifyMode.topmost && counter > 0)
{
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
StopProgress();
}
}
private bool IsNumeric(string val)
{
double num;
return double.TryParse(val, out num);
}
private string AppendWildcards(string val)
{
if (val.Length == 0)
{
return "%";
}
val = "%" + val + "%";
return val.Replace("%%", "%");
}
#endregion
#region Worker Userdef Query
private Dictionary<int, string> _userdefValues = null;
private QueryTheme _theme = null;
async void worker2_DoWork(object sender, DoWorkEventArgs e)
{
if (_theme == null || _theme.Nodes == null || _theme.Nodes.Count == 0 || _userdefValues == null)
{
return;
}
if (_parent == null || _parent.MapDocument == null ||
_parent.MapDocument.FocusMap == null ||
_parent.MapDocument.FocusMap.Display == null)
{
return;
}
ISpatialReference sRef =
(_parent.MapDocument.FocusMap.Display.SpatialReference != null) ?
_parent.MapDocument.FocusMap.Display.SpatialReference.Clone() as ISpatialReference :
null;
try
{
StartProgress();
foreach (QueryThemeTable table in _theme.Nodes)
{
if (table.QueryFieldDef == null)
{
continue;
}
IFeatureLayer layer = table.GetLayer(_parent._doc) as IFeatureLayer;
if (layer == null || !(layer.Class is IFeatureClass))
{
continue;
}
IFeatureClass fc = layer.Class as IFeatureClass;
#region SQL
StringBuilder sql = new StringBuilder();
int actPromptID = -99;
foreach (DataRow fieldDef in table.QueryFieldDef.Select("", "Prompt"))
{
string logic = " OR ";
if ((int)fieldDef["Prompt"] != actPromptID)
{
actPromptID = (int)fieldDef["Prompt"];
logic = ") AND (";
}
string val = "";
if (!_userdefValues.TryGetValue((int)fieldDef["Prompt"], out val))
{
continue;
}
if (val == "")
{
continue;
}
val = val.Replace("*", "%");
IField field = fc.FindField(fieldDef["Field"].ToString());
if (field == null)
{
continue;
}
switch (field.type)
{
case FieldType.biginteger:
case FieldType.Double:
case FieldType.Float:
case FieldType.smallinteger:
case FieldType.integer:
if (IsNumeric(val))
{
if (sql.Length > 0)
{
sql.Append(logic);
}
sql.Append(field.name + fieldDef["Operator"] + val);
}
break;
case FieldType.String:
string op = fieldDef["Operator"].ToString();
string v = val;
if (v.IndexOf("%") != -1)
{
op = " like ";
}
else if (op.ToLower() == " like ")
{
v += "%";
}
if (sql.Length > 0)
{
sql.Append(logic);
}
sql.Append(field.name + op + "'" + v + "'");
break;
}
}
if (sql.Length == 0)
{
continue;
}
sql.Insert(0, "(");
sql.Append(")");
#endregion
if (!_cancelTracker.Continue)
{
return;
}
#region Layer Title
string title = fc.Name;
if (_focusMap != null && _focusMap.TOC != null)
{
ITOCElement tocElement = _focusMap.TOC.GetTOCElement(layer);
if (tocElement != null)
{
title = tocElement.Name;
}
}
#endregion
#region Fields
FieldCollection fields = null;
IField primaryDisplayField = null;
if (layer != null && layer.Fields != null && table.VisibleFieldDef != null && table.VisibleFieldDef.UseDefault == false)
{
fields = new FieldCollection();
foreach (IField field in layer.Fields.ToEnumerable())
{
if (table.VisibleFieldDef.PrimaryDisplayField == field.name)
{
primaryDisplayField = field;
}
DataRow[] r = table.VisibleFieldDef.Select("Visible=true AND Name='" + field.name + "'");
if (r.Length == 0)
{
continue;
}
Field f = new Field(field);
f.visible = true;
f.aliasname = (string)r[0]["Alias"];
fields.Add(f);
}
}
#endregion
#region QueryFilter
QueryFilter filter = new QueryFilter();
if (fields == null)
{
filter.SubFields = "*";
}
else
{
foreach (IField field in fields.ToEnumerable())
{
if (!field.visible)
{
continue;
}
filter.AddField(field.name);
}
if (primaryDisplayField != null)
{
filter.AddField(primaryDisplayField.name);
}
if (layer is IFeatureLayer && ((IFeatureLayer)layer).FeatureClass != null)
{
filter.AddField(((IFeatureLayer)layer).FeatureClass.ShapeFieldName);
}
}
filter.WhereClause = sql.ToString();
filter.FeatureSpatialReference = _parent.MapDocument.FocusMap.Display.SpatialReference;
#endregion
SetMsgText("Query Table " + title, 1);
SetMsgText("", 2);
#region Query
using (IFeatureCursor cursor = await fc.Search(filter) as IFeatureCursor)
{
if (cursor == null)
{
continue;
}
int counter = 0;
IFeature feature;
List<IFeature> features = new List<IFeature>();
while ((feature = await cursor.NextFeature()) != null)
{
if (!_cancelTracker.Continue)
{
return;
}
//this.AddFeature(feature, fc.SpatialReference, title);
features.Add(feature);
counter++;
if (counter % 100 == 0)
{
SetMsgText(counter + " Features...", 2);
ManualResetEvent resetEvent = new ManualResetEvent(false);
this.AddFeature(features, sRef, layer, title, fields, primaryDisplayField, resetEvent);
features = new List<IFeature>();
resetEvent.WaitOne();
}
}
if (features.Count > 0)
{
this.AddFeature(features, sRef, layer, title, fields, primaryDisplayField, null);
}
}
#endregion
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
StopProgress();
}
}
#endregion
#region Callbacks
private delegate void StartProgressCallback();
private void StartProgress()
{
if (progressDisk.InvokeRequired)
{
StartProgressCallback d = new StartProgressCallback(StartProgress);
this.Invoke(d);
}
else
{
_parent.Clear();
progressDisk.Visible = true;
progressDisk.Start(100);
}
}
private delegate void StopProgressCallback();
private void StopProgress()
{
if (progressDisk.InvokeRequired)
{
StopProgressCallback d = new StopProgressCallback(StopProgress);
this.Invoke(d);
}
else
{
btnQuery.Enabled = true;
btnStop.Enabled = false;
progressDisk.Stop();
progressDisk.Visible = false;
_parent.WriteFeatureCount();
lblMsg1.Text = lblMsg2.Text = "";
}
}
private delegate void AddFeatureCallback(List<IFeature> features, ISpatialReference sRef, IFeatureLayer layer, string category, IFieldCollection fields, IField primaryDisplayField, ManualResetEvent resetEvent);
private void AddFeature(List<IFeature> features, ISpatialReference sRef, IFeatureLayer layer, string category, IFieldCollection fields, IField primaryDisplayField, ManualResetEvent resetEvent)
{
if (_parent.InvokeRequired)
{
AddFeatureCallback d = new AddFeatureCallback(AddFeature);
this.Invoke(d, new object[] { features, sRef, layer, category, fields, primaryDisplayField, resetEvent });
}
else
{
foreach (IFeature feature in features)
{
_parent.AddFeature(feature, sRef, layer, category, fields, primaryDisplayField);
}
features.Clear();
if (resetEvent != null)
{
resetEvent.Set();
}
}
}
private delegate void SetMsgTextCallback(string text, int msg);
private void SetMsgText(string text, int msg)
{
if (lblMsg1.InvokeRequired)
{
SetMsgTextCallback d = new SetMsgTextCallback(SetMsgText);
this.Invoke(d, new object[] { text, msg });
}
else
{
if (msg == 1)
{
lblMsg1.Text = text;
}
else if (msg == 2)
{
lblMsg2.Text = text;
}
}
}
#endregion
private void btnQuery_Click(object sender, EventArgs e)
{
if (_parent == null || _combo == null)
{
return;
}
if (_combo.ThemeMode == QueryThemeMode.Default)
{
_queryVal = cmbQueryText.Text;
_queryField = cmbField.SelectedItem != null ? cmbField.SelectedItem.ToString() : "";
_useWildcards = chkWildcards.Checked;
_focusMap = _parent._doc != null ? _parent._doc.FocusMap : null;
_mode = _parent.Mode;
if (btnAllFields.Checked)
{
_searchType = SearchType.allfields;
}
else if (btnField.Checked)
{
_searchType = SearchType.field;
}
else if (btnDisplayField.Checked)
{
_searchType = SearchType.displayfield;
}
else
{
return;
}
if (!cmbQueryText.Items.Contains(_queryVal))
{
cmbQueryText.Items.Add(_queryVal);
}
_cancelTracker.Reset();
btnQuery.Enabled = false;
btnStop.Enabled = true;
_worker.RunWorkerAsync(_parent.AllQueryableLayers);
}
else
{
if (_combo.UserDefinedQueries == null)
{
return;
}
foreach (QueryTheme theme in _combo.UserDefinedQueries.Queries)
{
if (theme.Text == lblQueryName.Text)
{
if (theme.PromptDef == null)
{
return;
}
_userdefValues = new Dictionary<int, string>();
foreach (DataRow row in theme.PromptDef.Rows)
{
foreach (Control ctrl in panelCustomFields.Controls)
{
if (ctrl.Name == "txt" + row["ID"].ToString())
{
_userdefValues.Add((int)row["ID"], ctrl.Text);
}
}
}
_theme = theme;
_focusMap = _parent._doc != null ? _parent._doc.FocusMap : null;
_cancelTracker.Reset();
btnQuery.Enabled = false;
btnStop.Enabled = true;
_worker2.RunWorkerAsync();
}
}
}
}
private void btnStop_Click(object sender, EventArgs e)
{
lock (_cancelTracker)
{
_cancelTracker.Cancel();
}
}
private void btnSearch_CheckedChanged(object sender, EventArgs e)
{
if (sender == btnAllFields || sender == btnDisplayField)
{
cmbField.Enabled = false;
}
else
{
cmbField.Enabled = true;
FillFieldsCombo();
}
}
#region IDockableWindow Member
public DockWindowState DockableWindowState
{
get
{
return DockWindowState.none;
}
set
{
}
}
public Image Image
{
get { return null; }
}
#endregion
private void FillFieldsCombo()
{
string selected = cmbField.SelectedItem as string;
cmbField.Items.Clear();
List<IDatasetElement> elements = _parent.AllQueryableLayers;
if (elements == null)
{
return;
}
foreach (IDatasetElement element in elements)
{
if (!(element.Class is IFeatureClass))
{
continue;
}
IFeatureClass fc = element.Class as IFeatureClass;
if (fc.Fields == null)
{
continue;
}
foreach (IField field in fc.Fields.ToEnumerable())
{
if (field.type == FieldType.binary || field.type == FieldType.Shape)
{
continue;
}
if (!cmbField.Items.Contains(field.aliasname))
{
cmbField.Items.Add(field.aliasname);
}
}
}
if (selected != null && cmbField.Items.Contains(selected))
{
cmbField.SelectedItem = selected;
}
if (cmbField.SelectedIndex == -1 && cmbField.Items.Count > 0)
{
cmbField.SelectedIndex = 0;
}
}
private void cmbField_DropDown(object sender, EventArgs e)
{
FillFieldsCombo();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Visible = false;
}
private QueryThemeCombo QueryCombo
{
get
{
if (_parent == null || _parent._doc == null || !(_parent._doc.Application is IGUIApplication))
{
return null;
}
return ((IGUIApplication)_parent._doc.Application).Tool(new Guid("51A2CF81-E343-4c58-9A42-9207C8DFBC01")) as QueryThemeCombo;
}
}
#region CustomQuery
private QueryTheme GetQueryTheme(string name)
{
if (_combo == null || _combo.UserDefinedQueries == null)
{
return null;
}
foreach (QueryTheme theme in _combo.UserDefinedQueries.Queries)
{
if (theme.Text == name)
{
return theme;
}
}
return null;
}
private void BuildQueryForm()
{
panelCustomFields.Controls.Clear();
if (_combo == null)
{
return;
}
QueryTheme query = GetQueryTheme(_combo.Text);
if (query == null)
{
return;
}
lblQueryName.Text = query.Text;
if (query.PromptDef == null)
{
return;
}
int y = 5;
foreach (DataRow row in query.PromptDef.Rows)
{
System.Windows.Forms.Label label = new System.Windows.Forms.Label();
label.Text = row["Prompt"].ToString() + ":" + (((bool)row["Obliging"]) ? "*" : " ");
label.Location = new System.Drawing.Point(10, y);
label.Size = new Size(150, 21);
label.TextAlign = ContentAlignment.MiddleRight;
panelCustomFields.Controls.Add(label);
Control txtBox = CustomInputControl.Create(row);
if (txtBox == null)
{
continue;
}
txtBox.Location = new System.Drawing.Point(163, y);
txtBox.Size = new Size(190, 21);
txtBox.Name = "txt" + row["ID"].ToString();
panelCustomFields.Controls.Add(txtBox);
y += 26;
}
}
private void QueryCombo_SelectedItemChanged(string text)
{
if (_combo == null)
{
return;
}
if (_combo.ThemeMode == QueryThemeMode.Custom && text != lblQueryName.Text)
{
BuildQueryForm();
}
}
#endregion
}
internal class CustomInputControl
{
static public Control Create(DataRow row)
{
if (row == null)
{
return null;
}
return new CustomQueryTextBox(row);
}
}
internal interface ICustomInputControl
{
string UserText { get; }
}
internal class CustomQueryTextBox : TextBox, ICustomInputControl
{
private int _promptID = -1;
public CustomQueryTextBox(DataRow row)
{
_promptID = (int)row["ID"];
}
#region ICustomInputControl Member
public string UserText
{
get { return this.Text; }
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace API.Model
{
[Table("Inscrit")]
public class Inscrit
{
[Required]
[Key]
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Prenom { get; set; }
[Required]
[MaxLength(50)]
public string Nom { get; set; }
[Required]
[MaxLength(50)]
public string MotDePasse { get; set; }
[Required]
[MaxLength(50)]
public string Login { get; set; }
[Required]
[MaxLength(50)]
public string Email { get; set; }
[ForeignKey("IdRole")]
public Role Role { get; set; }
[Required]
[MaxLength(50)]
public string PathImage { get; set; }
public int IdRole { get; set; }
//
public DateTime DureeValidite { get; set; } //trouver source
[Required]
public int Valide { get; set; } // trouver source
}
} |
using AutoMapper;
using Uintra.Features.Permissions.Models;
using Uintra.Infrastructure.Extensions;
using Umbraco.Core.Models;
namespace Uintra.Features.Permissions.AutoMapperProfiles
{
public class PermissionsAutoMapperProfile : Profile
{
public PermissionsAutoMapperProfile()
{
CreateMap<IMemberGroup, IntranetMemberGroup>()
.ForMember(dst => dst.Id, o => o.MapFrom(el => el.Id))
.ForMember(dst => dst.Name, o => o.MapFrom(el => el.Name));
CreateMap<IntranetMemberGroup, MemberGroupViewModel>()
.ForMember(dst => dst.Id, o => o.MapFrom(el => el.Id))
.ForMember(dst => dst.Name, o => o.MapFrom(el => el.Name));
CreateMap<PermissionManagementModel, PermissionViewModel>()
.ForMember(dst => dst.ActionId, o => o.MapFrom(el => el.SettingIdentity.Action.ToInt()))
.ForMember(dst => dst.ActionName, o => o.MapFrom(el => el.SettingIdentity.Action.GetDisplayName()))
.ForMember(dst => dst.ParentActionId, o => o.MapFrom(el => el.ParentActionType.ToNullableInt()))
.ForMember(dst => dst.ResourceTypeId, o => o.MapFrom(el => el.SettingIdentity.ResourceType.ToInt()))
.ForMember(dst => dst.ResourceTypeName, o => o.MapFrom(el => el.SettingIdentity.ResourceType.GetDisplayName()))
.ForMember(dst => dst.Allowed, o => o.MapFrom(el => el.SettingValues.IsAllowed))
.ForMember(dst => dst.Enabled, o => o.MapFrom(el => el.SettingValues.IsEnabled))
.ForMember(dst => dst.IntranetMemberGroupId, o => o.MapFrom(el => el.Group.Id));
}
}
} |
namespace gView.Framework.Topology
{
public class PlanarGraph
{
Edges _edges = new Edges();
public PlanarGraph(Nodes nodes, Edges edges)
{
_edges = new Edges();
foreach (Edge edge in edges)
{
_edges.Add(new Edge(edge.p1, edge.p2));
_edges.Add(new Edge(edge.p2, edge.p1));
}
_edges.Sort();
}
}
}
|
using FeriaVirtual.Domain.Models.Users.Interfaces;
using FeriaVirtual.Domain.SeedWork.Query;
using System.Threading.Tasks;
namespace FeriaVirtual.Application.Services.Signin.Queries
{
public class SigninQueryHandler
: IQueryHandler<SigninQuery, SigninResponse>
{
private readonly ISessionRepository _repository;
public SigninQueryHandler(ISessionRepository repository)
{
_repository = repository;
}
public async Task<SigninResponse> Handle(SigninQuery query)
{
if (query is null) {
throw new InvalidSigninServiceException("Credenciales de usuario inválidas.");
}
return await ValidateResult(query);
}
private async Task<SigninResponse> ValidateResult(SigninQuery userQuery)
{
var result = await _repository.SignIn<SigninResponse>(userQuery.Username, userQuery.Password);
if (result is null)
throw new InvalidSigninServiceException("Usuario no esta registrado en Feria virtual.");
if (result.IsActive < 0 || result.IsActive > 2)
throw new InvalidSigninServiceException("Usuario no tiene acceso a Feria virtual.");
return result;
}
}
}
|
namespace Ludotek.Api.Dto
{
public class ErreurDto
{
/// <summary>
/// Code Erreur
/// </summary>
public string Code { get; set; }
/// <summary>
/// Libellé erreur
/// </summary>
public string Libelle { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClipModels;
namespace Test
{
class Program
{
static void Main(string[] args)
{
TClipDBContext db = new TClipDBContext();
//TrafficClip clip = db.TClips.Find(48);
//ServiceLayer.AddClipEntryToMusicMaster(clip, MM_REMOTE_ENTERPRISE_STATION_URL, MM_REMOTE_ENTERPRISE_STATION_NAME);
List<EncodingServer> servers = db.EncodingServers.ToList();
int debuggie = 1;
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace starteAlkemy.Models
{
public class Home
{
[Key]
public int Id { get; set; }
public List<Project> ListProject { get; set; }
public List<HomeImages> ListImage { get; set; }
public string WelcomeText { get; set; }
public string MercadoPagoId { get; set; }
public string Cbu { get; set; }
public string Alias { get; set; }
public string NumeroDeCuenta { get; set; }
public string ImageMain { get; set; }
public string BackgroundOurMission { get; set; }
public string BackgroundDonate { get; set; }
public string BackgroundProject { get; set; }
public string TitleOurMission { get; set; }
public string DescOurMission { get; set; }
public string TitleItemOneOurMission { get; set; }
public string TitleItemTwoOurMission { get; set; }
public string TitleItemThreeOurMission { get; set; }
public string DescItemOneOurMission { get; set; }
public string DescItemTwoOurMission { get; set; }
public string DescItemThreeOurMission { get; set; }
}
} |
using ApiSGCOlimpiada.Data.OrcamentoDAO;
using ApiSGCOlimpiada.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using ApiSGCOlimpiada.Data.SolicitacaoCompraDAO;
namespace ApiSGCOlimpiada.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class OrcamentosController : ControllerBase
{
private readonly IOrcamentoDAO dao;
private readonly ISolicitacaoCompraDAO solicitacao;
public OrcamentosController(IOrcamentoDAO dao, ISolicitacaoCompraDAO solicitacao)
{
this.dao = dao;
this.solicitacao = solicitacao;
}
[HttpGet]
public IEnumerable<Orcamento> GetAll()
{
return dao.GetAll();
}
[HttpGet("{id}", Name = "GetOrcamento")]
public IActionResult GetOrcamentoById(long id)
{
var solicitacao = dao.Find(id);
if (solicitacao == null)
return NotFound(new { Message = "Orçamento não encontrado" });
return new ObjectResult(solicitacao);
}
[HttpPost]
public async Task<IActionResult> Create([FromForm] Orcamento orcamento, IFormFile arquivo)
{
if (string.IsNullOrEmpty(orcamento.Fornecedor) && string.IsNullOrEmpty(orcamento.Cnpj)
&& string.IsNullOrEmpty(orcamento.Data.ToString("dd/MM/yyyy HH:mm")) && string.IsNullOrEmpty(orcamento.FormaPagamento))
return BadRequest(new { Message = "Todos os campos são obrigatórios" });
long idSolicitacao = solicitacao.GetAll().Last().Id;
var fileName = await Utils.UploadUtil.UploadAnexosPdfAsync(arquivo, "AnexoOrcamentos", orcamento.Fornecedor, idSolicitacao);
orcamento.Anexo = fileName;
if (dao.Add(orcamento))
return CreatedAtRoute("GetOrcamento", new { id = orcamento.Id }, orcamento);
return BadRequest(new { Message = "Erro interno no servidor" });
}
[HttpPut("{id}")]
public async Task<IActionResult> PutAsync([FromForm] Orcamento orcamento, long id, IFormFile arquivo)
{
if (string.IsNullOrEmpty(orcamento.Fornecedor) && string.IsNullOrEmpty(orcamento.Cnpj)
&& string.IsNullOrEmpty(orcamento.Data.ToString("dd/MM/yyyy HH:mm")) && orcamento.ValorTotal == 0
&& orcamento.TotalIpi == 0 && orcamento.TotalProdutos == 0)
return BadRequest(new { Message = "Todos os campos são obrigatórios" });
long idSolicitacao = solicitacao.GetAll().Last().Id;
var fileName = await Utils.UploadUtil.UploadAnexosPdfAsync(arquivo, "AnexoOrcamentos", orcamento.Fornecedor, idSolicitacao);
if (!string.IsNullOrEmpty(fileName))
{
orcamento.Anexo = fileName.Substring(16);
}
if (dao.Find(id) == null)
return NotFound(new { Message = "Orçamento não encontrado" });
if (dao.Update(orcamento, id))
return CreatedAtRoute("GetOrcamento", new { id = orcamento.Id }, orcamento);
return BadRequest(new { Message = "Erro interno no servidor" });
}
[HttpGet("solicitacao/{id}")]
public IEnumerable<Orcamento> GetByIdSolicitacao(long id)
{
return dao.GetOrcamentoBySolicitacao(id);
}
[HttpGet("download/{filename}")]
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filepart not present");
var path = Path.Combine($@"{Directory.GetCurrentDirectory()}\AnexoOrcamentos", filename);
var memory = new MemoryStream();
using var stream = new FileStream(path, FileMode.Open);
await stream.CopyToAsync(memory);
memory.Position = 0;
var file = File(memory, "application/pdf", Path.GetFileName(path));
return file;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Door : MonoBehaviour, IHackable
{
private Vector3 startPosition;
private Vector3 endPosition;
private bool isOpening = false;
private float t = 0f;
protected void Awake()
{
startPosition = transform.position;
endPosition = startPosition + 1.5f * transform.right;
}
protected void Update()
{
transform.position = Vector3.Lerp(startPosition, endPosition,
(1 - Mathf.Cos(Mathf.PI * t)) / 2f);
if (isOpening && t < 1f)
{
t += Time.deltaTime / 2;
if (t > 1f)
t = 1f;
}
else if (!isOpening && t > 0f)
{
t -= Time.deltaTime / 2;
if (t < 0f)
t = 0f;
}
}
public void Open()
{
isOpening = true;
}
public void Close()
{
isOpening = false;
}
public void Hack()
{
Open();
}
}
|
using UnityEngine;
using System.Collections;
/// <summary>
/// This class is used to hide and show a 2D object in the scene
/// </summary>
public class HideShow : MonoBehaviour {
enum Axis {vertical, horizontal};
private Vector2 hide, show, target;
private RectTransform transf;
[SerializeField]
private bool moving;
public float slideTime, distance, slideTimeLerp;
public bool showed, locked;
[SerializeField] private Axis axis;
// Use this for initialization
void Start ()
{
transf = GetComponent<RectTransform> ();
moving = locked = false;
show = transf.anchoredPosition;
if (axis == Axis.horizontal)
hide = transf.anchoredPosition + Vector2.Scale (transf.sizeDelta, Vector2.right * distance);
else
hide = transf.anchoredPosition + Vector2.Scale (transf.sizeDelta, Vector2.up * distance);
transf.anchoredPosition = target = hide;
slideTime = 0.4f;
slideTimeLerp = 1f;
}
void Update()
{
if (moving)
{
transf.anchoredPosition = Vector2.Lerp(transf.anchoredPosition, target, slideTimeLerp);
slideTimeLerp += Time.unscaledDeltaTime / slideTime;
if (slideTimeLerp > 1f)
moving = false;
}
}
/// <summary>
/// Shows this instance.
/// </summary>
public void Show ()
{
if (!showed && !locked)
{
showed = true;
target = show;
moving = true;
slideTimeLerp = 0;
}
}
/// <summary>
/// Hides this instance.
/// </summary>
public void Hide ()
{
if (showed && !locked)
{
showed = false;
target = hide;
moving = true;
slideTimeLerp = 0;
}
}
/// <summary>
/// Toggles between hidden and showed.
/// </summary>
public void Toggle()
{
if (showed)
Hide();
else
Show();
}
/// <summary>
/// Moves to a relative position.
/// </summary>
/// <param name="posRel">Position relative to showed in percent.</param>
public void MoveTo (float posRel)
{
if (!locked)
{
if (axis == Axis.horizontal)
target = transf.anchoredPosition + Vector2.Scale(transf.sizeDelta, Vector2.right * (1f - 0.01f * posRel));
else
target = transf.anchoredPosition + Vector2.Scale(transf.sizeDelta, Vector2.up * (1f - 0.01f * posRel));
showed = true;
moving = true;
slideTimeLerp = 0;
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using TankStatistics;
public class StatPanel : MonoBehaviour
{
public List<GameObject> placementIcons = new List<GameObject>();
public List<string> placementStrings = new List<string>();
public TextMeshProUGUI username;
public TextMeshProUGUI common;
public TextMeshProUGUI adspecific;
public TextMeshProUGUI score;
public TextMeshProUGUI rank;
public void SetCommonStats(int kills, int shots, int closeCalls, int ADTotal)
{
common.text = $"kills: {kills}\nshots fired: {shots}\nbullets dodged: " +
$"{closeCalls}\n airdrops picked up: {ADTotal}";
}
public void SetUsername(string username)
{
this.username.text = username;
}
public void SetScore(int score)
{
this.score.text = score.ToString();
}
public void SetPlacementIcon(int place)
{
placementIcons[place - 1].SetActive(true);
rank.text = placementStrings[place - 1];
}
public void SetADStats(Stats stat)
{
if (stat.shieldBlocks != 0)
{
adspecific.text += $"bullets blocked by shield: {stat.shieldBlocks}\n";
}
if (stat.landminesCreated != 0)
{
adspecific.text += $"bullets blocked by shield: {stat.shieldBlocks}\n";
}
if (stat.landmineKills != 0)
{
adspecific.text += $"bullets blocked by shield: {stat.shieldBlocks}\n";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using AcessoBancoDados;
using DTO;
namespace Negocios
{
public class CursoNegocios
{
AcessoDadosSqlServer acessoDadosSqlServer = new AcessoDadosSqlServer();
public string Inserir(Curso curso)
{
try
{
acessoDadosSqlServer.LimparParametros();
acessoDadosSqlServer.AdicionarParametros("@CursoNome", curso.CursoNome);
acessoDadosSqlServer.AdicionarParametros("@CursoUnidadeID", Convert.ToInt32(curso.CursoUnidadeID));
string CursoID = acessoDadosSqlServer.ExecutarManipulacao(CommandType.Text, "INSERT INTO tblCurso (CursoNome,CursoUnidadeID) VALUES (@CursoNome,@CursoUnidadeID) SELECT @@IDENTITY AS RETORNO").ToString();
return CursoID;
}
catch (Exception ex)
{
return ex.Message;
}
}
public string Alterar(Curso curso)
{
try
{
acessoDadosSqlServer.LimparParametros();
acessoDadosSqlServer.AdicionarParametros("@CursoID", curso.CursoID);
acessoDadosSqlServer.AdicionarParametros("@CursoNome", curso.CursoNome);
acessoDadosSqlServer.AdicionarParametros("@CursoUnidadeID", Convert.ToInt32(curso.CursoUnidadeID));
string CursoID = acessoDadosSqlServer.ExecutarManipulacao(CommandType.Text, "UPDATE tblCurso SET CursoNome = @CursoNome, CursoUnidadeID = @CursoUnidadeID WHERE CursoID = @CursoID SELECT @CursoID AS RETORNO").ToString();
return CursoID;
}
catch (Exception ex)
{
return ex.Message;
}
}
public string Excluir(Curso curso)
{
try
{
acessoDadosSqlServer.LimparParametros();
acessoDadosSqlServer.AdicionarParametros("@CursoID", curso.CursoID);
string CursoID = acessoDadosSqlServer.ExecutarManipulacao(CommandType.Text, "DELETE FROM tblCurso WHERE CursoID = @CursoID SELECT @CursoID AS RETORNO").ToString();
return CursoID;
}
catch (Exception ex)
{
return ex.Message;
}
}
public CursoColecao ConsultarPorNome(string nome, string unidade)
{
//Criar uma nova coleção de clientes (aqui ela está vazia)
CursoColecao cursoColecao = new CursoColecao();
acessoDadosSqlServer.LimparParametros();
DataTable dataTableCurso;
if (unidade == "")
{
acessoDadosSqlServer.AdicionarParametros("@CursoNome", nome);
dataTableCurso = acessoDadosSqlServer.ExecutarConsulta(CommandType.Text, "SELECT CursoID AS ID, CursoNome AS Curso, UnidadeNome AS Unidade FROM tblCurso INNER JOIN tblUnidade ON CursoUnidadeID = UnidadeID WHERE CursoNome LIKE '%' + @CursoNome + '%'");
}
else
{
acessoDadosSqlServer.AdicionarParametros("@CursoUnidadeID", RetornaIDCurso(unidade));
acessoDadosSqlServer.AdicionarParametros("@CursoNome", nome);
dataTableCurso = acessoDadosSqlServer.ExecutarConsulta(CommandType.Text, "SELECT CursoID AS ID, CursoNome AS Curso, UnidadeNome AS Unidade FROM tblCurso INNER JOIN tblUnidade ON CursoUnidadeID = UnidadeID WHERE (CursoNome LIKE '%' + @CursoNome + '%') and (CursoUnidadeID = @CursoUnidadeID)");
}
//Percorrer o DataTable e transformar em coleção de cliente
//Cada linha do DataTable é um cliente
foreach (DataRow linha in dataTableCurso.Rows)
{
//Criar um cliente vazio
//Colocar os dados da linha dele
//Adicionar ele na coleção
Curso curso = new Curso();
curso.CursoID = Convert.ToInt32(linha["ID"]);
curso.CursoNome = Convert.ToString(linha["Curso"]);
curso.CursoUnidadeNome = Convert.ToString(linha["Unidade"]);
cursoColecao.Add(curso);
}
return cursoColecao;
}
public int RetornaIDCurso (string nome)
{
acessoDadosSqlServer.LimparParametros();
acessoDadosSqlServer.AdicionarParametros("@CursoUnidadeNome", nome);
int ID = Convert.ToInt32(acessoDadosSqlServer.ExecutarManipulacao(CommandType.Text, "SELECT UnidadeID FROM tblUnidade where UnidadeNome LIKE '%' + @CursoUnidadeNome + '%'"));
return ID;
}
public int VerificarUso(int cursoid)
{
acessoDadosSqlServer.LimparParametros();
acessoDadosSqlServer.AdicionarParametros("@CursoID", cursoid);
int verificacao = Convert.ToInt32(acessoDadosSqlServer.ExecutarManipulacao(CommandType.Text, "SELECT TOP 1 CursoID FROM tblCurso INNER JOIN tblAluno ON CursoID = AlunoCursoID WHERE CursoID = @CursoID and AlunoID > '0'"));
return verificacao;
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Level31 : MonoBehaviour
{
public GameObject[] items;
public int currentPhase = 0;
public int touchCounter = 0;
public Vector2 lastTouch;
public Vector2 curTouch;
private void Start()
{
TapListener.ScreenTap += CheckTouch;
}
private void OnDestroy()
{
TapListener.ScreenTap -= CheckTouch;
}
private void CheckTouch(Vector2 touch)
{
curTouch = touch;
touchCounter++;
switch (currentPhase)
{
case 0:
lastTouch = curTouch;
NextPhase();
break;
case 1:
if (curTouch.y < lastTouch.y)
{
lastTouch = curTouch;
if (touchCounter == 1)
{
NextPhase();
}
}
else
{
ResetState();
}
break;
case 2:
if (curTouch.y > lastTouch.y)
{
lastTouch = curTouch;
if (touchCounter == 2)
{
NextPhase();
}
}
else
{
ResetState();
}
break;
case 3:
if (curTouch.x > lastTouch.x)
{
lastTouch = curTouch;
if (touchCounter == 2)
{
NextPhase();
}
}
else
{
ResetState();
}
break;
case 4:
if (curTouch.x < lastTouch.x)
{
lastTouch = curTouch;
if (touchCounter == 3)
{
NextPhase();
}
}
else
{
ResetState();
}
break;
case 5:
if (curTouch.y < lastTouch.y)
{
lastTouch = curTouch;
if (touchCounter == 2)
{
NextPhase();
Debug.Log("Win");
GameManager.instance.NextLevel();
}
}
else
{
ResetState();
}
break;
}
}
private void ResetState()
{
touchCounter = 0;
currentPhase = 0;
Array.ForEach(items, item => item.SetActive(true));
}
private void NextPhase()
{
items[currentPhase].SetActive(false);
currentPhase++;
touchCounter = 0;
}
} |
using Autofac;
using System;
using System.Linq;
using System.Reflection;
namespace CC.Web.Api.Core
{
public class AutofacConfig
{
public static void RegisterObj(ContainerBuilder builder)
{
//注册Service中的组件,Service中的类要以Service结尾,否则注册失败
builder.RegisterAssemblyTypes(GetAssemblyByName("CC.Web.Service")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces().PropertiesAutowired();
//注册Dao中的组件,Dao中的类要以Dao结尾,否则注册失败
builder.RegisterAssemblyTypes(GetAssemblyByName("CC.Web.Dao")).Where(a => a.Name.EndsWith("Dao")).AsImplementedInterfaces().PropertiesAutowired();
}
/// <summary>
/// 根据程序集名称获取程序集
/// </summary>
/// <param name="AssemblyName">程序集名称</param>
/// <returns></returns>
public static Assembly GetAssemblyByName(String AssemblyName)
{
return Assembly.Load(AssemblyName);
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Upgrader.PostgreSql;
namespace Upgrader.Test.PostgreSql
{
[TestClass]
public class PrimaryKeyInfoPostgreSqlTest : PrimaryKeyInfoTest
{
public PrimaryKeyInfoPostgreSqlTest() : base(new PostgreSqlDatabase(AssemblyInitialize.PostgreSqlConnectionString))
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ToolTipToggle : MonoBehaviour
{
public GameObject itemWithText;
public float textVisible = 0f;
// Update is called once per frame
void Update()
{
textVisible = textVisible - Time.deltaTime;
if(textVisible >=0f)
itemWithText.GetComponent<MeshRenderer>().enabled = true;
else
itemWithText.GetComponent<MeshRenderer>().enabled = false;
}
private void OnTriggerStay2D(Collider2D collision)
{
if(collision.tag == "Player")
{
textVisible = 1f;
}
}
}
|
using BimPlus.Sdk.Data.DbCore.Analysis;
using BimPlus.Sdk.Data.DbCore.Structure;
using BimPlus.Sdk.Data.DbCore;
using BimPlus.Sdk.Data.StructuralLoadResource;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using BimPlus.Client;
using BimPlus.Sdk.Data.DbCore.Connection;
using BimPlus.Sdk.Data.TenantDto;
using System;
using System.Drawing;
using BimPlus.Sdk.Data.CSG;
using BimPlus.Sdk.Data.DbCore.Steel;
namespace BimPlusDemo
{
public partial class MainWindow
{
private void Nodes_OnClick(object sender, RoutedEventArgs e)
{
var model = SelectModel("StructuralAnalysis");
if (model?.TopologyDivisionId == null)
return;
var nodes =
IntBase.ApiCore.DtObjects.GetObjects<StructuralPointConnection>(model.TopologyDivisionId.Value);
if (nodes?.Count >= 12)
{
MessageBox.Show("Nodes are already created!");
return;
}
// create some StructuralPointConnection objects
var topologyDivision = new TopologyItem
{
Parent = model.TopologyDivisionId.Value,
Division = model.Id,
LogParentID = model.ProjectId,
Name = "Nodes",
Children = new List<DtObject>(12)
{
new StructuralPointConnection
{
Parent = model.TopologyDivisionId.Value,
Name = "N1",
Division = model.Id,
LogParentID = model.ProjectId,
X = 0.5,
Y = 0.5,
Z = 0.2,
NodeId = 1,
AppliedCondition = new BoundaryNodeCondition("TRigid", true, true, true, true, true, true)
},
new StructuralPointConnection
{
Parent = model.TopologyDivisionId.Value,
Name = "N2",
Division = model.Id,
LogParentID = model.ProjectId,
X = 2.0,
Y = 0.5,
Z = 0.2,
NodeId = 2,
AppliedCondition = new BoundaryNodeCondition("TRigid", false, false, false, true, true, true)
},
new StructuralPointConnection
{
Parent = model.TopologyDivisionId.Value,
Name = "N3",
Division = model.Id,
LogParentID = model.ProjectId,
X = 3.6,
Y = 0.5,
Z = 0.2,
NodeId = 3,
AppliedCondition = new BoundaryNodeCondition("TRigid", true, true, true, false, false, false)
},
new StructuralPointConnection
{
Parent = model.TopologyDivisionId.Value,
Name = "N4",
Division = model.Id,
LogParentID = model.ProjectId,
X = 0.5,
Y = 6.0,
Z = 0.2,
NodeId = 4,
AppliedCondition = new BoundaryNodeCondition("Fixed", 100, 3, 100, 3.5, 1.9, 3.7)
},
new StructuralPointConnection
{
Parent = model.TopologyDivisionId.Value,
Name = "N5",
Division = model.Id,
LogParentID = model.ProjectId,
X = 2.000,
Y = 6.000,
Z = 0.200,
NodeId = 5,
AppliedCondition = new BoundaryNodeCondition("RRidig", false, false, false, true, true, true)
},
new StructuralPointConnection
{
Parent = model.TopologyDivisionId.Value,
Name = "N6",
Division = model.Id,
LogParentID = model.ProjectId,
X = 3.600,
Y = 6.000,
Z = 0.200,
NodeId = 6,
AppliedCondition = new BoundaryNodeCondition("N6", 2.0, true, 3.0, 2.5, false, 4.7)
},
new StructuralPointConnection
{
Parent = model.TopologyDivisionId.Value,
Name = "N7",
Division = model.Id,
LogParentID = model.ProjectId,
X = 0.500,
Y = 0.500,
Z = 3.400,
NodeId = 7
},
new StructuralPointConnection
{
Parent = model.TopologyDivisionId.Value,
Name = "N8",
Division = model.Id,
LogParentID = model.ProjectId,
X = 2.000,
Y = 0.500,
Z = 3.400,
NodeId = 8
},
new StructuralPointConnection
{
Parent = model.TopologyDivisionId.Value,
Name = "N9",
Division = model.Id,
LogParentID = model.ProjectId,
X = 3.600,
Y = 0.500,
Z = 3.400,
NodeId = 9
},
new StructuralPointConnection
{
Parent = model.TopologyDivisionId.Value,
Name = "N10",
Division = model.Id,
LogParentID = model.ProjectId,
X = 0.500,
Y = 6.000,
Z = 4.400,
NodeId = 10
},
new StructuralPointConnection
{
Parent = model.TopologyDivisionId.Value,
Name = "N11",
Division = model.Id,
LogParentID = model.ProjectId,
X = 2.000,
Y = 6.000,
Z = 4.400,
NodeId = 11
},
new StructuralPointConnection
{
Parent = model.TopologyDivisionId.Value,
Name = "N12",
Division = model.Id,
LogParentID = model.ProjectId,
X = 3.600,
Y = 6.000,
Z = 4.400,
NodeId = 12
}
}
};
// ReSharper disable once UnusedVariable
if (IntBase.ApiCore.DtObjects.PostObject(topologyDivision) == null)
MessageBox.Show("could not create geometry object.");
else
IntBase.ApiCore.Projects.ConvertGeometry(model.ProjectId);
IntBase.EventHandlerCore.OnExportStarted(this,
new BimPlusEventArgs {Id = model.ProjectId, Value = "ModelChanged"});
}
private void CurveMember_OnClick_OnClick(object sender, RoutedEventArgs e)
{
var model = SelectModel("StructuralAnalysis");
if (model?.TopologyDivisionId == null)
return;
var nodes =
IntBase.ApiCore.DtObjects.GetObjects<StructuralPointConnection>(model.TopologyDivisionId.Value,
false, false, true);
if (nodes?.Count < 12)
{
MessageBox.Show("Please create at first Node objects");
return;
}
if (nodes == null)
return;
// create some StructuralPointConnection objects
var topologyDivision = new TopologyItem
{
Parent = model.TopologyDivisionId.Value,
Division = model.Id,
LogParentID = model.ProjectId,
Name = "Beams",
Children = new List<DtObject>(13)
{
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B1",
Division = model.Id,
LogParentID = model.ProjectId,
// CurveMember is defined by relation to existing nodes.
// In Ifc you have to use 'RelConnectsStructuralMember' objects to establish this relation.
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R1",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 1)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R2",
AppliedCondition = new BoundaryNodeCondition("", false, false, false, true, true, true),
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 7)?.Id
}
}
},
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B2",
Division = model.Id,
LogParentID = model.ProjectId,
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R3",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 2)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R4",
AppliedCondition = new BoundaryNodeCondition("", false, false, false, true, true, true),
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 8)?.Id
}
}
},
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B3",
Division = model.Id,
LogParentID = model.ProjectId,
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R5",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 3)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R6",
AppliedCondition = new BoundaryNodeCondition("", false, false, false, true, true, true),
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 9)?.Id
}
}
},
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B4",
Division = model.Id,
LogParentID = model.ProjectId,
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R7",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 4)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R8",
AppliedCondition = new BoundaryNodeCondition("", false, false, false, true, true, true),
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 10)?.Id
}
}
},
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B5",
Division = model.Id,
LogParentID = model.ProjectId,
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R5",
AppliedCondition = new BoundaryNodeCondition("", false, false, false, true, true, true),
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 5)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R6",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 11)?.Id
}
}
},
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B6",
Division = model.Id,
LogParentID = model.ProjectId,
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R5",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 6)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R6",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 12)?.Id
}
}
},
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B7",
Division = model.Id,
LogParentID = model.ProjectId,
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R7",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 7)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R8",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 8)?.Id
}
}
},
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B8",
Division = model.Id,
LogParentID = model.ProjectId,
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R9",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 8)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R10",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 9)?.Id
}
}
},
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B9",
Division = model.Id,
LogParentID = model.ProjectId,
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R11",
AppliedCondition = new BoundaryNodeCondition("", false, false, false, true, true, true),
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 10)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R12",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 11)?.Id
}
}
},
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B10",
Division = model.Id,
LogParentID = model.ProjectId,
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R12",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 11)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R13",
AppliedCondition = new BoundaryNodeCondition("", false, false, false, true, true, true),
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 12)?.Id
}
}
},
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B11",
Division = model.Id,
LogParentID = model.ProjectId,
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R14",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 7)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R15",
AppliedCondition = new BoundaryNodeCondition("", false, false, false, true, true, true),
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 10)?.Id
}
}
},
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B12",
Division = model.Id,
LogParentID = model.ProjectId,
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R16",
AppliedCondition = new BoundaryNodeCondition("", false, false, false, true, true, true),
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 8)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R17",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 11)?.Id
}
}
},
new StructuralCurveMember
{
Parent = model.TopologyDivisionId.Value,
Name = "B13",
Division = model.Id,
LogParentID = model.ProjectId,
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "R18",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 9)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "R19",
// each 'RelConnectsStructuralMember' can have own stiffness information.
AppliedCondition =
new BoundaryNodeCondition("Rigid", false, false, false, true, true, true),
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 12)?.Id
}
}
}
}
};
//var json = Newtonsoft.Json.JsonConvert.SerializeObject(topologyDivision);
if (IntBase.ApiCore.DtObjects.PostObject(topologyDivision) == null)
MessageBox.Show("could not create geometry object.");
else
{
IntBase.ApiCore.Projects.ConvertGeometry(model.ProjectId);
IntBase.EventHandlerCore.OnExportStarted(this,
new BimPlusEventArgs {Id = model.ProjectId, Value = "ModelChanged"});
}
}
private void SurfaceMember_OnClick(object sender, RoutedEventArgs e)
{
var model = SelectModel("StructuralAnalysis");
if (model?.TopologyDivisionId == null)
return;
var nodes =
IntBase.ApiCore.DtObjects.GetObjects<StructuralPointConnection>(model.TopologyDivisionId.Value,
false, false, true);
if (nodes?.Count < 12)
{
MessageBox.Show("Please create at first Node objects");
return;
}
if (nodes == null)
return;
var ssm = new TopologyItem
{
Parent = model.TopologyDivisionId.Value,
Division = model.Id,
LogParentID = model.ProjectId,
Name = "Surfaces",
Children = new List<DtObject>(1)
{
new StructuralSurfaceMember
{
Name = "B12",
Division = model.Id,
LogParentID = model.ProjectId,
// surface is defined by relation to existing nodes.
ConnectedBy = new List<RelConnectsStructuralMember>(2)
{
new RelConnectsStructuralMember
{
OrderNumber = 1,
Name = "P1",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 9)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 2,
Name = "P2",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 8)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 3,
Name = "P3",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 11)?.Id
},
new RelConnectsStructuralMember
{
OrderNumber = 4,
Name = "P4",
RelatedStructuralConnection = nodes.Find(x => x.NodeId == 12)?.Id
}
}
}
}
};
//var json = Newtonsoft.Json.JsonConvert.SerializeObject(ssm);
if (IntBase.ApiCore.DtObjects.PostObject(ssm) == null)
MessageBox.Show("could not create geometry object.");
else
{
IntBase.ApiCore.Projects.ConvertGeometry(model.ProjectId);
IntBase.EventHandlerCore.OnExportStarted(this,
new BimPlusEventArgs {Id = model.ProjectId, Value = "ModelChanged"});
}
}
private void Loads_OnClick(object sender, RoutedEventArgs e)
{
var model = SelectModel("StructuralAnalysis");
if (model?.TopologyDivisionId == null)
return;
var nodes =
IntBase.ApiCore.DtObjects.GetObjects<StructuralPointConnection>(model.TopologyDivisionId.Value,
false, false, true);
if (nodes == null || nodes.Count < 12)
{
MessageBox.Show("Please create at first Node objects");
return;
}
var beams =
IntBase.ApiCore.DtObjects.GetObjects<StructuralCurveMember>(model.TopologyDivisionId.Value,
false, false, true);
if (beams == null)
{
MessageBox.Show("Please create at first Beam objects (StructuralCurveMember)");
return;
}
var ceiling = IntBase.ApiCore.DtObjects.GetObjects<StructuralSurfaceMember>(model.TopologyDivisionId.Value,
false, false, true).FirstOrDefault();
var loadCases = CreateDefaultLoadGroups(model);
var constructionLc = loadCases.FirstOrDefault(x => x.Name == "Construction Load")?.IsGroupedBy[0]?.Id;
var ownWeightLc = loadCases.FirstOrDefault(x => x.Name == "Own Weight")?.IsGroupedBy[0]?.Id;
var trafficLc = loadCases.FirstOrDefault(x => x.Name == "Traffic Load")?.IsGroupedBy[0]?.Id;
var snowLc = loadCases.FirstOrDefault(x => x.Name == "Snow Load")?.IsGroupedBy[0]?.Id;
var windxLc = loadCases.FirstOrDefault(x => x.Name == "Wind Load X")?.IsGroupedBy[0]?.Id;
var windyLc = loadCases.FirstOrDefault(x => x.Name == "Wind Load Y")?.IsGroupedBy[0]?.Id;
var cl1 = new StructuralPointAction
{
Parent = model.TopologyDivisionId.Value,
Name = "CA1",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadSingleForce { ForceZ = -6000 },
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "AC1",
RelatingElement = nodes.Find(x => x.NodeId == 7)?.Id
}
}
};
if (constructionLc.HasValue) // add reference to LoadCase 'construction'
cl1.AddProperty(TableNames.tabAttribConstObjInstObj, $"Connection-RelatedElement.1", constructionLc.Value);
var wy1 = new StructuralPointAction
{
Parent = model.TopologyDivisionId.Value,
Name = "Wy1",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadSingleForce { ForceY = -3000 },
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "AC2",
RelatingElement = nodes.Find(x => x.NodeId == 8)?.Id
}
}
};
if (windyLc.HasValue) // add reference to LoadCase Windy'
wy1.AddProperty(TableNames.tabAttribConstObjInstObj, $"Connection-RelatedElement.1", windyLc.Value);
var wx1 = new StructuralPointAction
{
Parent = model.TopologyDivisionId.Value,
Name = "Wx1",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadSingleForce { ForceX = -3000 },
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "AC3",
RelatingElement = nodes.Find(x => x.NodeId == 9)?.Id
}
}
};
if (windxLc.HasValue) // add reference to LoadCase Windx'
wx1.AddProperty(TableNames.tabAttribConstObjInstObj, $"Connection-RelatedElement.1", windxLc.Value);
var ta1 = new StructuralLinearAction
{
Parent = model.TopologyDivisionId.Value,
Name = "TA1",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadConfiguration
{
Values = new List<StructuralLoadOrResult>(2)
{
new StructuralLoadLinearForce {LinearForceZ = -5000},
new StructuralLoadLinearForce {LinearForceZ = -2000}
},
Locations = new List<double>(2) { 200, 4000 }
},
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "RW1",
RelatingElement = beams.Find(x => x.Name == "B12")?.Id
}
}
};
if (trafficLc.HasValue) // add back reference to LoadCase 'traffic'
ta1.AddProperty(TableNames.tabAttribConstObjInstObj, $"Connection-RelatedElement.1", trafficLc.Value);
var wx2 = new StructuralLinearAction
{
Parent = model.TopologyDivisionId.Value,
Name = "Wx2",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadLinearForce { LinearForceX = 2000 },
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "RW2",
RelatingElement = beams.Find(x => x.Name == "B11")?.Id
}
}
};
if (windxLc.HasValue) // add reference to LoadCase 'windX'
wx2.AddProperty(TableNames.tabAttribConstObjInstObj, $"Connection-RelatedElement.2", windxLc.Value);
var wy2 = new StructuralLinearAction
{
Parent = model.TopologyDivisionId.Value,
Name = "Wy2",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadLinearForce { LinearForceY = -3000 },
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "RW3",
RelatingElement = beams.Find(x => x.Name == "B9")?.Id
}
}
};
if (windyLc.HasValue)
wy2.AddProperty(TableNames.tabAttribConstObjInstObj, $"Connection-RelatedElement.2", windyLc.Value);
var sl = new StructuralLinearAction
{
Parent = model.TopologyDivisionId.Value,
Name = "Sl",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadLinearForce { LinearMomentX = 1500 },
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "Sl",
RelatingElement = beams.Find(x => x.Name == "B1")?.Id
}
}
};
if (windyLc.HasValue) // add back reference to LoadCase 'own windY'
sl.AddProperty(TableNames.tabAttribConstObjInstObj, $"Connection-RelatedElement.3", windyLc.Value);
var wy3 = new StructuralLinearAction
{
Parent = model.TopologyDivisionId.Value,
Name = "Wy3",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadTemperature { DeltaTConstant = 25 },
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "RW4",
RelatingElement = beams.Find(x => x.Name == "B10")?.Id
}
}
};
if (snowLc.HasValue) // add back reference to LoadCase 'Snow'
wy3.AddProperty(TableNames.tabAttribConstObjInstObj, $"Connection-RelatedElement.1", snowLc.Value);
// create some StructuralPointConnection objects
var topologyDivision = new TopologyItem
{
Parent = model.TopologyDivisionId.Value,
Division = model.Id,
LogParentID = model.ProjectId,
Name = "Loads",
Children = new List<DtObject>(7)
{
cl1,
wy1,
wx1,
ta1,
wx2,
wy2,
sl,
wy3
}
};
if (ceiling != null)
{
var ow = new StructuralPlanarAction
{
Parent = model.TopologyDivisionId.Value,
Name = "OW",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadPlanarForce { PlanarForceZ = 400 },
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "Ow",
RelatingElement = ceiling.Id
}
}
};
if (ownWeightLc.HasValue) // add back reference to Loadcase 'own weight'
ow.AddProperty(TableNames.tabAttribConstObjInstObj, $"Connection-RelatedElement.1",
ownWeightLc.Value);
topologyDivision.AddChild(ow);
}
// ReSharper disable once UnusedVariable
var json = Newtonsoft.Json.JsonConvert.SerializeObject(topologyDivision);
if (IntBase.ApiCore.DtObjects.PostObject(topologyDivision) == null)
MessageBox.Show("could not create geometry object.");
else
{
IntBase.ApiCore.Projects.ConvertGeometry(model.ProjectId);
IntBase.EventHandlerCore.OnExportStarted(this,
new BimPlusEventArgs { Id = model.ProjectId, Value = "ModelChanged" });
}
}
private List<StructuralLoadCase> CreateDefaultLoadGroups(DtoDivision model)
{
if (!model.TopologyDivisionId.HasValue)
return new List<StructuralLoadCase>();
var loadCaseRelations =
IntBase.ApiCore.DtObjects.GetObjects<StructuralLoadCase>(model.TopologyDivisionId.Value, false, false, true) ?? new List<StructuralLoadCase>();
if (loadCaseRelations.Count >= 5)
return loadCaseRelations;
var ow = Guid.NewGuid();
var cl = Guid.NewGuid();
var tl = Guid.NewGuid();
var sl = Guid.NewGuid();
var wlx = Guid.NewGuid();
var wly = Guid.NewGuid();
var loadCases = new TopologyItem
{
Parent = model.TopologyDivisionId.Value,
Name = "LoadCases",
Division = model.Id,
LogParentID = model.ProjectId,
Children = new List<DtObject>(13)
{
new StructuralLoadCase
{
Id = ow,
Name = "Own Weight",
Division = model.Id,
LogParentID = model.ProjectId,
IsGroupedBy = new List<RelAssignsToGroup>(1)
{
new RelAssignsToGroup
{
Name = "OW"
}
}
},
new StructuralLoadCase
{
Id = cl,
Name = "Construction Load",
Division = model.Id,
LogParentID = model.ProjectId,
IsGroupedBy = new List<RelAssignsToGroup>(1)
{
new RelAssignsToGroup
{
Name = "CL"
// ,RelatedObjects = new List<Guid>(1) { loads.Find(x => x.Name == "CA1").Id }
}
}
},
new StructuralLoadCase
{
Id = tl,
Name = "Traffic Load",
Division = model.Id,
LogParentID = model.ProjectId,
IsGroupedBy = new List<RelAssignsToGroup>(1)
{
new RelAssignsToGroup
{
Name = "TL"
// ,RelatedObjects = new List<Guid>(1) { loads.Find(x => x.Name == "TA1").Id }
}
}
},
new StructuralLoadCase
{
Id = sl,
Name = "Snow Load",
Division = model.Id,
LogParentID = model.ProjectId,
IsGroupedBy = new List<RelAssignsToGroup>(1)
{
new RelAssignsToGroup
{
Name = "SL"
}
}
},
new StructuralLoadCase
{
Id = wlx,
Name = "Wind Load X",
Division = model.Id,
LogParentID = model.ProjectId,
IsGroupedBy = new List<RelAssignsToGroup>(1)
{
new RelAssignsToGroup
{
Name = "WLx"
//,RelatedObjects = (from load in loads where load.Name.Contains("Wx") select load.Id).ToList()
}
}
},
new StructuralLoadCase
{
Id = wly,
Name = "Wind Load Y",
Division = model.Id,
LogParentID = model.ProjectId,
IsGroupedBy = new List<RelAssignsToGroup>(1)
{
new RelAssignsToGroup
{
Name = "WLy"
//,RelatedObjects = (from load in loads where load.Name.Contains("Wy") select load.Id).ToList()
}
}
},
new StructuralLoadGroup
{
Parent = model.TopologyDivisionId.Value,
Name = "LoadCombination O+C",
Description = "Combination with ownWeight and construction load",
Division = model.Id,
LogParentID = model.ProjectId,
IsGroupedBy = new List<RelAssignsToGroup>(1)
{
new RelAssignsToGroup
{
Name = "O+C",
RelatedObjects = new List<Guid>(2) { ow, cl}
}
}
},
new StructuralLoadGroup
{
Parent = model.TopologyDivisionId.Value,
Name = "LoadCombination O+C+T",
Description = "Combination with ownWeight, construction load and traffic load",
Division = model.Id,
LogParentID = model.ProjectId,
IsGroupedBy = new List<RelAssignsToGroup>(1)
{
new RelAssignsToGroup
{
Name = "O+C+T",
RelatedObjects = new List<Guid>(3) { ow, cl, tl}
}
}
},
new StructuralLoadGroup
{
Parent = model.TopologyDivisionId.Value,
Name = "LoadCombination O+C+T+Wx",
Description = "Combination with ownWeight, construction load, traffic load and windX load",
Division = model.Id,
LogParentID = model.ProjectId,
IsGroupedBy = new List<RelAssignsToGroup>(1)
{
new RelAssignsToGroup
{
Name = "O+C+T+Wx",
RelatedObjects = new List<Guid>(3)
{ow, cl, tl, wlx}
}
}
},
new StructuralLoadGroup
{
Parent = model.TopologyDivisionId.Value,
Name = "LoadCombination O+C+T+Wy",
Description = "Combination with ownWeight, construction load, traffic load and windY load",
Division = model.Id,
LogParentID = model.ProjectId,
IsGroupedBy = new List<RelAssignsToGroup>(1)
{
new RelAssignsToGroup
{
Name = "O+C+T+Wy",
RelatedObjects = new List<Guid>(3)
{ow, cl, tl, wly}
}
}
},
new StructuralLoadGroup
{
Parent = model.TopologyDivisionId.Value,
Name = "Ultimate Limit",
Description = "Combination with all existing load groups",
Division = model.Id,
LogParentID = model.ProjectId,
IsGroupedBy = new List<RelAssignsToGroup>(1)
{
new RelAssignsToGroup
{
Name = "UL",
RelatedObjects = new List<Guid>(3)
{
ow, cl, tl, wlx, wly,sl
}
}
}
}
}
};
//var json = Newtonsoft.Json.JsonConvert.SerializeObject(loadCases);
var loadCaseTopologyNode = IntBase.ApiCore.DtObjects.PostObject(loadCases);
loadCaseRelations = loadCaseTopologyNode.Children.OfType<StructuralLoadCase>().ToList();
if (loadCaseRelations.Count > 5)
{
MessageBox.Show($"LoadCases in Node {loadCaseTopologyNode.Name} created");
}
return loadCaseRelations;
}
private void Results_OnClick(object sender, RoutedEventArgs e)
{
var model = SelectModel("StructuralAnalysis");
if (model?.TopologyDivisionId == null)
return;
var nodes =
IntBase.ApiCore.DtObjects.GetObjects<StructuralPointConnection>(model.TopologyDivisionId.Value,
false, false, true);
if (nodes == null || nodes.Count < 12)
{
MessageBox.Show("Please create at first Node objects");
return;
}
var beams =
IntBase.ApiCore.DtObjects.GetObjects<StructuralCurveMember>(model.TopologyDivisionId.Value,
false, false, true);
if (beams == null)
{
MessageBox.Show("Please create at first Beam objects (StructuralCurveMember)");
return;
}
if (nodes == null)
return;
// create some StructuralPointReaction objects
var topologyDivision = new TopologyItem
{
Parent = model.TopologyDivisionId.Value,
Division = model.Id,
LogParentID = model.ProjectId,
Name = "Reactions",
Children = new List<DtObject>(13)
{
new StructuralPointReaction
{
Parent = model.TopologyDivisionId.Value,
Name = "S1",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadSingleForce
{
ForceX = 300,
ForceY = 0,
ForceZ = 1800
},
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "AC1",
RelatingElement = nodes.Find(x => x.NodeId == 1)?.Id
}
}
},
new StructuralPointReaction
{
Parent = model.TopologyDivisionId.Value,
Name = "S2",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadSingleForce
{
ForceX = 500,
ForceY = 100,
ForceZ = 200
},
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "AC2",
RelatingElement = nodes.Find(x => x.NodeId == 2)?.Id
}
}
},
new StructuralPointReaction
{
Parent = model.TopologyDivisionId.Value,
Name = "S3",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadSingleForce
{
ForceX = 100,
ForceY = 1800,
ForceZ = 700
},
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "AC3",
RelatingElement = nodes.Find(x => x.NodeId == 3)?.Id
}
}
},
new StructuralPointReaction
{
Parent = model.TopologyDivisionId.Value,
Name = "S5",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadSingleDisplacement
{
DisplacementX = 3,
DisplacementY = 4,
DisplacementZ = 2,
RotationalDisplacementRX = 5.4,
RotationalDisplacementRY = 4.8,
RotationalDisplacementRZ = 16.5
},
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "AC4",
RelatingElement = nodes.Find(x => x.NodeId == 5)?.Id
}
}
},
new StructuralCurveReaction
{
Parent = model.TopologyDivisionId.Value,
Name = "R6",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadConfiguration
{
Values = new List<StructuralLoadOrResult>(2)
{
new StructuralLoadLinearForce {LinearForceX = -3000},
new StructuralLoadLinearForce {LinearForceX = 3000}
},
Locations = new List<double>(2) { 0, 4200 }
},
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "AC6",
RelatingElement = beams.Find(x => x.Name == "B5")?.Id
}
}
},
new StructuralCurveReaction
{
Parent = model.TopologyDivisionId.Value,
Name = "R4",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadConfiguration
{
Values = new List<StructuralLoadOrResult>(2)
{
new StructuralLoadLinearForce {LinearForceX = -3000, LinearForceY = -500},
new StructuralLoadLinearForce {LinearForceX = 3000, LinearForceY = 500}
},
Locations = new List<double>(2) { 0, 4200 }
},
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "AC6",
RelatingElement = beams.Find(x => x.Name == "B4")?.Id
}
}
},
new StructuralPointReaction
{
Parent = model.TopologyDivisionId.Value,
Name = "S6",
Division = model.Id,
LogParentID = model.ProjectId,
AppliedLoad = new StructuralLoadSingleDisplacement
{
RotationalDisplacementRX = 25.4,
RotationalDisplacementRY = 14.8,
RotationalDisplacementRZ = 06.5
},
AssignedToStructuralItem = new List<RelConnectsStructuralActivity>(1)
{
new RelConnectsStructuralActivity
{
Name = "AC6",
RelatingElement = nodes.Find(x => x.NodeId == 6)?.Id
}
}
}
}
}; // ReSharper disable once UnusedVariable
var json = Newtonsoft.Json.JsonConvert.SerializeObject(topologyDivision);
if (IntBase.ApiCore.DtObjects.PostObject(topologyDivision) == null)
MessageBox.Show("could not create geometry object.");
else
{
IntBase.ApiCore.Projects.ConvertGeometry(model.ProjectId);
IntBase.EventHandlerCore.OnExportStarted(this,
new BimPlusEventArgs { Id = model.ProjectId, Value = "ModelChanged" });
}
}
private void Assemblies_OnClick(object sender, RoutedEventArgs e)
{
var model = SelectModel("StructuralAnalysis");
if (model?.TopologyDivisionId == null)
return;
var nodes =
IntBase.ApiCore.DtObjects.GetObjects<StructuralPointConnection>(model.TopologyDivisionId.Value,
false, false, true);
if (nodes == null || nodes.Count < 12)
{
MessageBox.Show("Please create at first Node objects");
return;
}
var node3 = nodes.Find(x => x.NodeId == 3);
var node6 = nodes.Find(x => x.NodeId == 6);
var node9 = nodes.Find(x => x.NodeId == 9);
var node12 = nodes.Find(x => x.NodeId == 12);
if (node12 == null || node3 == null || node6 == null || node9 == null)
{
MessageBox.Show("Can't identify nodes");
return;
}
var beams =
IntBase.ApiCore.DtObjects.GetObjects<StructuralCurveMember>(model.ProjectId, false, false, true);
if (beams == null)
{
MessageBox.Show("Please create at first Beam objects (StructuralCurveMember)");
return;
}
var topologyDivision = new TopologyItem
{
Parent = model.TopologyDivisionId.Value,
Name = "SteelAssemblies",
Division = model.Id,
LogParentID = model.ProjectId
};
// create some assemblies with relation to StructuralCurveMembers
var assembly1 = new ElementAssembly
{
Name = "B3_Column",
Parent = model.TopologyDivisionId,
Division = model.Id,
LogParentID = IntBase.CurrentProject.Id,
CsgTree = new DtoCsgTree { Color = (uint)Color.MediumBlue.ToArgb() },
Connections = new List<ConnectionElement>
{
new RelConnectsElements
{
Parent = model.ProjectId,
Name = "Relation_B3_Assembly",
OrderNumber = 3,
RelatedElement = beams.Find(x => x.Name == "B3")?.Id
}
}
};
assembly1.CsgTree.Elements.Add(new Path
{
Geometry = new List<CsgGeoElement>
{
new StartPolygon {Point = new List<double> {node3.X.GetValueOrDefault()*1000, node3.Y.GetValueOrDefault() * 1000, node3.Z.GetValueOrDefault()*1000}},
new Line {Point = new List<double> {node9.X.GetValueOrDefault() * 1000, node9.Y.GetValueOrDefault() * 1000, node9.Z.GetValueOrDefault()*1000}}
},
CrossSection = "HEB120"
});
topologyDivision.AddChild(assembly1);
var assembly2 = new ElementAssembly
{
Name = "B6_Column",
Parent = model.TopologyDivisionId,
Division = model.Id,
LogParentID = IntBase.CurrentProject.Id,
CsgTree = new DtoCsgTree { Color = (uint)Color.MediumBlue.ToArgb() },
Connections = new List<ConnectionElement>
{
new RelConnectsElements
{
Parent = model.ProjectId,
Name = "Relation_B6_Assembly",
OrderNumber = 6,
RelatedElement = beams.Find(x => x.Name == "B6")?.Id
}
}
};
assembly2.CsgTree.Elements.Add(new Path
{
Rotation = Math.PI / 2,
Geometry = new List<CsgGeoElement>
{
new StartPolygon {Point = new List<double> {node6.X.GetValueOrDefault() * 1000, node6.Y.GetValueOrDefault() * 1000, node6.Z.GetValueOrDefault()*1000}},
new Line {Point = new List<double> {node12.X.GetValueOrDefault() * 1000, node12.Y.GetValueOrDefault() * 1000, node12.Z.GetValueOrDefault()*1000}}
},
CrossSection = "HEB120"
});
topologyDivision.AddChild(assembly2);
var assembly3 = new ElementAssembly
{
Name = "B13_Column",
Parent = model.TopologyDivisionId,
Division = model.Id,
LogParentID = IntBase.CurrentProject.Id,
CsgTree = new DtoCsgTree { Color = (uint)Color.CornflowerBlue.ToArgb() },
Connections = new List<ConnectionElement>
{
new RelConnectsElements
{
Parent = model.ProjectId,
Name = "Relation_B13_Assembly",
OrderNumber = 13,
RelatedElement = beams.Find(x => x.Name == "B13")?.Id
}
}
};
assembly3.CsgTree.Elements.Add(new Path
{
OffsetX = 30,
OffsetY = -50,
Geometry = new List<CsgGeoElement>
{
new StartPolygon {Point = new List<double> {node9.X.GetValueOrDefault() * 1000, node9.Y.GetValueOrDefault() * 1000, node9.Z.GetValueOrDefault()*1000}},
new Line {Point = new List<double> {node12.X.GetValueOrDefault() * 1000, node12.Y.GetValueOrDefault() * 1000, node12.Z.GetValueOrDefault()*1000}}
},
CrossSection = "UPE100"
});
topologyDivision.AddChild(assembly3);
var assembly4 = new ElementAssembly
{
Name = "B13_ColumnB",
Parent = model.TopologyDivisionId,
Division = model.Id,
LogParentID = IntBase.CurrentProject.Id,
CsgTree = new DtoCsgTree { Color = (uint)Color.CornflowerBlue.ToArgb() },
Connections = new List<ConnectionElement>
{
new RelConnectsElements
{
Parent = model.ProjectId,
Name = "Relation_B13_Assembly",
OrderNumber = 12,
RelatedElement = beams.Find(x => x.Name == "B13")?.Id
}
}
};
assembly4.CsgTree.Elements.Add(new Path
{
Rotation = Math.PI,
OffsetX = 30,
OffsetY = 50,
Geometry = new List<CsgGeoElement>
{
new StartPolygon {Point = new List<double> {node9.X.GetValueOrDefault() * 1000, node9.Y.GetValueOrDefault() * 1000, node9.Z.GetValueOrDefault()*1000}},
new Line {Point = new List<double> {node12.X.GetValueOrDefault() * 1000, node12.Y.GetValueOrDefault() * 1000, node12.Z.GetValueOrDefault()*1000}}
},
CrossSection = "UPE100"
});
topologyDivision.AddChild(assembly4);
var json = Newtonsoft.Json.JsonConvert.SerializeObject(topologyDivision);
if (IntBase.ApiCore.DtObjects.PostObject(topologyDivision) == null)
MessageBox.Show("could not create geometry object.");
else
{
IntBase.ApiCore.Projects.ConvertGeometry(model.ProjectId);
IntBase.EventHandlerCore.OnExportStarted(this,
new BimPlusEventArgs { Id = model.ProjectId, Value = "ModelChanged" });
}
}
}
}
|
using System;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Parts;
using DFC.ServiceTaxonomy.GraphSync.Models;
using Newtonsoft.Json.Linq;
namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Parts
{
public class GraphSyncPartGraphSyncer : ContentPartGraphSyncer, IGraphSyncPartGraphSyncer
{
public override int Priority { get => int.MaxValue; }
public override string PartName => nameof(GraphSyncPart);
public override Task AddSyncComponents(JObject content, IGraphMergeContext context)
{
object? idValue = context.SyncNameProvider.GetNodeIdPropertyValue(content, context.ContentItemVersion);
if (idValue != null)
{
// id is added as a special case as part of SyncAllowed,
// so we allow an overwrite, which will occur as part of syncing
//todo: something cleaner
context.MergeNodeCommand.Properties[context.SyncNameProvider.IdPropertyName()] = idValue;
//context.MergeNodeCommand.Properties.Add(context.SyncNameProvider.IdPropertyName(), idValue);
}
return Task.CompletedTask;
}
public override async Task MutateOnClone(JObject content, ICloneContext context)
{
string newIdPropertyValue = await context.SyncNameProvider.GenerateIdPropertyValue(context.ContentItem.ContentType);
//todo: which is the best way? if we want to use Alter, we'd have to pass the part, rather than content
// (so that named parts work, where >1 type of part is in a content type)
content[nameof(GraphSyncPart.Text)] = newIdPropertyValue;
//context.ContentItem.Alter<GraphSyncPart>(p => p.Text = newIdPropertyValue);
}
public override Task<(bool validated, string failureReason)> ValidateSyncComponent(
JObject content,
IValidateAndRepairContext context)
{
//todo: assumes string id
return Task.FromResult(context.GraphValidationHelper.ContentPropertyMatchesNodeProperty(
context.SyncNameProvider.ContentIdPropertyName,
content,
context.SyncNameProvider.IdPropertyName(),
context.NodeWithRelationships.SourceNode!,
(contentValue, nodeValue) =>
{
if (nodeValue is JValue {Type: JTokenType.String} nodeValueToken)
{
nodeValue = nodeValueToken.ToObject<string>()!;
}
if (!(nodeValue is string nodeValueString))
{
return false;
}
var leftValue = ((string)contentValue!)
.Replace("<<contentapiprefix>>", string.Empty);
var rightValue = context.SyncNameProvider.IdPropertyValueFromNodeValue(nodeValueString, context.ContentItemVersion)
.Replace("<<contentapiprefix>>", string.Empty);
if (Uri.TryCreate(rightValue, UriKind.Absolute, out var rightValueUri))
{
rightValue = rightValueUri.PathAndQuery.Replace("/api/execute", string.Empty);
}
return Equals(leftValue, rightValue);
}));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task5_Matrix
{
public struct Matrix
{
/// <summary>
/// Matrix -> 2D massive
/// </summary>
public int[,] Massive { get; set; }
public int RowCount {
get
{
if (this.Massive == null)
return 0;
return this.Massive.GetLength(0);
}
}
public int ColumnCount
{
get
{
if (this.Massive == null)
return 0;
return this.Massive.GetLength(1);
}
}
/// <summary>
/// Matrix sum
/// </summary>
/// <param name="leftMatrix"></param>
/// <param name="rightMatrix"></param>
/// <returns>Summed matrix</returns>
public static Matrix operator +(Matrix leftMatrix, Matrix rightMatrix)
{
if(leftMatrix == rightMatrix)
{
Matrix summedMatrix = new Matrix
{
Massive = new int[leftMatrix.ColumnCount, leftMatrix.RowCount]
};
for (int i = 0; i < leftMatrix.RowCount; i++)
{
for (int j = 0; j < leftMatrix.ColumnCount; j++)
{
summedMatrix.Massive[i,j] = leftMatrix.Massive[i, j] + rightMatrix.Massive[i, j];
}
}
return summedMatrix;
}
throw new ArgumentException("Размерность матриц не совпадает");
}
/// <summary>
/// Matrix diff
/// </summary>
/// <param name="leftMatrix"></param>
/// <param name="rightMatrix"></param>
/// <returns>Matrix diff</returns>
public static Matrix operator -(Matrix leftMatrix, Matrix rightMatrix)
{
if (leftMatrix == rightMatrix)
{
Matrix newMatrix = new Matrix
{
Massive = new int[leftMatrix.ColumnCount, leftMatrix.RowCount]
};
for (int i = 0; i < leftMatrix.RowCount; i++)
{
for (int j = 0; j < leftMatrix.ColumnCount; j++)
{
newMatrix.Massive[i, j] = leftMatrix.Massive[i, j] - rightMatrix.Massive[i, j];
}
}
return newMatrix;
}
throw new ArgumentException("Размерность матриц не совпадает");
}
/// <summary>
/// Matrix Multiply
/// </summary>
/// <param name="leftMatrix"></param>
/// <param name="rightMatrix"></param>
/// <returns>Matrix mult</returns>
public static Matrix operator *(Matrix leftMatrix, Matrix rightMatrix)
{
if (leftMatrix.ColumnCount == rightMatrix.RowCount)
{
Matrix newMatrix = new Matrix
{
Massive = new int[leftMatrix.ColumnCount, leftMatrix.RowCount]
};
for (int i = 0; i < leftMatrix.RowCount; i++)
{
for (int j = 0; j < rightMatrix.ColumnCount; j++)
{
int s = 0;
for (int z = 0; z < leftMatrix.ColumnCount; ++z)
s += leftMatrix.Massive[i, z] * rightMatrix.Massive[z, j];
newMatrix.Massive[i, j] = s;
}
}
return newMatrix;
}
throw new ArgumentException("Размерность матриц не совпадает");
}
/// <summary>
/// Compare 2 matrices
/// </summary>
/// <param name="leftMatrix"></param>
/// <param name="rightMatrix"></param>
/// <returns>Equal or not in bool</returns>
public static bool operator ==(Matrix leftMatrix, Matrix rightMatrix)
{
if (leftMatrix.ColumnCount == rightMatrix.ColumnCount && leftMatrix.RowCount == rightMatrix.RowCount)
return true;
return false;
}
/// <summary>
/// Compare 2 matrices
/// </summary>
/// <param name="leftMatrix"></param>
/// <param name="rightMatrix"></param>
/// <returns>Equal or not in bool</returns>
public static bool operator !=(Matrix leftMatrix, Matrix rightMatrix)
{
if (leftMatrix.ColumnCount == rightMatrix.ColumnCount && leftMatrix.RowCount == rightMatrix.RowCount)
return false;
return true;
}
/// <summary>
/// Matrix * vector
/// </summary>
/// <param name="matrix"></param>
/// <param name="vector"></param>
/// <returns>Matrix</returns>
public static Matrix operator *(Matrix matrix, Vector vector)
{
int vectorSize = vector.Massive.Length;
int matrixColumnSize = matrix.ColumnCount;
if(matrixColumnSize != vectorSize) {
throw new ArgumentException("Размерности не подходят для умножения");
}
Matrix newMatrix = new Matrix
{
Massive = new int[matrix.ColumnCount, matrix.RowCount]
};
for (int i = 0; i < matrix.RowCount; i++)
{
for (int j = 0; j < matrix.ColumnCount; j++)
{
newMatrix.Massive[i, j] = matrix.Massive[i, j] * vector.Massive[j];
}
}
return newMatrix;
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return true;
}
public override int GetHashCode()
{
return (this.ColumnCount << 2) ^ this.RowCount/3;
}
}
}
|
using System;
namespace Infrostructure.Exeption
{
public class InvalidWattageMeasureValueException :Exception
{
public InvalidWattageMeasureValueException(string message = "مقدار خالی وارد شده است") : base(message) { }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Enums;
using Alabo.Domains.Repositories;
using Alabo.Domains.Services;
using Alabo.Extensions;
using Alabo.Framework.Core.Admins.Configs;
using Alabo.Framework.Core.Enums.Enum;
using Alabo.Industry.Cms.Articles.Domain.Entities;
using MongoDB.Bson;
namespace Alabo.Industry.Cms.Articles.Domain.Services {
public class ChannelService : ServiceBase<Channel, ObjectId>, IChannelService {
public ChannelService(IUnitOfWork unitOfWork, IRepository<Channel, ObjectId> repository) : base(unitOfWork,
repository) {
}
/// <summary>
/// 获取频道分类类型
/// </summary>
/// <param name="channel"></param>
public Type GetChannelClassType(Channel channel) {
var fullName =
$"Alabo.App.Cms.Articles.Domain.CallBacks.Channel{channel.ChannelType.ToString()}ClassRelation";
// string fullName = $"Alabo.App.Cms.Articles.Domain.CallBacks.ChannelArticleCalssRelation";
var type = fullName.GetTypeByFullName();
return type;
}
/// <summary>
/// 获取频道标签类型
/// </summary>
/// <param name="channel"></param>
public Type GetChannelTagType(Channel channel) {
var fullName =
$"Alabo.App.Cms.Articles.Domain.CallBacks.Channel{channel.ChannelType.ToString()}TagRelation";
var type = fullName.GetTypeByFullName();
return type;
}
public bool Check(string script) {
// return Repository.IsHavingData(script);
return false;
}
public List<DataField> DataFields(string channelId) {
var channel = GetSingle(r => r.Id == channelId.ToObjectId());
if (channel != null) {
var list = channel.FieldJson.DeserializeJson<List<DataField>>();
return list;
}
return null;
}
public void InitialData() {
var list = GetList();
if (!list.Any()) {
var channelTypeEnum = typeof(ChannelType);
foreach (var channelTypeName in Enum.GetNames(channelTypeEnum)) {
var channelType = (ChannelType)Enum.Parse(channelTypeEnum, channelTypeName);
if (channelType >= 0) {
var channel = new Channel {
ChannelType = channelType,
Name = channelType.GetDisplayName(),
Status = Status.Normal,
Id = channelType.GetFieldAttribute().GuidId.ToObjectId(),
Icon = channelType.GetFieldAttribute().Icon
};
AddOrUpdate(channel, false);
}
}
}
}
public ObjectId GetChannelId(ChannelType channelType) {
switch (channelType) {
case ChannelType.Article:
return ChannelType.Article.GetFieldAttribute().GuidId.ToSafeObjectId();
case ChannelType.Comment:
return ChannelType.Comment.GetFieldAttribute().GuidId.ToSafeObjectId();
case ChannelType.Video:
return ChannelType.Video.GetFieldAttribute().GuidId.ToSafeObjectId();
case ChannelType.Images:
return ChannelType.Images.GetFieldAttribute().GuidId.ToSafeObjectId();
case ChannelType.Down:
return ChannelType.Down.GetFieldAttribute().GuidId.ToSafeObjectId();
case ChannelType.Question:
return ChannelType.Question.GetFieldAttribute().GuidId.ToSafeObjectId();
case ChannelType.Help:
return ChannelType.Help.GetFieldAttribute().GuidId.ToSafeObjectId();
case ChannelType.Job:
return ChannelType.Job.GetFieldAttribute().GuidId.ToSafeObjectId();
case ChannelType.TopLine:
return ChannelType.TopLine.GetFieldAttribute().GuidId.ToSafeObjectId();
case ChannelType.Message:
return ChannelType.Message.GetFieldAttribute().GuidId.ToSafeObjectId();
case ChannelType.UserNotice:
return ChannelType.UserNotice.GetFieldAttribute().GuidId.ToSafeObjectId();
}
return ChannelType.Article.GetFieldAttribute().GuidId.ToSafeObjectId();
}
}
} |
using EnumsNET;
using Model.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Data;
namespace Resources.Converters
{
public class EnumTypeToDescriptionsListConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
List<string> OrientationList = new List<string>();
if(value != null && value is OrientationTypes)
{
Type orientation = value.GetType();
Array enumValues = orientation.GetEnumValues();
foreach (var element in enumValues)
{
string description = element.ToString();
OrientationList.Add(description);
}
}
return OrientationList;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
List<string> OrientationList = new List<string>();
if (value != null && value is OrientationTypes)
{
Type orientation = value.GetType();
Array enumValues = orientation.GetEnumValues();
foreach (var element in enumValues)
{
string description = element.ToString();
OrientationList.Add(description);
}
}
return OrientationList;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using Properties.Controllers;
using Properties.Core.Interfaces;
using Properties.Core.Objects;
using Properties.Tests.Helper;
namespace Properties.Tests.UnitTests.Controllers
{
[TestFixture]
// ReSharper disable once InconsistentNaming
public class VideosController_TestFixture
{
private readonly Mock<IVideoService> _mockVideoService = new Mock<IVideoService>();
private VideosController _videosController;
[SetUp]
public void Setup()
{
_videosController =
ControllerHelper.GetInitialisedVideosController(_mockVideoService.Object);
AutoMapperConfig.Bootstrap();
}
[Test]
public void VideosController_NullVideoService_ThrowsException()
{
//act
Assert.Throws<ArgumentNullException>(() => new VideosController(null));
}
[Test]
public void GetPropertyVideos_EmptyPropertyReference_ThrowsException()
{
//act
Assert.Throws<ArgumentNullException>(() => _videosController.GetPropertyVideos(string.Empty));
}
[Test]
public void GetPropertyVideos_CallsVideosServices()
{
//arrange
const string reference = "ABCD1234";
_mockVideoService.ResetCalls();
_mockVideoService.Setup(x => x.GetVideosForProperty(reference)).Returns(new List<Video>());
//act
var result = _videosController.GetPropertyVideos(reference);
//assert
_mockVideoService.Verify(x => x.GetVideosForProperty(reference), Times.Once);
}
[Test]
public void GetPropertyVideo_EmptyPropertyReference_ThrowsException()
{
//arrange
const string reference = "ABCD1234";
//act
Assert.Throws<ArgumentNullException>(() => _videosController.GetPropertyVideo(string.Empty, reference));
}
[Test]
public void GetPropertyVideo_EmptyVideoReference_ThrowsException()
{
//arrange
const string reference = "ABCD1234";
//act
Assert.Throws<ArgumentNullException>(() => _videosController.GetPropertyVideo(reference, string.Empty));
}
[Test]
public void GetPropertyVideo_CallsVideosService()
{
//arrange
const string reference = "ABCD1234";
//act
var result = _videosController.GetPropertyVideo(reference, reference);
//assert
_mockVideoService.Verify(x => x.GetVideoForProperty(reference, reference), Times.Once);
}
[Test]
public void Post_EmptyPropertyReference_ThrowsException()
{
//act
Assert.Throws<ArgumentNullException>(() => _videosController.PostVideo(string.Empty, new Models.Video()));
}
[Test]
public void Post_NullVideo_ThrowsException()
{
//arrange
const string reference = "ABCD1234";
//act
Assert.Throws<ArgumentNullException>(() => _videosController.PostVideo(reference, null));
}
[Test]
public void Post_Video_VideoServiceSucceeds_Returns201CreatedAndLocationHeader()
{
//arrange
const string reference = "ABCD1234";
_mockVideoService.ResetCalls();
_mockVideoService.Setup(x => x.CreateVideo(reference, It.IsAny<Video>())).Returns(reference);
//act
var result = _videosController.PostVideo(reference, new Models.Video());
//assert
result.StatusCode.Should().Be(HttpStatusCode.Created);
result.Headers.Location.Should().NotBeNull();
_mockVideoService.Verify(x => x.CreateVideo(reference, It.IsAny<Video>()), Times.Once);
}
[Test]
public void Post_Video_VideoeServiceFails_Returns501InternalServerError()
{
//arrange
const string reference = "ABCD1234";
_mockVideoService.ResetCalls();
_mockVideoService.Setup(x => x.CreateVideo(reference, It.IsAny<Video>())).Returns((string)null);
//act
var result = _videosController.PostVideo(reference, new Models.Video());
//assert
result.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
result.Headers.Location.Should().BeNull();
_mockVideoService.Verify(x => x.CreateVideo(reference, It.IsAny<Video>()), Times.Once);
}
[Test]
public void Put_EmptyPropertyReference_ThrowsException()
{
//arrange
const string reference = "ABCD1234";
//act
Assert.Throws<ArgumentNullException>(
() => _videosController.PutVideo(string.Empty, reference, new Models.Video()));
}
[Test]
public void Put_EmptyVideoReference_ThrowsException()
{
//arrange
const string reference = "ABCD1234";
//act
Assert.Throws<ArgumentNullException>(
() => _videosController.PutVideo(reference, string.Empty, new Models.Video()));
}
[Test]
public void Put_NullVideo_ThrowsException()
{
//arrange
const string reference = "ABCD1234";
//act
Assert.Throws<ArgumentNullException>(() => _videosController.PutVideo(reference, reference, null));
}
[Test]
public void Put_Video_VideoServiceSucceeds_Returns200Ok()
{
//arrange
const string reference = "ABCD1234";
_mockVideoService.ResetCalls();
_mockVideoService.Setup(x => x.UpdateVideo(reference, reference, It.IsAny<Video>())).Returns(true);
//act
var result = _videosController.PutVideo(reference, reference, new Models.Video());
//assert
result.StatusCode.Should().Be(HttpStatusCode.OK);
_mockVideoService.Verify(x => x.UpdateVideo(reference, reference, It.IsAny<Video>()), Times.Once);
}
[Test]
public void Put_Video_VideoServiceFails_Returns501InternalServerError()
{
//arrange
const string reference = "ABCD1234";
_mockVideoService.ResetCalls();
_mockVideoService.Setup(x => x.UpdateVideo(reference, reference, It.IsAny<Video>())).Returns(false);
//act
var result = _videosController.PutVideo(reference, reference, new Models.Video());
//assert
result.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
_mockVideoService.Verify(x => x.UpdateVideo(reference, reference, It.IsAny<Video>()), Times.Once);
}
[Test]
public void Delete_EmptyPropertyReference_ThrowsException()
{
//arrange
const string reference = "ABCD1234";
//act
Assert.Throws<ArgumentNullException>(() => _videosController.DeleteVideo(string.Empty, reference));
}
[Test]
public void Delete_EmptyVideoReference_ThrowsException()
{
//arrange
const string reference = "ABCD1234";
//act
Assert.Throws<ArgumentNullException>(() => _videosController.DeleteVideo(reference, string.Empty));
}
[Test]
public void Delete_Video_VideoServiceSucceeds_Returns204NoContent()
{
//arrange
const string reference = "ABCD1234";
_mockVideoService.ResetCalls();
_mockVideoService.Setup(x => x.DeleteVideo(reference, reference)).Returns(true);
//act
var result = _videosController.DeleteVideo(reference, reference);
//assert
result.StatusCode.Should().Be(HttpStatusCode.NoContent);
_mockVideoService.Verify(x => x.DeleteVideo(reference, reference), Times.Once);
}
[Test]
public void Delete_Video_VideoServiceFails_Returns501InternalServerError()
{
//arrange
const string reference = "ABCD1234";
_mockVideoService.ResetCalls();
_mockVideoService.Setup(x => x.DeleteVideo(reference, reference)).Returns(false);
//act
var result = _videosController.DeleteVideo(reference, reference);
//assert
result.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
_mockVideoService.Verify(x => x.DeleteVideo(reference, reference), Times.Once);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using AutoMapper;
using Imp.Admin.Infrastructure;
using Imp.Admin.Models.Users;
using Imp.Core.Data;
using Imp.Core.Domain.Users;
using Imp.Data;
using Imp.Services.Files;
using Imp.Services.Security;
using Imp.Services.Users;
namespace Imp.Admin
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// autofac di
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly).InstancePerLifetimeScope();
builder.RegisterType(typeof(UserService)).AsImplementedInterfaces().InstancePerLifetimeScope();
builder.RegisterType(typeof(FileService)).AsImplementedInterfaces().InstancePerLifetimeScope();
builder.RegisterType(typeof(PermissionService)).AsImplementedInterfaces().InstancePerLifetimeScope();
builder.RegisterType(typeof(FormsAuthenticationService))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
// builder.Register<IAuthenticationService>(m => new FormsAuthenticationService()).InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
builder.Register<IDbContext>(c =>
new ImpObjectContext("data source=(local);initial catalog=ImpDev;user id=sa;password=P@ssword"))
.InstancePerLifetimeScope();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
AutoMapperStartup.Execute();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
|
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Utilities;
namespace EddiCompanionAppService.Endpoints
{
public class CombinedStationEndpoints : Endpoint
{
// We cache the profile to avoid spamming the service
private JObject cachedStationJson;
private DateTime cachedStationTimeStamp;
public DateTime cachedStationExpires => cachedStationTimeStamp.AddSeconds(30);
private static int retries;
// Set up an event handler for data changes
public event EndpointEventHandler StationUpdatedEvent;
/// <summary>
/// Returns combined profile, market, and shipyard data (verifying that the data is synchronized to expected values between endpoints)
/// </summary>
public JObject GetCombinedStation(string expectedCommanderName, string expectedStarSystemName, string expectedStationName, bool forceRefresh = false)
{
if ((!forceRefresh) && cachedStationExpires > DateTime.UtcNow)
{
// return the cached version
return cachedStationJson;
}
var profileJson = CompanionAppService.Instance.ProfileEndpoint.GetProfile();
if (profileJson != null)
{
var profileCmdrName = profileJson["commander"]?["name"]?.ToString();
var docked = profileJson["commander"]?["docked"]?.ToObject<bool?>() ?? false;
var onFoot = profileJson["commander"]?["onfoot"]?.ToObject<bool?>() ?? false;
var profileSystemName = profileJson["lastSystem"]?["name"]?.ToString();
var profileStationName = (profileJson["lastStarport"]?["name"])?.ToString().ReplaceEnd('+');
// Make sure that the Frontier API is configured to return data for the correct commander
if (string.IsNullOrEmpty(profileCmdrName) || profileCmdrName == expectedCommanderName)
{
// If we're docked, the lastStation information should be located within the lastSystem identified by the profile
// Make sure the profile is caught up to the game state
var marketJson = new MarketEndpoint().GetMarket();
var shipyardJson = new ShipyardEndpoint().GetShipyard();
if ((docked || onFoot) &&
!string.IsNullOrEmpty(profileSystemName) &&
expectedStarSystemName == profileSystemName &&
profileStationName == expectedStationName &&
marketJson != null && profileStationName == marketJson["name"]?.ToString() &&
shipyardJson != null && profileStationName == shipyardJson["name"]?.ToString())
{
// Data is up to date, we can proceed
retries = 0;
cachedStationJson = new JObject
{
{ "profileJson", profileJson },
{ "marketJson", marketJson },
{ "shipyardJson", shipyardJson }
};
cachedStationTimeStamp = new List<DateTime?>
{
profileJson["timestamp"]?.ToObject<DateTime?>(),
marketJson["timestamp"]?.ToObject<DateTime?>(),
shipyardJson["timestamp"]?.ToObject<DateTime?>()
}.OrderByDescending(d => d).FirstOrDefault() ?? DateTime.MinValue;
StationUpdatedEvent?.Invoke(this, new CompanionApiEndpointEventArgs(CompanionAppService.Instance.ServerURL(), profileJson, marketJson, shipyardJson, null));
return cachedStationJson;
}
}
else
{
Logging.Warn("Frontier API incorrectly configured: Returning information for Commander " +
$"'{profileCmdrName}' rather than for expected Commander '{expectedCommanderName}'. Disregarding incorrect information.");
return null;
}
}
// Data acquisition not successful, delay and retry (up to 5 times)
if (retries >= 5) { return null; }
retries += 1;
Thread.Sleep(TimeSpan.FromSeconds(10));
return GetCombinedStation(expectedCommanderName, expectedStarSystemName, expectedStationName);
}
}
}
|
namespace ServiceDesk.Ticketing.DataAccess.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class updateAddTicketComments : DbMigration
{
public override void Up()
{
CreateTable(
"Ticketing.TicketCommentStates",
c => new
{
Id = c.Guid(nullable: false),
Comment = c.String(),
CreatedOn = c.DateTime(nullable: false),
TicketState_Id = c.Guid(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("Ticketing.Tickets", t => t.TicketState_Id)
.Index(t => t.TicketState_Id);
}
public override void Down()
{
DropForeignKey("Ticketing.TicketCommentStates", "TicketState_Id", "Ticketing.Tickets");
DropIndex("Ticketing.TicketCommentStates", new[] { "TicketState_Id" });
DropTable("Ticketing.TicketCommentStates");
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XH.Domain.Catalogs
{
public enum RegionType
{
[Description("省")]
Province = 0,
[Description("直辖市")]
Municipality = 1,
[Description("市")]
City = 2,
[Description("区")]
District = 3,
[Description("县")]
County = 4,
[Description("乡镇")]
Town = 5,
[Description("村")]
Village = 6
}
}
|
using System;
namespace DamianTourBackend.Core.Entities
{
public class Registration
{
public Guid Id { get; set; }
public DateTime TimeStamp { get; set; }
public bool Paid { get; set; }
public Guid RouteId { get; set; }
public bool OrderedShirt { get; set; }
public ShirtSize ShirtSize { get; set; }
public Privacy Privacy { get; set; }
public Registration() { }
public Registration(DateTime timeStamp, Route route, User user, bool orderedShirt, ShirtSize shirtSize, Privacy privacy, bool paid = false)
{
Id = Guid.NewGuid();
TimeStamp = timeStamp;
RouteId = route.Id;
OrderedShirt = orderedShirt;
ShirtSize = shirtSize;
Privacy = privacy;
user.Registrations.Add(this);
Paid = paid;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CRL.Business.RoleAuthorize
{
[Attribute.Table(TableName = "Department")]
public class Department:Category.Category
{
}
}
|
using System.Threading.Tasks;
using ViewModel;
namespace DataAccess
{
public interface ICatalogsListQuery
{
Task<ListResponse<CatalogsResponse>> RunAsync(CatalogsFilter filter, ListOptions options);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.Mvc;
namespace HRM.Authentication
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class RequiredLoginAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (HttpContext.Current.Session["Username"] == null)
return false;
return true;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (this.AuthorizeCore(filterContext.HttpContext))
{
return;
}
else
{
filterContext.Result = new RedirectResult("/Login/Index");
}
}
}
} |
namespace RosPurcell.Web.Infrastructure.ViewModelBuilding
{
using RosPurcell.Web.ViewModels.Pages.Base;
using Umbraco.Core.Models;
public interface IViewModelBuilder
{
TTo Build<TTo>()
where TTo : new();
TTo Build<TFrom, TTo>(TFrom from)
where TTo : new();
TTo BuildPage<TTo>(IPublishedContent from)
where TTo : BasePageViewModel, new();
TTo BuildPage<TTo, TData>(IPublishedContent from, TData data)
where TTo : BasePageViewModel, new();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Facade
{
class Program
{
public abstract class Design
{
public abstract void setPosition(double x, double y);
public abstract void setWidth(double x);
public abstract void setHeight(double y);
public abstract void setColor(int r, int g, int b);
}
public class TextBox : Design
{
public override void setPosition(double x, double y)
{
Console.WriteLine("TextBox has been set at " + x + " " + y);
}
public override void setWidth(double x)
{
Console.WriteLine("TextBox width is " + x + " now");
}
public override void setHeight(double y)
{
Console.WriteLine("TextBox Height is " + y + " now");
}
public override void setColor(int r, int g, int b)
{
}
}
public class Label : Design
{
public override void setPosition(double x, double y)
{
Console.WriteLine("Label has been set at " + x + " " + y);
}
public override void setWidth(double x)
{
Console.WriteLine("Label width is " + x + " now");
}
public override void setHeight(double y)
{
Console.WriteLine("Label Height is " + y + " now");
}
public override void setColor(int r, int g, int b)
{
Console.WriteLine("Label Color is set!");
}
}
public class Button : Design
{
public override void setPosition(double x, double y)
{
Console.WriteLine("Button has been set at " + x + " " + y);
}
public override void setWidth(double x)
{
Console.WriteLine("Button width is " + x + " now");
}
public override void setHeight(double y)
{
Console.WriteLine("Button Height is " + y + " now");
}
public override void setColor(int r, int g, int b)
{
Console.WriteLine("Button Color is set!");
}
}
public class GraphicalUserInterface
{
private Design textBox;
private Design button;
private Design label;
public GraphicalUserInterface()
{
this.textBox = new TextBox();
this.label = new Label();
this.button = new Button();
}
public void createTextBox()
{
this.textBox.setPosition(1.0, 1.0);
this.textBox.setWidth(1.0);
this.textBox.setHeight(1.0);
}
public void createLabel()
{
this.label.setPosition(2.0, 2.0);
this.label.setWidth(2.0);
this.label.setHeight(2.0);
}
public void createButton()
{
this.button.setPosition(3.0, 3.0);
this.button.setWidth(3.0);
this.button.setHeight(3.0);
}
}
static void Main(string[] args)
{
GraphicalUserInterface buildGUI = new GraphicalUserInterface();
buildGUI.createButton();
buildGUI.createLabel();
buildGUI.createTextBox();
}
}
}
|
namespace Nan.Error
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public sealed class NanException<T> : Exception
{
public NanException(T target, string message) : base(message)
{
this.Target = target;
}
public NanException(T target, string message, Exception inner) : base(message,inner)
{
this.Target = target;
}
public T Target { get; private set; }
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace iSukces.Code.VsSolutions
{
public class Solution
{
public Solution(FileInfo solutionFile)
{
Projects = new List<SolutionProject>();
SolutionFile = new FileName(solutionFile);
var lines = File.ReadAllLines(SolutionFile.FullName);
var inProject = false;
foreach (var i in lines)
{
var ii = i.Trim();
if (inProject)
{
if (ii == "EndProject") inProject = false;
continue;
}
var a = TryParseProject(ii);
if (a == null)
continue;
Projects.Add(a);
inProject = true;
}
}
public override string ToString() => string.Format("Solution {0}", SolutionFile.Name);
private SolutionProject TryParseProject(string line)
{
var match = ProjectRegex.Match(line);
if (!match.Success)
return null;
var fi = new FileInfo(Path.Combine(SolutionFile.Directory.FullName, match.Groups[3].Value));
var project = new SolutionProject
{
// LocationUid = Guid.Parse(match.Groups[1].Value),
// Name = match.Groups[2].Value,
// ReSharper disable once PossibleNullReferenceException
Location = new FileName(fi)
// ProjectUid = Guid.Parse(match.Groups[4].Value)
};
return project.Location.Exists
? project
: null;
}
public FileName SolutionFile { get; }
public List<SolutionProject> Projects { get; }
private static readonly Regex ProjectRegex = new Regex(ProjectRegexFilter, RegexOptions.Compiled);
private const string ProjectRegexFilter =
@"^Project\(\s*\""*{([^}]+)\}\""\s*\)\s*=\s*\""([^\""]+)\""\s*,\s*\""([^\""]+)\""\s*,\s*\s*\""*{([^}]+)\}\""\s*(.*)$";
}
} |
using Newtonsoft.Json;
namespace Library.API.Models
{
public class Link
{
public Link(string href, string method, string relation)
{
Href = href;
Method = method;
Relation = relation;
}
/// <summary>
/// 用户可以检索资源或改变应用状态的URL
/// </summary>
public string Href { get; private set; }
/// <summary>
/// 请求该URL要是用的http方法
/// </summary>
public string Method { get; private set; }
/// <summary>
/// 描述href指向的资源和现有资源的关系
/// </summary>
[JsonProperty("rel")]
public string Relation { get; private set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStrcture.LinkedList
{
/// <summary>
/// 雙向環狀鏈結串列
/// </summary>
public class DoublyLinkedList : LinkedList
{
// HACK 還未實作RemoveAt
public DoublyLinkedList() : base() { }
public override Node Append(int value)
{
var result = new Node() { Value = value, Next = default, Previous = default };
// Linear版本
//if (First == default)
//{
// First = result;
//}
//else
//{
// Last.Next = result;
// result.Previous = Last;
//}
//Last = result;
// Circular版本
if (First == default)
{
First = result;
}
else
{
Last.Next = result;
result.Previous = Last;
}
Last = result;
Last.Next = First;
First.Previous = Last;
Count++;
return result;
}
public override Node InsertBefore(Node target, int value)
{
if (target == default)
{
return default;
}
var current = First;
var pre = new Node();
var result = new Node() { Value = value };
if (target == First)
{
Last.Next = result;
result.Next = First;
result.Previous = Last;
First = result;
}
while (current != target)
{
current = current.Next;
}
// 1 <-> 2 <-> 3
// 1 <-> 5 <-> 2 <-> 3
pre = current.Previous;
pre.Next = result; // 改掉1原本所指向的位址 1 -> "5"
current.Previous = result;
result.Next = current;
result.Previous = pre;
Count++;
return result;
}
public override Node InsertAfter(Node target, int value)
{
if (target == default)
{
return default;
}
var current = First;
var nextNode = new Node();
var result = new Node() { Value = value };
if (target == Last)
{
Last = result;
Last.Next = First;
First.Previous = Last;
}
// 找到target
while (target != current)
{
current = current.Next;
}
// 用node去想 比較好理解
// 關鍵點是: 處理toAppend的指標 還有原本node的指標
// e.g. insertAfter 2
// 2 <-> 5 <-> 3
nextNode = current.Next;
nextNode.Previous = result; // 改掉3原本指向的位址 5 <- "3"(nextNode)
current.Next = result; // 改掉2原本指向的位址 2 -> 5
result.Next = nextNode; // "5" -> 3
result.Previous = current; // 2 <- "5"
Count++;
return result;
}
public override void Concat(LinkedList linkedList)
{
if (linkedList == default)
{
return;
}
// 處理中間串接過程
Last.Next = linkedList.First;
linkedList.First.Previous = Last;
Last = linkedList.Last;
// 處理頭尾指標
First.Previous = linkedList.Last;
linkedList.Last.Next = First;
Count += linkedList.Count;
}
}
}
|
using System;
namespace Phenix.Security.Business
{
/// <summary>
/// 用户角色
/// </summary>
[Serializable]
[Phenix.Core.Mapping.ReadOnly]
public class UserRoleReadOnly : UserRole<UserRoleReadOnly>
{
}
/// <summary>
/// 用户角色清单
/// </summary>
[Serializable]
public class UserRoleReadOnlyList : Phenix.Business.BusinessListBase<UserRoleReadOnlyList, UserRoleReadOnly>
{
}
/// <summary>
/// 用户角色
/// </summary>
[Serializable]
public class UserRole : UserRole<UserRole>
{
}
/// <summary>
/// 用户角色清单
/// </summary>
[Serializable]
public class UserRoleList : Phenix.Business.BusinessListBase<UserRoleList, UserRole>
{
}
/// <summary>
/// 用户角色
/// </summary>
[Phenix.Core.Mapping.ClassAttribute("PH_USER_ROLE", FriendlyName = "用户角色"), System.SerializableAttribute(), System.ComponentModel.DisplayNameAttribute("用户角色")]
public abstract class UserRole<T> : Phenix.Business.BusinessBase<T> where T : UserRole<T>
{
/// <summary>
/// UR_ID
/// </summary>
public static readonly Phenix.Business.PropertyInfo<long?> UR_IDProperty = RegisterProperty<long?>(c => c.UR_ID);
[Phenix.Core.Mapping.Field(FriendlyName = "UR_ID", TableName = "PH_USER_ROLE", ColumnName = "UR_ID", IsPrimaryKey = true, NeedUpdate = true)]
private long? _UR_ID;
/// <summary>
/// UR_ID
/// </summary>
[System.ComponentModel.DisplayName("UR_ID")]
public long? UR_ID
{
get { return GetProperty(UR_IDProperty, _UR_ID); }
internal set
{
SetProperty(UR_IDProperty, ref _UR_ID, value);
}
}
[System.ComponentModel.Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
public override string PrimaryKey
{
get { return UR_ID.ToString(); }
}
/// <summary>
/// 用户
/// </summary>
public static readonly Phenix.Business.PropertyInfo<long?> UR_US_IDProperty = RegisterProperty<long?>(c => c.UR_US_ID);
[Phenix.Core.Mapping.Field(FriendlyName = "用户", TableName = "PH_USER_ROLE", ColumnName = "UR_US_ID", NeedUpdate = true)]
[Phenix.Core.Mapping.FieldLink("PH_USER", "US_ID")]
private long? _UR_US_ID;
/// <summary>
/// 用户
/// </summary>
[System.ComponentModel.DisplayName("用户")]
public long? UR_US_ID
{
get { return GetProperty(UR_US_IDProperty, _UR_US_ID); }
set { SetProperty(UR_US_IDProperty, ref _UR_US_ID, value); }
}
/// <summary>
/// 角色
/// </summary>
public static readonly Phenix.Business.PropertyInfo<long?> UR_RL_IDProperty = RegisterProperty<long?>(c => c.UR_RL_ID);
[Phenix.Core.Mapping.Field(FriendlyName = "角色", TableName = "PH_USER_ROLE", ColumnName = "UR_RL_ID", NeedUpdate = true)]
[Phenix.Core.Mapping.FieldLink("PH_ROLE", "RL_ID")]
private long? _UR_RL_ID;
/// <summary>
/// 角色
/// </summary>
[System.ComponentModel.DisplayName("角色")]
public long? UR_RL_ID
{
get { return GetProperty(UR_RL_IDProperty, _UR_RL_ID); }
set { SetProperty(UR_RL_IDProperty, ref _UR_RL_ID, value); }
}
/// <summary>
/// 录入人
/// </summary>
public static readonly Phenix.Business.PropertyInfo<string> InputerProperty = RegisterProperty<string>(c => c.Inputer);
[Phenix.Core.Mapping.Field(FriendlyName = "录入人", Alias = "UR_INPUTER", TableName = "PH_USER_ROLE", ColumnName = "UR_INPUTER", NeedUpdate = true, OverwritingOnUpdate = true, IsInputerColumn = true)]
private string _inputer;
/// <summary>
/// 录入人
/// </summary>
[System.ComponentModel.DisplayName("录入人")]
public string Inputer
{
get { return GetProperty(InputerProperty, _inputer); }
}
/// <summary>
/// 录入时间
/// </summary>
public static readonly Phenix.Business.PropertyInfo<DateTime?> InputTimeProperty = RegisterProperty<DateTime?>(c => c.InputTime);
[Phenix.Core.Mapping.Field(FriendlyName = "录入时间", Alias = "UR_INPUTTIME", TableName = "PH_USER_ROLE", ColumnName = "UR_INPUTTIME", NeedUpdate = true, OverwritingOnUpdate = true, IsInputTimeColumn = true)]
private DateTime? _inputTime;
/// <summary>
/// 录入时间
/// </summary>
[System.ComponentModel.DisplayName("录入时间")]
public DateTime? InputTime
{
get { return GetProperty(InputTimeProperty, _inputTime); }
}
}
}
|
using OpenTK;
using OpenTK.Graphics;
using StorybrewCommon.Mapset;
using StorybrewCommon.Scripting;
using StorybrewCommon.Storyboarding;
using StorybrewCommon.Storyboarding.Util;
using System;
using System.Linq;
namespace StorybrewScripts
{
public class Background : StoryboardObjectGenerator
{
[Configurable]
public string BackgroundPath = "";
[Configurable]
public int StartTime = 0;
[Configurable]
public int EndTime = 0;
[Configurable]
public double Opacity = 0.2;
public override void Generate()
{
if (BackgroundPath == "") BackgroundPath = Beatmap.BackgroundPath ?? string.Empty;
if (StartTime == EndTime) EndTime = (int)(Beatmap.HitObjects.LastOrDefault()?.EndTime ?? AudioDuration);
var bitmap = GetMapsetBitmap(BackgroundPath);
var bg = GetLayer("").CreateSprite(BackgroundPath, OsbOrigin.Centre);
bg.Scale(StartTime, 500.0f / bitmap.Height);
bg.Fade(StartTime , 0);
bg.Fade(EndTime, 0);
bg.Fade(124565,1);
bg.Fade(181292,181292,1,0);
bg.Fade(220565 ,220565,0,1);
bg.Fade(198746,1);
bg.Fade(356927,0);
bg.Fade(358018 - 500,358018 ,0,1);
bg.Fade(88565,1);
bg.Fade(414745,0);
var s = GetLayer("").CreateSprite("sb/blur.png", OsbOrigin.Centre);
s.Scale(StartTime, 500.0f / bitmap.Height);
s.Fade(OsbEasing.InOutBounce,89656,89656 + 1000,0,1);
s.Fade(OsbEasing.InOutBounce,163837,163837 + 1000,0,1);
s.Fade(OsbEasing.InOutBounce,392927,392927 + 1000,0,1);
s.Fade(0,1);
s.Fade(39482,39482 + 2000,1,0);
s.Fade(416927,421291,1,0);
s.Fade(124565,124565 + 2000,1,0);
s.Fade(266382,266382 + 500,0,1);
s.Fade(314382,314382 + 2000,1,0);
s.Fade(340564,1);
s.Fade(356927,356927 + 200,1,0.2);
s.Fade(181292,181292 + 500,1,0);
var ss = GetLayer("").CreateSprite("sb/noblur.png", OsbOrigin.Centre);
ss.Scale(StartTime, 500.0f / bitmap.Height);
ss.Fade(0,0);
ss.Fade(39482,1);
ss.Fade(89656- 500,89656,1,0);
ss.Fade(OsbEasing.InOutBounce,142019 ,142019 + 1000,0,1);
ss.Fade(146383,146383 + 500,1,0);
ss.Fade(OsbEasing.InOutBounce,183201,183201 + 1000,0,1);
ss.Fade(OsbEasing.InOutBounce,216201,216201 + 1000,0,1);
ss.Fade(220565,220565 + 500,1,0);
ss.Fade(198746,198746 + 2000,1,0);
ss.Fade(238018,238018 + 2000,0,1);
ss.Fade(266382,266382 + 500,1,0);
ss.Fade(OsbEasing.InOutBounce,331836,331836 + 1000,0,1);
ss.Fade(340564,340564 + 2000,1,0);
var v = GetLayer("Vignette").CreateSprite("sb/vignette.png", OsbOrigin.Centre);
v.Scale(StartTime, 500.0f / bitmap.Height);
v.Fade(StartTime,1);
v.Fade(EndTime,EndTime + 2000,1,0);
{
var step = Random(2000,5000);
for(var t = 0 + step; t < EndTime; t += step) {
var previousTime = t - step;
var ranPoX = Random(-5, 5);
var ranPoY = Random(-5, 5);
bg.Move(OsbEasing.InOutQuad,previousTime, t, bg.PositionAt(previousTime), new Vector2(ranPoX+ 320, ranPoY+240));
s.Move(OsbEasing.InOutQuad,previousTime, t, s.PositionAt(previousTime), new Vector2(ranPoX+ 320, ranPoY+240));
ss.Move(OsbEasing.InOutQuad,previousTime, t, ss.PositionAt(previousTime), new Vector2(ranPoX+ 320, ranPoY+240));
}
}
var step1 = Random(6000,10000);
for(var t = 0 + step1; t < EndTime; t += step1) {
var previousTime = t - step1;
var rot = Random(-0.04,0.04 );
bg.Rotate(OsbEasing.InOutQuad,previousTime, t, bg.RotationAt(previousTime),rot);
s.Rotate(OsbEasing.InOutQuad,previousTime, t, s.RotationAt(previousTime), rot);
ss.Rotate(OsbEasing.InOutQuad,previousTime, t, ss.RotationAt(previousTime),rot);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using BE;
using BL;
using PL.Views;
using PL.Models;
namespace PL.ViewModel
{
public class IceCreamShopVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private IceCreamShopUC IceCreamShopUC { get; set; }
private IceCreamShopModel CurrentModel { get; set; }
public IceCreamShopVM(IceCreamShopUC iceCreamShopUC)
{
this.IceCreamShopUC = iceCreamShopUC;
CurrentModel = new IceCreamShopModel();
CurrentModel.iceCream = iceCreamShopUC.iceCream;
CurrentModel.shop = iceCreamShopUC.shop;
CurrentModel.iceCream.UpdateLists();
iceCreamShopUC.ImageViewIceCream.ItemsSource = CurrentModel.iceCream.images;
if (CurrentModel.iceCream.comments[0] != "")
iceCreamShopUC.CommentViewIceCream.ItemsSource = CurrentModel.iceCream.comments;
}
#region shop
public string ShopAddress
{
get { return CurrentModel.shop.Adress; }
}
public string ShopCoordinatesGps
{
get { return CurrentModel.GetGpsAddress(CurrentModel.shop.Adress); }
}
public string ShopPhone
{
get { return CurrentModel.shop.Phone; }
}
public string ShopWebSite
{
get { return CurrentModel.shop.WebSiteLink; }
}
public string ShopFaceBook
{
get { return CurrentModel.shop.FaceBookLink; }
}
public string ShopName
{
get { return CurrentModel.shop.Id; }
}
public string ShopImage
{
get { return CurrentModel.shop.images[0]; }
}
#endregion
#region IceCream
public string IceCreamID
{
get { return CurrentModel.iceCream.Id; }
}
public string IceCreamImage
{
get { return CurrentModel.iceCream.Image; }
}
public string IceCreamTaste
{
get { return CurrentModel.iceCream.Taste; }
}
public string IceCreamEnergy
{
get { return CurrentModel.iceCream.Energy.ToString(); }
}
public string IceCreamProteins
{
get { return CurrentModel.iceCream.Proteins.ToString(); }
}
public string IceCreamCalories
{
get { return CurrentModel.iceCream.Calories.ToString(); }
}
public string IceCreamGrade
{
get
{
string[] grade = CurrentModel.iceCream.Marks.Split(',').ToArray();
return grade[0];
}
}
public string IceCreamDescription
{
get { return CurrentModel.iceCream.Description; }
}
#endregion
}
}
|
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.SocialPlatforms;
namespace HudReplacer
{
public class GuardianHUD
{
private static StatusEffect _guardianPower;
private static float _cooldown;
[CanBeNull] internal static Localize _localize;
internal string GP_text;
internal static void GetGuardianPower()
{
Player.m_localPlayer.GetGuardianPowerHUD(out _guardianPower, out _cooldown);
if (_guardianPower == null)
{
GDPower.Gpowerindicator = false;
}
else if (_guardianPower != null)
{
GDPower.Gpowerindicator = true;
GDPower.GuardianSprite = _guardianPower.m_icon;
GDPower.CooldownTxt = TimeFomat(Mathf.CeilToInt(_cooldown));
GDPower.GDName = Localization.instance.Localize(_guardianPower.m_name);
GDPower.GDKey = Localization.instance.Localize("$KEY_GPower");
GDPower.rawcooldown = _cooldown;
}
}
public static string TimeFomat(int secs)
{
int mins = (secs % 3600) / 60;
secs = secs % 60;
return $"{mins:00}:{secs:00}";
}
}
} |
using System;
namespace FirstFollowParser
{
class Program
{
static void Main(string[] args)
{
GrammarParser grammer = new GrammarParser(@"C:\Users\darkshot\source\repos\LL1Parser\ParserTests\Sample5.in");
Console.WriteLine(string.Join(",", grammer.nonTerminals));
Console.WriteLine(string.Join(",", grammer.terminals));
Console.WriteLine(grammer.grammer.Count);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
var fifo = new FirstFollow(grammer);
fifo.First();
fifo.printFirst();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
fifo.Follow();
fifo.PrintFollow();
}
}
}
|
using Uintra.Features.Links.Models;
namespace Uintra.Features.CentralFeed.Models.GroupFeed
{
public struct GroupInfo
{
public string Title { get; }
public UintraLinkModel Url { get; }
public GroupInfo(string title, UintraLinkModel url)
{
Title = title;
Url = url;
}
}
} |
using System.IO;
using UnityEditor;
using UnityEngine;
public static class SavePrefabHelper
{
[MenuItem("GameObject/SavePrefab", false, 10)]
public static void SavePrefab()
{
var selectingGO = Selection.activeObject as GameObject;
if (selectingGO == null)
{
return;
}
var prefabName = selectingGO.name;
var index = prefabName.IndexOf("(Clone)");
if (index > 0)
{
prefabName = prefabName.Remove(index);
}
var prefabs = AssetDatabase.FindAssets("t:prefab");
foreach (var item in prefabs)
{
var prefabPath = AssetDatabase.GUIDToAssetPath(item);
var fileName = Path.GetFileNameWithoutExtension(prefabPath);
if (fileName == prefabName)
{
PrefabUtility.SaveAsPrefabAssetAndConnect(selectingGO, prefabPath, InteractionMode.AutomatedAction, out var success);
if (success)
{
EditorUtility.DisplayDialog("SavePrefab", $"SavePrefab {prefabPath} Success!", "OK");
return;
}
}
}
EditorUtility.DisplayDialog("SavePrefab", "SavePrefab Failed!", "OK");
}
}
|
using SGCFT.Dominio.Entidades;
using SGCFT.Utilitario;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SGCFT.Dominio.Contratos.Servicos
{
public interface IModuloServico
{
Retorno InserirModulo(Modulo modulo);
Retorno AlterarModulo(Modulo modulo);
}
}
|
using UnityEngine;
using System.Collections;
public class GUIFadeScript : MonoBehaviour {
public CanvasGroup fadeCanvasGroup;
public IEnumerator FadeToBlack(float speed)
{
while (fadeCanvasGroup.alpha < 1f)
{
fadeCanvasGroup.alpha += speed * Time.deltaTime;
yield return null;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SensorsDBAPI.Models
{
public class Alert
{
public int id { get; set; }
public string type { get; set; }
public string condition { get; set; }
public float value { get; set; }
public float valueMax { get; set; }
public string state { get; set; }
}
} |
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Event Instancer of type `Void`. Inherits from `AtomEventInstancer<Void, VoidEvent>`.
/// </summary>
[EditorIcon("atom-icon-sign-blue")]
[AddComponentMenu("Unity Atoms/Event Instancers/Void Event Instancer")]
public class VoidEventInstancer : AtomEventInstancer<Void, VoidEvent> { }
}
|
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace TweetApp.Entities
{
[DataContract]
[BsonIgnoreExtraElements]
public class AppUser
{
[BsonId]
[BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
public string UserId { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string LoginId { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string ContactNumber { get; set; }
[JsonIgnore]
public ICollection<Tweet> Tweets { get; set; }
[JsonIgnore]
public ICollection<TweetLike> LikedTweets { get; set; }
public string token { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FactoryMethod.Employes
{
public sealed class Policeman : Employee
{
public Policeman()
{
_price = 10;
}
public override float CalculateMonthPrice(int hoursInMonth)
{
return _price * hoursInMonth;
}
}
}
|
#if UNITY_2019_1_OR_NEWER
using UnityEditor;
using UnityEngine.UIElements;
using UnityAtoms.Editor;
using UnityEngine;
namespace UnityAtoms.BaseAtoms.Editor
{
/// <summary>
/// Event property drawer of type `Vector2Pair`. Inherits from `AtomEventEditor<Vector2Pair, Vector2PairEvent>`. Only availble in `UNITY_2019_1_OR_NEWER`.
/// </summary>
[CustomEditor(typeof(Vector2PairEvent))]
public sealed class Vector2PairEventEditor : AtomEventEditor<Vector2Pair, Vector2PairEvent> { }
}
#endif
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DigitalFormsSteamLeak.Entity.IModels
{
public interface ICommentsSession
{
Guid CommentsId { get; set; }
string CommentNotes { get; set; }
string CommenterName { get; set; }
DateTime DateCommented { get; set; }
Guid LeakDetailsId { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace com.Sconit.Web.Models.SearchModels.TMS
{
public class TransportActingBillSearchModel : SearchModelBase
{
public string OrderNo { get; set; }
public string Flow { get; set; }
public string Carrier { get; set; }
public DateTime? EndTime { get; set; }
public DateTime? StartTime { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace Abc.MvcWebUI.Entity
{
public class DataInitializer : DropCreateDatabaseIfModelChanges<DataContext>
{
protected override void Seed(DataContext context)
{
var categories = new List<Category>()
{
new Category(){ Name = "Kadın Etek", Description = "Kamera ürünleri"},
new Category(){ Name = "Kadın t-shirt", Description = "Kamera ürünleri"},
new Category(){ Name = "Kadın Pantolon", Description = "Kamera ürünleri"},
new Category(){ Name = "Kadın Elbise", Description = "Kamera ürünleri"}
};
foreach (var item in categories)
{
context.Categories.Add(item);
}
context.SaveChanges();
var products = new List<Product>()
{
new Product(){ Name = "Etek",Description = "Kullanmayı çok seveceğiniz ergonomik tasarım Optik vizör, çekiminizi oluşturmanıza ve tahmin etmenize olanak tanıyarak her zaman anın arkasındaki duyguyu yakalamak için hazır olmanızı sağlar. Sezgisel kullanımlı kullanıcı dostu kontrolleri ve görüntüyü incelemek için 7,5 cm'lik (3 inç) geniş LCD ekranıyla EOS 1200D'yi kullanması çok keyiflidir.", Price =1200 , Stock =500 , IsApproved =true , CategoryId = 1,IsHome = true,İmage = "etek1.jpg"},
new Product(){ Name = "Etek",Description = "Kullanmayı çok seveceğiniz ergonomik tasarım Optik vizör, çekiminizi oluşturmanıza ve tahmin etmenize olanak tanıyarak her zaman anın arkasındaki duyguyu yakalamak için hazır olmanızı sağlar. Sezgisel kullanımlı kullanıcı dostu kontrolleri ve görüntüyü incelemek için 7,5 cm'lik (3 inç) geniş LCD ekranıyla EOS 1200D'yi kullanması çok keyiflidir.", Price =1200 , Stock =500 , IsApproved =true , CategoryId = 1,IsHome = false,İmage = "etek2.jpg"},
new Product(){ Name = "t-shirt",Description = "Kullanmayı çok seveceğiniz ergonomik tasarım Optik vizör, çekiminizi oluşturmanıza ve tahmin etmenize olanak tanıyarak her zaman anın arkasındaki duyguyu yakalamak için hazır olmanızı sağlar. Sezgisel kullanımlı kullanıcı dostu kontrolleri ve görüntüyü incelemek için 7,5 cm'lik (3 inç) geniş LCD ekranıyla EOS 1200D'yi kullanması çok keyiflidir.", Price =1200 , Stock =500 , IsApproved =true , CategoryId = 2,IsHome = true,İmage = "tshirt.jpg"},
new Product(){ Name = "t-shirt",Description = "Kullanmayı çok seveceğiniz ergonomik tasarım Optik vizör, çekiminizi oluşturmanıza ve tahmin etmenize olanak tanıyarak her zaman anın arkasındaki duyguyu yakalamak için hazır olmanızı sağlar. Sezgisel kullanımlı kullanıcı dostu kontrolleri ve görüntüyü incelemek için 7,5 cm'lik (3 inç) geniş LCD ekranıyla EOS 1200D'yi kullanması çok keyiflidir.", Price =1200 , Stock =500 , IsApproved =true , CategoryId = 2,IsHome = false,İmage = "tshirt2.jpg"},
new Product(){ Name = "pantolon",Description = "Kullanmayı çok seveceğiniz ergonomik tasarım Optik vizör, çekiminizi oluşturmanıza ve tahmin etmenize olanak tanıyarak her zaman anın arkasındaki duyguyu yakalamak için hazır olmanızı sağlar. Sezgisel kullanımlı kullanıcı dostu kontrolleri ve görüntüyü incelemek için 7,5 cm'lik (3 inç) geniş LCD ekranıyla EOS 1200D'yi kullanması çok keyiflidir.", Price =1200 , Stock =500 , IsApproved =true , CategoryId = 3,IsHome = true,İmage = "pantolon1.jpg"},
new Product(){ Name = "Pantolon",Description = "Kullanmayı çok seveceğiniz ergonomik tasarım Optik vizör, çekiminizi oluşturmanıza ve tahmin etmenize olanak tanıyarak her zaman anın arkasındaki duyguyu yakalamak için hazır olmanızı sağlar. Sezgisel kullanımlı kullanıcı dostu kontrolleri ve görüntüyü incelemek için 7,5 cm'lik (3 inç) geniş LCD ekranıyla EOS 1200D'yi kullanması çok keyiflidir.", Price =1200 , Stock =500 , IsApproved =false , CategoryId = 3,IsHome = true,İmage = "pantolon 2.jpg"},
new Product(){ Name = "Elbise",Description = "Kullanmayı çok seveceğiniz ergonomik tasarım Optik vizör, çekiminizi oluşturmanıza ve tahmin etmenize olanak tanıyarak her zaman anın arkasındaki duyguyu yakalamak için hazır olmanızı sağlar. Sezgisel kullanımlı kullanıcı dostu kontrolleri ve görüntüyü incelemek için 7,5 cm'lik (3 inç) geniş LCD ekranıyla EOS 1200D'yi kullanması çok keyiflidir.", Price =1200 , Stock =500 , IsApproved =false , CategoryId = 4,IsHome = true,İmage = "dress.jpg"},
new Product(){ Name = "Elbise",Description = "Kullanmayı çok seveceğiniz ergonomik tasarım Optik vizör, çekiminizi oluşturmanıza ve tahmin etmenize olanak tanıyarak her zaman anın arkasındaki duyguyu yakalamak için hazır olmanızı sağlar. Sezgisel kullanımlı kullanıcı dostu kontrolleri ve görüntüyü incelemek için 7,5 cm'lik (3 inç) geniş LCD ekranıyla EOS 1200D'yi kullanması çok keyiflidir.", Price =1200 , Stock =500 , IsApproved =true , CategoryId = 4,IsHome = false,İmage = "drees.jpg"}
};
foreach (var item in products)
{
context.Products.Add(item);
}
context.SaveChanges();
base.Seed(context);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApiUI.Models
{
public class MessageModel
{
public string MessageText { get; set; }
public int SenderId { get; set; }
public int ReceiverId { get; set; }
public DateTime MessageDate { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Threading.Tasks;
using Browsing;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
namespace DirectoryBrowser.Controllers
{
[Route("api/browsing")]
[ApiController]
public class BrowsingController : ControllerBase
{
IBrowser _browser;
public BrowsingController(IBrowser browser)
{
_browser = browser;
}
[HttpGet]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public ActionResult<Node> Get(string path)
{
Node toReturn = _browser.GetBrowserNodes(path);
return Ok(toReturn);
}
[Route("DownloadFile")]
[HttpGet]
public IActionResult DownloadFile(string path)
{
byte[] fileBytes = _browser.DownloadFile(path);
FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();
string contentType;
string fileName = Path.GetFileName(path);
if (!provider.TryGetContentType(fileName, out contentType))
{
contentType = "application/octet-stream";
}
ContentDisposition cd = new ContentDisposition
{
FileName = fileName,
Inline = false
};
Response.Headers.Add("Content-Disposition", cd.ToString());
Response.Headers.Add("X-Content-Type-Options", "nosniff");
return File(fileBytes, contentType, fileName);
}
[Route("UploadFiles")]
[HttpPost]
public async Task<ActionResult<Node>> UploadFiles(IList<IFormFile> files)
{
string path = HttpContext.Request?.Headers["X-File-Path"];
Node node = await _browser.UploadFilesAsync(new FileUpload(files, path));
return Ok(node);
}
[Route("MoveNodes")]
[HttpPost]
public ActionResult<Node> MoveNodes([FromBody] MoveNodes moveNodes)
{
Node node = _browser.MoveNodes(moveNodes);
return Ok(node);
}
[Route("CopyNodes")]
[HttpPost]
public async Task<ActionResult<Node>> CopyNodes([FromBody] CopyNodes copyNodes)
{
Node node = await _browser.CopyNodesAsync(copyNodes);
return Ok(node);
}
[Route("Search")]
[HttpPost]
public ActionResult<Node> Search([FromBody] Search searchModel)
{
Node node = _browser.Search(searchModel);
return Ok(node);
}
[Route("CreateDirectory")]
[HttpPut]
public ActionResult<Node> CreateDirectory([FromBody] CreateDirectory createDirectory)
{
Node node = _browser.CreateDirectory(createDirectory);
return Ok(node);
}
[HttpDelete]
public ActionResult Delete([FromBody]RemoveNodes removeNodes)
{
_browser.DeleteNodes(removeNodes);
return Ok();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using CarFinanceCalculator.Domain;
namespace CarFinanceCalculator.Forms.Views
{
public partial class Main : Form
{
private int _year;
private string _make;
private string _model;
private decimal _msrp;
private decimal _monthlyPayment;
private decimal _loanAmount;
private decimal _apr;
private int _term;
private DateTime _startDate;
private readonly List<SummaryLine> _displayLines = new List<SummaryLine>();
private readonly List<AmortizationScheduleLine> _rawLines = new List<AmortizationScheduleLine>();
public Main()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
if (!Validate())
{
MessageBox.Show(
"Check parameters...",
"Input Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
Calculate();
}
private void Calculate()
{
dgSummary.DataSource = null;
_displayLines.Clear();
_rawLines.Clear();
var car = new Car(_year, _make, _model, _msrp);
var loan = new CarLoan(car, _loanAmount, _apr, _term, _startDate);
var amortCalc = new AmortizationCalculator(_monthlyPayment);
var carValueCalc = new DepreciationCalculator();
amortCalc.Calculate(loan);
foreach (var line in amortCalc.Lines)
{
var carValue = carValueCalc.Calculate(car, line.PaymentDate);
var summaryLine = new SummaryLine(
line.PaymentDate,
line.Payment.ToString("C"),
line.Interest.ToString("C"),
line.Principal.ToString("C"),
line.RemainingPrincipal.ToString("C"),
carValue.ToString("C"),
(carValue - line.RemainingPrincipal).ToString("C"));
_displayLines.Add(summaryLine);
}
var maturityDate = _displayLines.Last().PaymentDate.ToShortDateString();
var equityDate = _displayLines.FirstOrDefault(p => !p.Equity.StartsWith("(")); // HACKZ0RZ
lblMaturityDate.Text = maturityDate;
lblEquityDate.Text = $"{equityDate?.PaymentDate.ToShortDateString() ?? "Never"}";
BindGrid();
}
private void BindGrid()
{
dgSummary.DataSource = _displayLines;
}
private bool Validate()
{
_make = txtMake.Text;
_model = txtModel.Text;
_startDate = dpStartDate.Value;
if (!int.TryParse(txtYear.Text, out _year))
return false;
if (!decimal.TryParse(txtMsrp.Text, out _msrp))
return false;
if (!decimal.TryParse(txtPayment.Text, out _monthlyPayment))
return false;
if (!decimal.TryParse(txtLoanAmount.Text, out _loanAmount))
return false;
if (!decimal.TryParse(txtRate.Text, out _apr) || _apr > 1 || _apr < 0)
return false;
if (!int.TryParse(txtTerm.Text, out _term))
return false;
return true;
}
}
public class SummaryLine
{
public DateTime PaymentDate { get; set; }
public string PaymentAmount { get; set; }
public string InterestPaid { get; set; }
public string PrincipalPaid { get; set; }
public string RemainingBalance { get; set; }
public string CarValue { get; set; }
public string Equity { get; set; }
public SummaryLine(
DateTime paymentDate,
string paymentAmount,
string interestPaid,
string principalPaid,
string remainingBalance,
string carValue,
string equity)
{
PaymentDate = paymentDate;
PaymentAmount = paymentAmount;
InterestPaid = interestPaid;
PrincipalPaid = principalPaid;
RemainingBalance = remainingBalance;
CarValue = carValue;
Equity = equity;
}
}
}
|
using System.IO;
using System.Threading.Tasks;
using DotnetSpider.Core;
using Newtonsoft.Json;
namespace DotnetSpider.Data.Storage
{
public class FileStorage : FileStorageBase
{
public static FileStorage CreateFromOptions(ISpiderOptions options)
{
return new FileStorage();
}
protected override async Task<DataFlowResult> Store(DataFlowContext context)
{
var file = Path.Combine(GetDataFolder(context.Response.Request.OwnerId), $"{context.Response.Request.Hash}.data");
CreateFile(file);
await Writer.WriteLineAsync("URL:\t" + context.Response.Request.Url);
var items = context.GetItems();
await Writer.WriteLineAsync("DATA:\t" + JsonConvert.SerializeObject(items));
return DataFlowResult.Success;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.SessionState;
using Newtonsoft.Json;
namespace mr.bBall_Lib
{
public class DevicesData
{
public class DeviceData
{
public int Id { get; set; }
public string acDevID { get; set; }
public decimal anBatteryVoltage { get; set; }
public decimal anSensor1 { get; set; }
public decimal anSensor2 { get; set; }
public DateTime adModificationDate { get; set; }
public int anUserMod { get; set; }
}
public static DataTable Get_d()
{
cSettings.GetSettings("");
cSQL lSql = new cSQL();
string lResp = lSql.ConnectSQL(Splosno.AppSQLName);
if (lResp.Length > 0) { throw new Exception(lResp); }
StringBuilder sSQL = new StringBuilder();
sSQL.AppendLine("SELECT TOP 500 * FROM DevicesData ");
sSQL.AppendLine("ORDER BY ID desc ");
sSQL.AppendLine(" ");
string lErr;
DataTable lTmpDT = lSql.FillDT(sSQL, out lErr);
if (lErr.Length > 0) { throw new Exception(lErr); }
lSql.DisconnectSQL();
return lTmpDT;
}
public static DataTable Get_d(string acDevID)
{
cSettings.GetSettings("");
cSQL lSql = new cSQL();
string lResp = lSql.ConnectSQL(Splosno.AppSQLName);
if (lResp.Length > 0) { throw new Exception(lResp); }
StringBuilder sSQL = new StringBuilder();
sSQL.AppendLine("select TOP 500 * from DevicesData where acDevID=@id ORDER BY ID desc ");
sSQL.AppendLine(" ");
sSQL.AppendLine(" ");
SqlParameter[] sqlParams = new SqlParameter[] {
new SqlParameter("@id", acDevID)
};
string lErr;
DataTable lTmpDT = lSql.FillDT(sSQL, sqlParams, out lErr);
if (lErr.Length > 0) { throw new Exception(lErr); }
lSql.DisconnectSQL();
return lTmpDT;
}
public static DataTable Get_d(int ID)
{
cSettings.GetSettings("");
cSQL lSql = new cSQL();
string lResp = lSql.ConnectSQL(Splosno.AppSQLName);
if (lResp.Length > 0) { throw new Exception(lResp); }
StringBuilder sSQL = new StringBuilder();
sSQL.AppendLine("select TOP 500 * from DevicesData where ID = @ID ORDER BY ID desc ");
sSQL.AppendLine(" ");
sSQL.AppendLine(" ");
SqlParameter[] sqlParams = new SqlParameter[] {
new SqlParameter("@ID", ID)
};
string lErr;
DataTable lTmpDT = lSql.FillDT(sSQL, sqlParams, out lErr);
if (lErr.Length > 0) { throw new Exception(lErr); }
lSql.DisconnectSQL();
return lTmpDT;
}
public static List<DeviceData> Get(int ID, string acDevID)
{
DataTable dt = new DataTable();
List<DeviceData> lResp = new List<DeviceData>();
if (ID > 0) { dt = Get_d(ID); }
else if (!String.IsNullOrEmpty(acDevID)) { dt = Get_d(acDevID); }
else { dt = Get_d(); }
foreach (DataRow r in dt.Rows)
{
lResp.Add(new DeviceData
{ Id = Convert.ToInt32(r["ID"]),
acDevID = Convert.ToString(r["acDevID"]),
anBatteryVoltage = Convert.ToDecimal(r["anBatteryVoltage"]),
anSensor1 = Convert.ToDecimal(r["anSensor1"]),
anSensor2 = Convert.ToDecimal(r["anSensor2"]),
adModificationDate = Convert.ToDateTime(r["adModificationDate"]),
anUserMod = Convert.ToInt32(r["anUserMod"])
});
}
return lResp;
}
public static List<DeviceData> Set(DeviceData pData)
{
if (pData.Id > 0) { Update(pData); } else { Insert(pData); }
return Get(pData.Id, pData.acDevID);
}
public static void Upload(DeviceData pData)
{
Insert(pData);
}
public static void Delete(DeviceData pData)
{
cSettings.GetSettings("");
cSQL lSql = new cSQL();
string lResp = lSql.ConnectSQL(Splosno.AppSQLName);
if (lResp.Length > 0) { throw new Exception(lResp); }
StringBuilder sSQL = new StringBuilder();
sSQL.AppendLine("DELETE FROM DevicesData ");
sSQL.AppendLine("WHERE (ID = @ID) ");
sSQL.AppendLine(" ");
SqlParameter[] sqlParams = new SqlParameter[] {
new SqlParameter("@ID", pData.Id)
};
string lErr = lSql.ExecuteQuery(sSQL, sqlParams);
lSql.DisconnectSQL();
if (lErr.Length > 0) { throw new Exception(lErr); }
}
public static void Update(DeviceData pData)
{
cSettings.GetSettings("");
cSQL lSql = new cSQL();
string lResp = lSql.ConnectSQL(Splosno.AppSQLName);
if (lResp.Length > 0) { throw new Exception(lResp); }
StringBuilder sSQL = new StringBuilder();
// get data
sSQL.Remove(0, sSQL.Length);
sSQL.AppendLine("update DevicesData SET adModificationDate = @adModificationDate, anUserMod = @anUserMod, anBatteryVoltage = @anBatteryVoltage, anSensor1 = @anSensor1, ");
sSQL.AppendLine(" anSensor2 = @anSensor2 ");
sSQL.AppendLine("where id=@id ");
sSQL.AppendLine(" ");
SqlParameter[] sqlParams = new SqlParameter[] {
new SqlParameter("@id", pData.Id),
new SqlParameter("@adModificationDate", pData.adModificationDate),
new SqlParameter("@anBatteryVoltage", pData.anBatteryVoltage),
new SqlParameter("@anSensor1", pData.anSensor1),
new SqlParameter("@anUserMod", pData.anUserMod),
new SqlParameter("@anSensor2", pData.anSensor2)
};
string lErr = lSql.ExecuteQuery(sSQL, sqlParams);
lSql.DisconnectSQL();
if (lErr.Length > 0) { throw new Exception(lErr); }
}
public static void Insert(DeviceData pData)
{
cSettings.GetSettings("");
cSQL lSql = new cSQL();
string lResp = lSql.ConnectSQL(Splosno.AppSQLName);
if (lResp.Length > 0) { throw new Exception(lResp); }
StringBuilder sSQL = new StringBuilder();
// get data
sSQL.Remove(0, sSQL.Length);
sSQL.AppendLine("INSERT INTO DevicesData (acDevID, anBatteryVoltage, anSensor1, anUserMod, anSensor2) ");
sSQL.AppendLine(" VALUES (@acDevID, @anBatteryVoltage, @anSensor1, @anUserMod, @anSensor2) ");
sSQL.AppendLine(" ");
sSQL.AppendLine(" ");
SqlParameter[] sqlParams = new SqlParameter[] {
new SqlParameter("@acDevID", pData.acDevID),
new SqlParameter("@adModificationDate", pData.adModificationDate),
new SqlParameter("@anBatteryVoltage", pData.anBatteryVoltage),
new SqlParameter("@anSensor1", pData.anSensor1),
new SqlParameter("@anUserMod", pData.anUserMod),
new SqlParameter("@anSensor2", pData.anSensor2)
};
string lErr = lSql.ExecuteQuery(sSQL, sqlParams);
lSql.DisconnectSQL();
if (lErr.Length > 0) { throw new Exception(lErr); }
}
}
}
|
using System;
using System.Dynamic;
namespace Profiling2.Domain.Extensions
{
public static class EntityIncompleteDateExtensions
{
public static bool HasIncompleteDate<T>(this T subject)
where T : IIncompleteDate
{
return subject.YearOfStart == 0 || subject.YearOfEnd == 0;
}
public static bool HasIntersectingDateWith<T>(this T subject, IIncompleteDate e)
where T : IIncompleteDate
{
if (e != null)
{
DateTime rStartDate = new DateTime(subject.YearOfStart > 0 ? subject.YearOfStart : 1, subject.MonthOfStart > 0 ? subject.MonthOfStart : 1, subject.DayOfStart > 0 ? subject.DayOfStart : 1);
DateTime rEndDate = new DateTime(subject.YearOfEnd > 0 ? subject.YearOfEnd : 1, subject.MonthOfEnd > 0 ? subject.MonthOfEnd : 1, subject.DayOfEnd > 0 ? subject.DayOfEnd : 1);
DateTime eStartDate = new DateTime(e.YearOfStart > 0 ? e.YearOfStart : 1, e.MonthOfStart > 0 ? e.MonthOfStart : 1, e.DayOfStart > 0 ? e.DayOfStart : 1);
DateTime eEndDate = new DateTime(e.YearOfEnd > 0 ? e.YearOfEnd : 1, e.MonthOfEnd > 0 ? e.MonthOfEnd : 1, e.DayOfEnd > 0 ? e.DayOfEnd : 1);
bool result = true;
if (e.YearOfStart > 0 || e.YearOfEnd > 0)
{
if (e.YearOfStart > 0)
{
if (subject.YearOfStart > 0)
result = result && eStartDate >= rStartDate;
if (subject.YearOfEnd > 0)
result = result && eStartDate <= rEndDate;
}
if (e.YearOfEnd > 0)
{
if (subject.YearOfStart > 0)
result = result && eEndDate >= rStartDate;
if (subject.YearOfEnd > 0)
result = result && eEndDate <= rEndDate;
}
}
else
return false;
return result;
}
return false;
}
/// <summary>
/// Printable date summary which doesn't attempt to fill in empty values.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="subject"></param>
/// <returns></returns>
public static string GetDateSummary<T>(this T subject)
where T : IIncompleteDate
{
string s = string.Empty;
if (subject.HasStartDate())
{
s += subject.GetStartDateString();
if (subject.HasEndDate())
{
s += " - " + subject.GetEndDateString();
}
}
else if (subject.HasEndDate())
{
s += subject.GetEndDateString();
}
return s;
}
public static bool HasStartDate<T>(this T subject)
where T : IIncompleteDate
{
return subject.YearOfStart > 0 || subject.MonthOfStart > 0 || subject.DayOfStart > 0;
}
public static bool HasEndDate<T>(this T subject)
where T : IIncompleteDate
{
return subject.YearOfEnd > 0 || subject.MonthOfEnd > 0 || subject.DayOfEnd > 0;
}
/// <summary>
/// Fills in incomplete start date with minimal values.
/// </summary>
/// <returns>Null on invalid date.</returns>
public static DateTime? GetStartDateTime<T>(this T subject)
where T : IIncompleteDate
{
string y, m, d;
y = subject.YearOfStart > 0 ? subject.YearOfStart.ToString() : "1";
m = subject.MonthOfStart > 0 ? subject.MonthOfStart.ToString() : "1";
d = subject.DayOfStart > 0 ? subject.DayOfStart.ToString() : "1";
string start = string.Join("-", new string[] { y, m, d });
DateTime result;
if (DateTime.TryParse(start, out result))
return result;
return null;
}
/// <summary>
/// Fills in incomplete end date with maximal values.
/// </summary>
/// <returns>Null on invalid date.</returns>
public static DateTime? GetEndDateTime<T>(this T subject)
where T : IIncompleteDate
{
int y, m, d;
y = subject.YearOfEnd > 0 ? subject.YearOfEnd : 9999;
m = subject.MonthOfEnd > 0 ? subject.MonthOfEnd : 12;
d = subject.DayOfEnd > 0 ? subject.DayOfEnd : DateTime.DaysInMonth(y, m);
string end = string.Join("-", new string[] { y.ToString(), m.ToString(), d.ToString() });
DateTime result;
if (DateTime.TryParse(end, out result))
return result;
return null;
}
/// <summary>
/// Printable date which doesn't attempt to fill in empty values.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="subject"></param>
/// <returns></returns>
public static string GetStartDateString<T>(this T subject)
where T : IIncompleteDate
{
string y, m, d;
y = subject.YearOfStart > 0 ? subject.YearOfStart.ToString() : "-";
m = subject.MonthOfStart > 0 ? subject.MonthOfStart.ToString() : "-";
d = subject.DayOfStart > 0 ? subject.DayOfStart.ToString() : "-";
return string.Join("/", new string[] { y, m, d });
}
/// <summary>
/// Printable date which doesn't attempt to fill in empty values.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="subject"></param>
/// <returns></returns>
public static string GetEndDateString<T>(this T subject)
where T : IIncompleteDate
{
string y, m, d;
y = subject.YearOfEnd > 0 ? subject.YearOfEnd.ToString() : "-";
m = subject.MonthOfEnd > 0 ? subject.MonthOfEnd.ToString() : "-";
d = subject.DayOfEnd > 0 ? subject.DayOfEnd.ToString() : "-";
return string.Join("/", new string[] { y, m, d });
}
public static bool IsCurrentAsOf<T>(this T subject, DateTime asOf)
where T : IIncompleteDate
{
if (subject.HasStartDate() && subject.GetStartDateTime() < asOf)
return false;
if (subject.HasEndDate() && subject.GetEndDateTime() > asOf)
return false;
return true;
}
public static string PrintDates<T>(this T subject)
where T : IIncompleteDate
{
string s = string.Empty;
if (subject.HasStartDate())
s += "from " + subject.GetStartDateString();
if (subject.HasEndDate())
s += (subject.HasStartDate() ? " " : string.Empty) + "until " + subject.GetEndDateString();
return s;
}
public static object GetIncompleteStartDate<T>(this T subject)
where T : IIncompleteDate
{
if (subject.HasStartDate())
{
dynamic o = new ExpandoObject();
if (subject.YearOfStart > 0)
o.year = subject.YearOfStart;
if (subject.MonthOfStart > 0)
o.month = subject.MonthOfStart;
if (subject.DayOfStart > 0)
o.day = subject.DayOfStart;
return o;
}
return null;
}
public static object GetIncompleteEndDate<T>(this T subject)
where T : IIncompleteDate
{
if (subject.HasEndDate())
{
dynamic o = new ExpandoObject();
if (subject.YearOfEnd > 0)
o.year = subject.YearOfEnd;
if (subject.MonthOfEnd > 0)
o.month = subject.MonthOfEnd;
if (subject.DayOfEnd > 0)
o.day = subject.DayOfEnd;
return o;
}
return null;
}
/// <summary>
/// Returns TimelineJS date object.
/// </summary>
/// <returns></returns>
public static object GetTimelineStartDateObject<T>(this T subject)
where T : IIncompleteDate
{
if (subject.HasStartDate())
return subject.GetIncompleteStartDate();
else if (subject.HasEndDate())
return subject.GetIncompleteEndDate();
return null;
}
/// <summary>
/// Returns TimelineJS date object.
/// </summary>
/// <returns></returns>
public static object GetTimelineEndDateObject<T>(this T subject)
where T : IIncompleteDate
{
if (subject.HasEndDate())
return subject.GetIncompleteEndDate();
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// 空白ページのアイテム テンプレートについては、http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 を参照してください
namespace TimerSample001
{
/// <summary>
/// それ自体で使用できる空白ページまたはフレーム内に移動できる空白ページ。
/// </summary>
public sealed partial class MainPage : Page
{
private DispatcherTimer _timer;
// イベントの実行回数をカウントする変数
private int _count;
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this._timer = new DispatcherTimer();
// タイマーイベントの間隔を指定。
// ここでは1秒おきに実行する
this._timer.Interval = TimeSpan.FromSeconds(1);
// 1秒おきに実行するイベントを指定
this._timer.Tick += _timer_Tick;
// タイマーイベントを開始する
this._timer.Start();
}
private void _timer_Tick(object sender, object e)
{
// コメントアウト(以下のコメントアウトコードを有効にするとUIスレッドで重い処理を実行した結果が確認できます。)
// ここで重たい処理発生
// ボタンの上にマウスオーバーした際にボタンがハイライトされるか確認してみましょう
//while(true)
//{
// System.Diagnostics.Debug.WriteLine("終わらない");
//}
// カウントを1加算
this._count++;
// TextBlockにカウントを表示
this.textBlock.Text = this._count.ToString();
}
private void button_Click(object sender, RoutedEventArgs e)
{
if (this._timer.IsEnabled == true)
{
this._timer.Stop();
this.button.Content = "タイマー再開";
}
else
{
this._timer.Start();
this.button.Content = "タイマー停止";
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class Card : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerDownHandler, IPointerUpHandler
{
public static float STACK_OFFSET = -26;
public static float DROP_DISTANCE = 35;
public GameObject highlight;
public Image suitImage;
public bool isFrontCard;
private int number;
private int suit;
private Transform canvas;
private bool hasDragged = false;
private bool hasStartedClick = false;
public void Initialize(int number, int suit, Sprite suitSprite, Transform canvas)
{
this.number = number;
this.suit = suit;
GetComponentInChildren<Text>().text = GetStringFromNumber(number);
suitImage.sprite = suitSprite;
this.canvas = canvas;
}
private string GetStringFromNumber(int number)
{
switch (number)
{
case 1:
return "A";
case 11:
return "J";
case 12:
return "Q";
case 13:
return "K";
default:
return number.ToString();
}
}
public void OnBeginDrag(PointerEventData eventData)
{
hasDragged = true;
if (isFrontCard)
{
transform.SetParent(canvas);
CardManager.inst.StartCardDrag(this);
}
}
public void OnDrag(PointerEventData eventData)
{
if (isFrontCard)
{
transform.position = Input.mousePosition;
CardManager.inst.CardDrag(this);
}
}
public void OnEndDrag(PointerEventData eventData)
{
hasDragged = false;
if (isFrontCard)
{
CardManager.inst.EndCardDrag(this);
}
}
public void Highlight()
{
highlight.SetActive(true);
}
public void StopHighlight()
{
highlight.SetActive(false);
}
public bool IsRed()
{
return suit == 0 || suit == 2;
}
public int GetSuit()
{
return suit;
}
public int GetNumber()
{
return number;
}
public void OnPointerDown(PointerEventData eventData)
{
hasStartedClick = true;
}
public void OnPointerUp(PointerEventData eventData)
{
if (hasStartedClick && !hasDragged && isFrontCard)
{
CardManager.inst.TryAddCardToFreeCell(this);
}
}
}
|
using System;
using Uintra.Infrastructure.TypeProviders;
namespace Uintra.Features.Permissions.TypeProviders
{
public class PermissionActionTypeProvider : EnumTypeProviderBase, IPermissionActionTypeProvider
{
public PermissionActionTypeProvider(params Type[] enums) : base(enums)
{
}
}
} |
namespace ForceBook
{
using System;
using System.Collections.Generic;
using System.Linq;
public class StartUp
{
public static void Main()
{
var command = Console.ReadLine();
var forceRegister = new Dictionary<string, List<string>>();
var forceUsers = new List<string>();
while (command != "Lumpawaroo")
{
if (command.Contains("|"))
{
var input = command.Split(new string[] { " | " }, StringSplitOptions.RemoveEmptyEntries).ToArray();
var forceSide = input[0];
var forceUser = input[1];
if (forceRegister.ContainsKey(forceSide) == false)
{
if (forceUsers.Contains(forceUser) == false)
{
forceRegister.Add(forceSide, new List<string>());
forceRegister[forceSide].Add(forceUser);
forceUsers.Add(forceUser);
}
}
else
{
if (forceUsers.Contains(forceUser) == false)
{
forceRegister[forceSide].Add(forceUser);
forceUsers.Add(forceUser);
}
}
}
if (command.Contains("->"))
{
var input = command.Split(new string[] { " -> " }, StringSplitOptions.RemoveEmptyEntries).ToArray();
var forceSide = input[1];
var forceUser = input[0];
if (forceUsers.Contains(forceUser))
{
var otherSide = forceRegister.First(x => x.Value.Contains(forceUser)).Key;
forceRegister[otherSide].Remove(forceUser);
if (forceRegister.ContainsKey(forceSide) == false)
{
forceRegister.Add(forceSide, new List<string>());
}
forceUsers.Add(forceUser);
forceRegister[forceSide].Add(forceUser);
Console.WriteLine($"{forceUser} joins the {forceSide} side!");
}
else
{
if (forceRegister.ContainsKey(forceSide) == false)
{
forceUsers.Add(forceUser);
forceRegister.Add(forceSide, new List<string>());
}
forceRegister[forceSide].Add(forceUser);
Console.WriteLine($"{forceUser} joins the {forceSide} side!");
}
}
command = Console.ReadLine();
}
foreach (var side in forceRegister.OrderByDescending(x => x.Value.Count).ThenBy(x => x.Key))
{
if (side.Value.Count == 0)
{
continue;
}
else
{
side.Value.Sort();
}
Console.WriteLine($"Side: {side.Key}, Members: {side.Value.Count}");
foreach (var user in side.Value)
{
Console.WriteLine($"! {user}");
}
}
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using TG.Blazor.IndexedDB;
using WebApplication1.Models;
namespace WebApplication1.DataAccess
{
public class RepositoryJob : RepositoryJobImpl
{
public RepositoryJob(IndexedDBManager dbManager)
: base(dbManager)
{
}
public override string Storename()
{
return "job";
}
}
} |
using System.Collections.Generic;
using CodingMilitia.PlayBall.WebFrontend.BackForFront.Web.AuthTokenHelpers;
using CodingMilitia.PlayBall.WebFrontend.BackForFront.Web.Configuration;
using IdentityModel;
using IdentityModel.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.DataProtection;
using System.IO;
using System.Net;
using CodingMilitia.PlayBall.WebFrontend.BackForFront.Web.ApiRouting;
using CodingMilitia.PlayBall.WebFrontend.BackForFront.Web.Security;
using Microsoft.Extensions.Hosting;
using ProxyKit;
[assembly: ApiController]
namespace CodingMilitia.PlayBall.WebFrontend.BackForFront.Web
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services
.AddControllers()
.AddControllersAsServices();
services.AddSingleton(serviceProvider =>
{
var configuration = serviceProvider.GetRequiredService<IConfiguration>();
return configuration.GetSection<AuthServiceSettings>("AuthServiceSettings");
});
services.AddSingleton<IDiscoveryCache>(serviceProvider =>
{
var authServiceConfig = serviceProvider.GetRequiredService<AuthServiceSettings>();
var factory = serviceProvider.GetRequiredService<IHttpClientFactory>();
return new DiscoveryCache(authServiceConfig.Authority, () => factory.CreateClient());
});
services
.AddHttpClient<ITokenRefresher, TokenRefresher>();
services
.AddTransient<CustomCookieAuthenticationEvents>()
.AddTransient<AccessTokenHttpMessageHandler>()
.AddHttpContextAccessor();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies", options => { options.EventsType = typeof(CustomCookieAuthenticationEvents); })
.AddOpenIdConnect("oidc", options =>
{
var authServiceConfig = _configuration.GetSection<AuthServiceSettings>("AuthServiceSettings");
options.SignInScheme = "Cookies";
options.Authority = authServiceConfig.Authority;
options.RequireHttpsMetadata = authServiceConfig.RequireHttpsMetadata;
options.ClientId = authServiceConfig.ClientId;
options.ClientSecret = authServiceConfig.ClientSecret;
options.ResponseType = OidcConstants.ResponseTypes.Code;
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("GroupManagement");
options.Scope.Add(OidcConstants.StandardScopes.OfflineAccess);
options.CallbackPath = "/auth/signin-oidc";
options.Events.OnRedirectToIdentityProvider = context =>
{
if (!context.HttpContext.Request.Path.StartsWithSegments("/auth/login"))
{
context.HttpContext.Response.StatusCode = 401;
context.HandleResponse();
}
return Task.CompletedTask;
};
});
services
.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
var dataProtectionKeysLocation =
_configuration.GetSection<DataProtectionSettings>(nameof(DataProtectionSettings))?.Location;
if (!string.IsNullOrWhiteSpace(dataProtectionKeysLocation))
{
services
.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(dataProtectionKeysLocation));
// TODO: encrypt the keys
}
services.AddProxy();
services.AddSingleton(
new ProxiedApiRouteEndpointLookup(
_configuration.GetSection<Dictionary<string, string>>("ApiRoutes")));
services
.AddSingleton<EnforceAuthenticatedUserMiddleware>()
.AddSingleton<ValidateAntiForgeryTokenMiddleware>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseMiddleware<EnforceAuthenticatedUserMiddleware>();
app.UseMiddleware<ValidateAntiForgeryTokenMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.Map("/api", api =>
{
api.RunProxy(async context =>
{
var endpointLookup = context.RequestServices.GetRequiredService<ProxiedApiRouteEndpointLookup>();
if (endpointLookup.TryGet(context.Request.Path, out var endpoint))
{
var forwardContext = context
.ForwardTo(endpoint)
.CopyXForwardedHeaders();
var token = await context.GetAccessTokenAsync();
forwardContext.UpstreamRequest.SetBearerToken(token);
return await forwardContext.Send();
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
});
});
}
}
} |
using System.Collections.Generic;
using System.Data.Entity;
using System.Security.Cryptography;
using System.Text;
using UsersLib.Entity;
namespace UsersLib.DbContextSettings
{
public class DbInitializer: CreateDatabaseIfNotExists<UsersLibDbContext>
{
protected override void Seed(UsersLibDbContext db)
{
User user = new User
{
DisplayName = "Administrator",
UserAccount = new UserAccount
{
Login = "admin",
Password = GetPasswordHashString("admin")
},
UserRoles = new List<UserRole>
{
new UserRole
{
Role = UserRoleKind.Admin
}
}
};
db.Users.Add(user);
db.SaveChanges();
}
private string GetPasswordHashString(string password)
{
SHA256 hasher = SHA256.Create();
byte[] bytes = Encoding.UTF8.GetBytes(password);
string hash = Encoding.UTF8.GetString(hasher.ComputeHash(bytes));
return hash;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using ShoppingList.Models;
using System.Collections.ObjectModel;
using SQLite;
using Xamarin.Forms;
using ShoppingList.Helpers;
namespace ShoppingList.Services
{
public class ShoppingListManager
{
private static ShoppingListManager instance;
private ShoppingDatabase database;
public ShoppingDatabase Database
{
get
{
if (database == null)
{
database = new ShoppingDatabase(DependencyService.Get<IFileHelper>().GetLocalFilePath("shoppingDatabase.db3"));
}
return database;
}
}
public static ShoppingListManager Instance
{
get
{
if (instance == null)
instance = new ShoppingListManager();
return instance;
}
}
private ShoppingListManager()
{
}
}
}
|
namespace AssessmentApp.Services.Data
{
using System.Collections.Generic;
using AssessmentApp.Web.ViewModels.Assessments;
public interface IAssessmentsService
{
IEnumerable<T> GetAll<T>(int? count = null);
object GetViewByAssessmentId(string id);
HygieneAssessmentInputViewModel GetHygieneAssessmentVm(string userId, string userName);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WystawkaAPI.Models
{
public class Foto
{
public int FotoID { get; set; }
public string FotoLocalization { get; set; }
}
} |
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Com.Colin.Web
{
/// <summary>
/// Summary description for LoginControl
/// </summary>
[DefaultProperty("Text")]
[ToolboxData("<{0}:BBSLogin runat=server></{0}:BBSLogin>")]
public class BBSLogin: WebControl
{
//创建服务器控件
public TextBox NameTextBox = new TextBox();
public TextBox PasswordTextBox = new TextBox();
public Button LoginButton = new Button();
public event EventHandler LoginClick;
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text
{
get
{
string s = (string)ViewState["Text"];
return ((s == null) ? "[" + ID + "]" : s);
}
set
{
ViewState["Text"] = value;
}
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string LoignBackGroundColor
{
get { return (string)ViewState["LoignBackGroundColor"]; }
set { ViewState["LoignBackGroundColor"] = value; }
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string LoginBorderWidth
{
get { return (string)ViewState["LoginBorderWidth"]; }
set { ViewState["LoginBorderWidth"] = value; }
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string LoginPadding
{
get { return (string)ViewState["LoginPadding"]; }
set { ViewState["LoginPadding"] = value; }
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string LoginInformation
{
get { return (string)ViewState["LoginInformation"]; }
set { ViewState["LoginInformation"] = value; }
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string ResignURL
{
get { return (string)ViewState["ResignURL"]; }
set { ViewState["ResignURL"] = value; }
}
public void Submit_Click(object sender, EventArgs e)
{
EventArgs arg = new EventArgs();
LoginClick?.Invoke(LoginButton, arg);
}
protected override void RenderContents(HtmlTextWriter output)
{
output.RenderBeginTag(HtmlTextWriterTag.Div);
output.RenderBeginTag(HtmlTextWriterTag.Tr);
NameTextBox.RenderControl(output);
output.RenderBeginTag(HtmlTextWriterTag.Td);
output.RenderBeginTag(HtmlTextWriterTag.Br);
output.RenderBeginTag(HtmlTextWriterTag.Tr);
PasswordTextBox.RenderControl(output);
output.RenderBeginTag(HtmlTextWriterTag.Td);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZM.TiledScreenDesigner
{
public enum ImageLayout
{
None,
Fill,
FillKeepRatio,
FillKeepRatioAndCrop
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KinectSandbox.Common.Colors
{
public struct RGB
{
public byte R;
public byte G;
public byte B;
public RGB(byte r, byte g, byte b)
{
this.R = r;
this.G = g;
this.B = b;
}
public static RGB Black
{
get { return new RGB(0,0,0); }
}
public static RGB White
{
get { return new RGB(byte.MaxValue, byte.MaxValue, byte.MaxValue); }
}
public static RGB Red
{
get { return new RGB(byte.MaxValue, 0, 0); }
}
public static RGB Lime
{
get { return new RGB(0, byte.MaxValue, 0); }
}
public static RGB Blue
{
get { return new RGB(0, 0, byte.MaxValue); }
}
public static RGB Yellow
{
get { return new RGB(byte.MaxValue, byte.MaxValue, 0); }
}
public static RGB Cyan
{
get { return new RGB(0, byte.MaxValue, byte.MaxValue); }
}
public static RGB Magenta
{
get { return new RGB(byte.MaxValue, 0, byte.MaxValue); }
}
public static RGB Silver
{
get { return new RGB(192, 192, 192); }
}
public static RGB Gray
{
get { return new RGB(128, 128, 128); }
}
public static RGB Maroon
{
get { return new RGB(128, 0, 0); }
}
public static RGB Olive
{
get { return new RGB(128, 128, 0); }
}
public static RGB Green
{
get { return new RGB(0, 128, 0); }
}
public static RGB Purple
{
get { return new RGB(128, 0, 128); }
}
public static RGB Teal
{
get { return new RGB(0, 128, 128); }
}
public static RGB Navy
{
get { return new RGB(0, 0, 128); }
}
public RGB ApplyIntensity(byte intensity)
{
var r = (byte)(this.R * intensity);
var g = (byte)(this.G * intensity);
var b = (byte)(this.B * intensity);
return new RGB(r, g, b);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace TYNMU.manger
{
public partial class left : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//判断是否登录
if (Session.Count==0||Session["IsLogin"]==null)
{
Response.Write("<script language='JavaScript'>parent.window.location='Login.aspx';</script>");
return;
}
//绑定框架
TreeView1.Target = "mainFrame";
//生成节点
AddNode();
}
private void AddNode()
{
string sSql = "select * from T_tree";
string[] level = Session["UserLevel"].ToString().Split(',');
DataTable dt = new DataTable();
dt = Data.DAO.Query(sSql).Tables[0];
this.TreeView1.Nodes.Clear();
DataView dv = dt.DefaultView;
dv.RowFilter = "ParentID=0";//筛选出根节点
foreach (DataRowView drv in dv)
{
//此处添加用户权限
foreach (string str in level)
{
if (str.Trim().Equals(drv.Row["ID"].ToString().Trim()))
{
TreeNode root = new TreeNode(drv.Row["Name"].ToString(), drv.Row["ID"].ToString());
root.NavigateUrl = drv.Row["url"].ToString();
this.TreeView1.Nodes.Add(root);
}
}
}
//加入子节点
for (int i = 0; i < this.TreeView1.Nodes.Count; i++)
{
this.AddChildNode(dt, this.TreeView1.Nodes[i]);
}
}
private void AddChildNode(DataTable dt, TreeNode node)
{
DataView dv = dt.DefaultView;
string[] level = Session["UserLevel"].ToString().Split(',');
dv.RowFilter = "ParentID=" + node.Value.Trim();
foreach (DataRowView drv in dv)
{
//此处添加用户权限管理
foreach (string str in level)
{
if (str.Trim().Equals(drv.Row["ID"].ToString().Trim()))
{
TreeNode childNode = new TreeNode(drv.Row["Name"].ToString(), drv.Row["ID"].ToString());
//增加url
childNode.NavigateUrl = drv.Row["url"].ToString();
node.ChildNodes.Add(childNode);
}
}
}
for (int i = 0; i < node.ChildNodes.Count; i++)
{
AddChildNode(dt, node.ChildNodes[i]);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Data
{
public class Snow
{
public float _3h { get; set; }
}
}
|
using Akka.Actor;
using Akka.TestKit.Xunit2;
using ConnelHooley.AkkaTestingHelpers;
using DirectoryBackupService.Shared.Actors;
using System;
using System.IO;
using Xunit;
using DirectoryBackupService.Shared.Models;
using System.Text;
using FluentAssertions;
using ConnelHooley.TestHelpers;
using System.Threading;
namespace DirectoryBackupService.Shared.SmallTests.Actors
{
public class SourceActorTests : TestKit
{
private readonly string _directory;
private readonly string _filePath1;
private readonly string _filePath2;
public SourceActorTests()
{
const string fileName1 = "File1.txt";
const string fileName2 = "File2.txt";
_directory = $@"C:\Tests\{Guid.NewGuid()}";
_filePath1 = Path.Combine(_directory, fileName1);
_filePath2 = Path.Combine(_directory, fileName2);
Directory.CreateDirectory(_directory);
DeleteFile(_filePath1);
DeleteFile(_filePath2);
}
private UnitTestFramework<SourceActor> ArrangeSourceActor()
{
//Arrange
var framework = UnitTestFrameworkSettings
.Empty
.CreateFramework<SourceActor>(this, Props.Create(() => new SourceActor(new SourceSettings(_directory, "2"))), 1);
framework.Supervisor.ExpectMsg<SourceActor.SetUpCompleteMessage>();
return framework;
}
//[Fact]
//public void SourceActor_FileIsCreatedAndUpdatedMultipleTimesInQuickSuccession_SendsOneUpsertMessageWithTheLatestFileContentsToChild()
//{
// //Arrange
// var framework = ArrangeSourceActor();
// // Act
// File.WriteAllText(_filePath1, Guid.NewGuid().ToString());
// File.WriteAllText(_filePath1, Guid.NewGuid().ToString());
// File.WriteAllText(_filePath1, Guid.NewGuid().ToString());
// File.WriteAllText(_filePath1, Guid.NewGuid().ToString());
// var expectedFileContentText = Guid.NewGuid().ToString();
// var expectedFileContentBytes = Encoding.ASCII.GetBytes(expectedFileContentText);
// File.WriteAllText(_filePath1, expectedFileContentText);
// // Assert
// var expected = new DestinationActor.UpsertFileMessage(
// Path.GetFileName(_filePath1));
// framework
// .ResolvedTestProbe("destination")
// .ExpectMsg<DestinationActor.UpsertFileMessage>()
// .Should().BeEquivalentTo(expected);
//}
//[Fact]
//public void SourceActor_FileIsCreatedAndDeletedInQuickSuccession_NoMessageIsSentToChild()
//{
// //Arrange
// var framework = ArrangeSourceActor();
// // Act
// File.WriteAllText(_filePath1, Guid.NewGuid().ToString());
// File.Delete(_filePath1);
// // Assert
// framework
// .ResolvedTestProbe("destination")
// .ExpectNoMsg();
//}
[Fact]
public void SourceActor_FileIsCreatedAndUpdatedAndDeletedAndCreatedAndUpdatedInQuickSuccession_SendsOneUpsertMessageToChild()
{
//Arrange
var framework = ArrangeSourceActor();
// Act
WriteFile(_filePath1);
WriteFile(_filePath1);
DeleteFile(_filePath1);
WriteFile(_filePath1);
WriteFile(_filePath1);
var fileContents = WriteFile(_filePath1);
// Assert
framework
.ResolvedTestProbe("destination")
.ExpectMsg<DestinationActor.UpsertFileMessage>()
.Should().BeEquivalentTo(new DestinationActor.UpsertFileMessage(_filePath1));
framework
.ResolvedTestProbe("destination")
.ExpectNoMsg();
}
[Fact]
public void SourceActor_FileIsCreatedAndDeletedInQuickSuccession_DoesNotAnyMessagesToChild()
{
//Arrange
var framework = ArrangeSourceActor();
// Act
WriteFile(_filePath1);
DeleteFile(_filePath1);
// Assert
framework
.ResolvedTestProbe("destination")
.ExpectNoMsg();
}
[Fact]
public void SourceActor_FileIsCreatedAndUpdatedAndRenamed_SendsAnUpsertMessageThenARenameMessageToChild()
{
//Arrange
var framework = ArrangeSourceActor();
// Act
WriteFile(_filePath1);
var fileContents = WriteFile(_filePath1);
RenameFile(_filePath1, _filePath2);
// Assert
framework
.ResolvedTestProbe("destination")
.ExpectMsg<DestinationActor.UpsertFileMessage>()
.Should().BeEquivalentTo(new DestinationActor.UpsertFileMessage(_filePath1));
framework
.ResolvedTestProbe("destination")
.ExpectMsg<DestinationActor.RenameFileMessage>()
.Should().BeEquivalentTo(new DestinationActor.RenameFileMessage(
_filePath1,
_filePath2));
framework
.ResolvedTestProbe("destination")
.ExpectNoMsg();
}
[Fact]
public void SourceActor_FileIsCreatedAndUpdatedAndDeletedInQuickSuccession_DoesNotSendAnyMessagesToChild()
{
//Arrange
var framework = ArrangeSourceActor();
// Act
WriteFile(_filePath1);
WriteFile(_filePath1);
WriteFile(_filePath1);
DeleteFile(_filePath1);
// Assert
framework
.ResolvedTestProbe("destination")
.ExpectNoMsg();
}
[Fact]
public void SourceActor_FileIsCreated_SendsOneUpsertMessageToChild()
{
// Arrange
var framework = ArrangeSourceActor();
// Act
var fileContents = WriteFile(_filePath1);
// Assert
framework
.ResolvedTestProbe("destination")
.ExpectMsg<DestinationActor.UpsertFileMessage>()
.Should().BeEquivalentTo(new DestinationActor.UpsertFileMessage(_filePath1));
framework
.ResolvedTestProbe("destination")
.ExpectNoMsg();
}
[Fact]
public void SourceActor_ExistingFileIsDeleted_SendsOneDeleteMessageToChild()
{
// Arrange
WriteFile(_filePath1);
var framework = ArrangeSourceActor();
// Act
DeleteFile(_filePath1);
// Assert
framework
.ResolvedTestProbe("destination")
.ExpectMsg<DestinationActor.DeleteFileMessage>()
.Should().BeEquivalentTo(new DestinationActor.DeleteFileMessage(_filePath1));
framework
.ResolvedTestProbe("destination")
.ExpectNoMsg();
}
[Fact]
public void SourceActor_ExistingFileIsUpdated_SendsOneUpsertMessageToChild()
{
// Arrange
WriteFile(_filePath1);
var framework = ArrangeSourceActor();
// Act
var fileContent = WriteFile(_filePath1);
// Assert
framework
.ResolvedTestProbe("destination")
.ExpectMsg<DestinationActor.UpsertFileMessage>()
.Should().BeEquivalentTo(new DestinationActor.UpsertFileMessage(
_filePath1));
framework
.ResolvedTestProbe("destination")
.ExpectNoMsg();
}
[Fact]
public void SourceActor_ExistingFileIsRenamed_SendsOneRenameMessageToChild()
{
// Arrange
WriteFile(_filePath1);
var framework = ArrangeSourceActor();
// Act
RenameFile(_filePath1, _filePath2);
// Assert
framework
.ResolvedTestProbe("destination")
.ExpectMsg<DestinationActor.RenameFileMessage>()
.Should().BeEquivalentTo(new DestinationActor.RenameFileMessage(
_filePath1,
_filePath2));
framework
.ResolvedTestProbe("destination")
.ExpectNoMsg();
}
private static byte[] WriteFile(string filePath)
{
var fileContent = TestHelper.GenerateStringFrom(TestHelper.AlphaNumeric);
var fileContentBytes = Encoding.ASCII.GetBytes(fileContent);
File.WriteAllBytes(filePath, fileContentBytes);
return fileContentBytes;
}
private static void DeleteFile(string filePath)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
private static void RenameFile(string existingFilePath, string newFilePath)
{
if (File.Exists(existingFilePath))
{
File.Move(existingFilePath, newFilePath);
}
}
public void Dispose()
{
DeleteFile(_filePath1);
DeleteFile(_filePath2);
Directory.Delete(_directory, true);
base.Dispose();
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Events;
using GFW;
namespace CodeX {
/// <summary>
/// 对象池管理器,分普通类对象池+资源游戏对象池
/// </summary>
public class ObjectPoolManager : ManagerModule {
private Transform m_PoolRootObject = null;
private Dictionary<string, object> m_ObjectPools = new Dictionary<string, object>();
private Dictionary<string, GameObjectPool> m_GameObjectPools = new Dictionary<string, GameObjectPool>();
Transform PoolRootObject {
get {
if (m_PoolRootObject == null) {
var objectPool = new GameObject("ObjectPool");
objectPool.transform.SetParent(m_Mono.transform);
objectPool.transform.localScale = Vector3.one;
objectPool.transform.localPosition = Vector3.zero;
m_PoolRootObject = objectPool.transform;
}
return m_PoolRootObject;
}
}
public GameObjectPool CreatePool(string poolName, int initSize, int maxSize, GameObject prefab) {
var pool = new GameObjectPool(poolName, prefab, initSize, maxSize, PoolRootObject);
m_GameObjectPools[poolName] = pool;
return pool;
}
public GameObjectPool GetPool(string poolName) {
if (m_GameObjectPools.ContainsKey(poolName)) {
return m_GameObjectPools[poolName];
}
return null;
}
public GameObject Get(string poolName) {
GameObject result = null;
if (m_GameObjectPools.ContainsKey(poolName)) {
GameObjectPool pool = m_GameObjectPools[poolName];
result = pool.NextAvailableObject();
if (result == null) {
Debug.LogWarning("No object available in pool. Consider setting fixedSize to false.: " + poolName);
}
} else {
Debug.LogError("Invalid pool name specified: " + poolName);
}
return result;
}
public void Release(string poolName, GameObject go) {
if (m_GameObjectPools.ContainsKey(poolName)) {
GameObjectPool pool = m_GameObjectPools[poolName];
pool.ReturnObjectToPool(poolName, go);
} else {
Debug.LogWarning("No pool available with name: " + poolName);
}
}
///-----------------------------------------------------------------------------------------------
public ObjectPool<T> CreatePool<T>(UnityAction<T> actionOnGet, UnityAction<T> actionOnRelease) where T : class {
var type = typeof(T);
var pool = new ObjectPool<T>(actionOnGet, actionOnRelease);
m_ObjectPools[type.Name] = pool;
return pool;
}
public ObjectPool<T> GetPool<T>() where T : class {
var type = typeof(T);
ObjectPool<T> pool = null;
if (m_ObjectPools.ContainsKey(type.Name)) {
pool = m_ObjectPools[type.Name] as ObjectPool<T>;
}
return pool;
}
public T Get<T>() where T : class {
var pool = GetPool<T>();
if (pool != null) {
return pool.Get();
}
return default(T);
}
public void Release<T>(T obj) where T : class {
var pool = GetPool<T>();
if (pool != null) {
pool.Release(obj);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Assets.Scripts;
using UnityEngine.UI;
public class Line : MonoBehaviour {
public LineRenderer lineRenderer { get; set; }
public GameObject FirstSphere { get; set; }
public GameObject SecondSphere { get; set; }
private EdgeCollider2D edgeCollider;
private GameInit gameInit;
private bool createAnimationFinished = false;
public void startInitAnimation(Sphere firstSphere, Sphere secondSphere)
{
StartCoroutine(initAnimation(firstSphere, secondSphere));
}
private void Awake()
{
lineRenderer = GetComponent<LineRenderer>();
edgeCollider = GetComponent<EdgeCollider2D>();
edgeCollider.enabled = false;
gameInit = GameObject.Find("Initialization").GetComponent<GameInit>();
}
private void Start()
{
lineRenderer.material = new Material(Shader.Find("Mobile/Particles/Additive"));
lineRenderer.startColor = new Color(0, 40, 235);
lineRenderer.endColor = Color.blue;
lineRenderer.startWidth = 0.1f;
lineRenderer.endWidth = 0.1f;
lineRenderer.positionCount = 2;
//edgeCollider.isTrigger = true;
transform.position = Vector3.zero;
transform.localScale = Vector3.one;
edgeCollider.edgeRadius = .1f;
}
private void Update()
{
if (createAnimationFinished)
{
lineRenderer.SetPosition(0, FirstSphere.transform.position);
lineRenderer.SetPosition(1, SecondSphere.transform.position);
transform.position = Vector3.zero;
Vector2[] tempArray = edgeCollider.points;
tempArray[0].x = lineRenderer.GetPosition(0).x;
tempArray[0].y = lineRenderer.GetPosition(0).y;
tempArray[1].x = lineRenderer.GetPosition(1).x;
tempArray[1].y = lineRenderer.GetPosition(1).y;
//tempArray[0].x = FirstSphere.transform.position.x;
//tempArray[0].y = FirstSphere.transform.position.y;
//tempArray[1].x = SecondSphere.transform.position.x;
//tempArray[1].y = SecondSphere.transform.position.y;
edgeCollider.points = tempArray;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag == "Cut" && gameObject != null)
{
GameObject waterSplash = Instantiate(gameInit.waterSplashPrefab, collision.transform.position, new Quaternion());
Destroy(waterSplash, 1f);
Destroy(gameObject);
GameObject.Find("Canvas").transform.GetChild(3).GetChild(0).GetComponent<Image>().fillAmount += .1f;
gameInit.lines.Remove(
gameInit.lines.Find(_ => _ == gameObject));
gameInit.Score += 5;
FirstSphere.GetComponent<Sphere>().IsTied = false;
SecondSphere.GetComponent<Sphere>().IsTied = false;
byte disappearProbability = (byte)Random.Range(0, 9);
byte sphereProbability = (byte)Random.Range(0, 2);
if (disappearProbability <= 8)
{
if (sphereProbability == 0 && FirstSphere != null)
{
gameInit.spheres.Remove(
gameInit.spheres.Find(_ => _ == FirstSphere.gameObject));
gameInit.NumberOfSpheres -= 1;
GameObject sphereDeathEffect = Instantiate(gameInit.sphereDeathEffectPrefab, FirstSphere.transform.position, new Quaternion());
Destroy(sphereDeathEffect, 1f);
FirstSphere.GetComponent<Sphere>().DestroySphere();
//Destroy(FirstSphere);
gameInit.spheres.Remove(
gameInit.spheres.Find(_ => _ == SecondSphere.gameObject));
gameInit.NumberOfSpheres -= 1;
GameObject sphereDeathEffect_1 = Instantiate(gameInit.sphereDeathEffectPrefab, SecondSphere.transform.position, new Quaternion());
Destroy(sphereDeathEffect_1, 1f);
SecondSphere.GetComponent<Sphere>().DestroySphere();
//Destroy(SecondSphere);
}
else if (SecondSphere != null)
{
gameInit.spheres.Remove(
gameInit.spheres.Find(_ => _ == SecondSphere.gameObject));
gameInit.NumberOfSpheres -= 1;
GameObject sphereDeathEffect = Instantiate(gameInit.sphereDeathEffectPrefab, SecondSphere.transform.position, new Quaternion());
Destroy(sphereDeathEffect, 1f);
SecondSphere.GetComponent<Sphere>().DestroySphere();
//Destroy(SecondSphere);
}
}
}
}
private IEnumerator initAnimation(Sphere firstSphere, Sphere secondSphere)
{
float counter = 0;
float lineDrawSpeed = .8f;
float distance = Vector3.Distance(firstSphere.transform.position, secondSphere.transform.position);
Vector3 pointA = firstSphere.transform.position;
Vector3 pointB = secondSphere.transform.position;
Vector3 pointAlongLine = firstSphere.transform.position;
firstSphere.IsTied = true;
secondSphere.IsTied = true;
while (pointAlongLine != secondSphere.transform.position)
{
if (counter < distance)
{
counter += .1f / lineDrawSpeed;
float x = Mathf.Lerp(0, distance, counter);
pointAlongLine = x * Vector3.Normalize(pointB - pointA) + pointA;
lineRenderer.SetPosition(1, pointAlongLine);
}
yield return new WaitForSeconds(0f);
}
// check null
firstSphere.TiedWith = secondSphere.gameObject;
firstSphere.Line = gameObject;
secondSphere.TiedWith = firstSphere.gameObject;
secondSphere.Line = gameObject;
createAnimationFinished = true;
edgeCollider.enabled = true;
yield return null;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.