text stringlengths 13 6.01M |
|---|
// <copyright file="JsonUtcResult.cs" company="Caspian Pacific Tech">
// Copyright (c) Caspian Pacific Tech. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace SmartLibrary.Site.Classes
{
using System;
using System.Web.Mvc;
using Newtonsoft.Json;
/// <summary>
/// Class for JSON Result.
/// <CreatedBy>Hardik Panchal</CreatedBy>
/// <CreatedDate>14-Aug-2018</CreatedDate>
/// <ModifiedBy></ModifiedBy>
/// <ModifiedDate></ModifiedDate>
/// <ReviewBy>Hardik Panchal</ReviewBy>
/// <ReviewDate>14-Aug-2018</ReviewDate>
/// </summary>
public class JsonUtcResult : JsonResult
{
/// <summary>
/// JSON Serializer Settings
/// </summary>
private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
};
/// <summary>
/// Execute Result
/// </summary>
/// <param name="context">context Value</param>
public override void ExecuteResult(ControllerContext context)
{
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("GET request not allowed");
}
var response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(this.ContentType) ? this.ContentType : "application/json";
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data == null)
{
return;
}
response.Write(JsonConvert.SerializeObject(this.Data, Settings));
}
}
} |
using IrsMonkeyApi.Models.Dto;
namespace IrsMonkeyApi.Models.DAL
{
public interface IProductItemDal
{
ItemProductDto GetProductItems(int productId);
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
namespace SampleMVCSolution.DataAccessLayer.ExchangeResources
{
/*
* These exceptions may be used on higher levels of DAL like repository
* as well as on lower layers like external resources.
* This layers shouldn't know about each other (so each of these can be substituted).
* As a result these exceptions should belong to some neutral namespace
* which may be used by both of these layers.
*
* This is my apology for creating another entity for keeping these exceptions.
* Resource entity is not repository as well as it is not ExternalResource but
* it may be used by both.
**/
public class ExchangeResource
{
// Case 1: Temporary error, timeout is reached, resource is overloaded or under maintainance, etc.
public class TryLaterException : BaseException { }
// Case 2: Permanent error, the request is correct, but impracticable, no such date, change your date.
public class TryRequestingOtherDatesOrCurrency : BaseException
{
public TryRequestingOtherDatesOrCurrency(string message) : base(message) { }
}
// Case 3: Maintainance error, the resource is exhausted, payment is over, some usage limit is reached, app_key is blocked.
// This exception is due to our part.
public class NotifyResourceMaintainer : BaseException
{
public NotifyResourceMaintainer(string messageKeepSecret) : base(messageKeepSecret) { }
public NotifyResourceMaintainer(string messageKeepSecret, Exception innerException) : base(messageKeepSecret, innerException) { }
}
// Case 4: The resource is broken or violates communication protocol.
// This is exception is mostly due to a resource part internal workings,
// but also may be a maintainance error (resource has changed it's api) or our code error (we generated a wrong request and got 404).
// It may be mapped to maintainance exception if the maintainer is interested in all such cases.
public class ResourceBrokageException : BaseException {
public ResourceBrokageException(string messageKeepSecret) : base(messageKeepSecret) { }
}
// Case 5: There is some unhandled exception while requesting resource 'caused by our code.
// This exception is better to be wrapped to attach to it a set of failed dates.
public class NotifyResourceDeveloper : BaseException
{
public NotifyResourceDeveloper(Exception innerException) : this("Unexpected exception was caught.", innerException) { }
public NotifyResourceDeveloper(string message, Exception innerException) : base(message, innerException) { }
}
/*
* Failed dates -- those which were tried to retrive but failed, causing the exception to be thrown.
* Unprocessed dates -- those which were not tried to be retrieved.
*/
public class BaseException : Exception
{
private IEnumerable<DateTime> untouchedDates = Enumerable.Empty<DateTime>();
private IEnumerable<DateTime> failedDates = Enumerable.Empty<DateTime>();
public IEnumerable<DateTime> GetFailedDates()
{
return this.failedDates;
}
public IEnumerable<DateTime> GetUntouchedDates()
{
return this.untouchedDates;
}
public void AddFailedDates(IEnumerable<DateTime> failedDates)
{
Trace.WriteLine("Adding "+ failedDates.Count() +" failed dates.");
this.failedDates = this.failedDates.Concat(failedDates);
}
public void AddFailedDate(DateTime date)
{
this.AddFailedDates(new[] {date});
}
public void AddUntouchedDates(IEnumerable<DateTime> failedDates)
{
this.untouchedDates = this.untouchedDates.Concat(failedDates);
}
public BaseException(string message) : base(message) { }
public BaseException(string message, Exception ex) : base(message, ex) {
var resEx = ex as BaseException;
if (resEx != null)
{
this.failedDates = resEx.failedDates; // TODO: may be fixed in tests.
this.untouchedDates = resEx.untouchedDates;
}
}
public BaseException() : base() { }
}
}
} |
using System;
namespace Aquamonix.Mobile.Lib.Utilities
{
public class MathUtil
{
public static int RoundToNearest(int n, int roundTo)
{
int nn = n;
if (n % roundTo == 0)
return n;
for (int x = 1; x <= roundTo; x++)
{
nn = (n - x);
if (nn % roundTo == 0)
{
return nn;
}
nn = (n + x);
if (nn % roundTo == 0)
{
return nn;
}
}
return n;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XboxCtrlrInput;
public class Wave {
public XboxButton Button;
public float Percentage;
public GameObject WavePrefab;
public bool AttemptedHit;
public Wave(XboxButton button, float percentage, GameObject prefab) {
Button = button;
Percentage = percentage;
WavePrefab = prefab;
AttemptedHit = false;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HZH_Controls.Controls;
using Newtonsoft.Json;
using WordTree.Model;
using WordTree.Service;
namespace StatTracer
{
public partial class TraceForm : Form
{
public List<string> yesterday = new List<string>();
public List<string> today = new List<string>();
public List<string> tomorrow = new List<string>();
//int count = 0;
//int needNum = 0;
float growth = 0.1f;
WordAndDicManager manager = WordAndDicManager.getInstance();
public TraceForm()
{
InitializeComponent();
YesterdayRecordInit();
TodaydayRecordInit();
TomorrowRecordInit();
FormInit(TimeLine1, yesterday);
FormInit(TimeLine2, today);
FormInit(TimeLine3, tomorrow);
PictureBoxInit(plant_pictureBox, pot_pictureBox);
PictureBoxInit(copy1plant_pictureBox, copypot_pictureBox1);
PictureBoxInit(copy3plant_pictureBox, copypot_pictureBox3);
}
private void YesterdayRecordInit()
{
string recordstring = File.ReadAllText("..\\..\\..\\StatTracer\\Record\\history\\hinfo.json");
List<string> records = JsonConvert.DeserializeObject<List<string>>(recordstring);
yesterday = records;
}
private void TodaydayRecordInit()
{
string recordstring = File.ReadAllText("..\\..\\..\\StatTracer\\Record\\current\\cinfo.json");
List<string> records = JsonConvert.DeserializeObject<List<string>>(recordstring);
today = records;
}
public void TomorrowRecordInit()
{
string recordstring = File.ReadAllText("..\\..\\..\\StatTracer\\Record\\temp\\tinfo.json");
List<string> records = JsonConvert.DeserializeObject<List<string>>(recordstring);
tomorrow = records;
}
public void TomorrowFormUpdate()
{
List<Word> words = new List<Word>();
List<TimeLineItem> temps = new List<TimeLineItem>();
foreach (string reco in tomorrow)
{
TimeLineItem temp = new TimeLineItem();
Word word = manager.getWord(reco);
temp.Details = word.Mean_cn + "\r\n" + word.Mean_en + "\r\n" + word.Sentence;
temp.Title = word.word;
temps.Add(temp);
}
if (TimeLine3.InvokeRequired)
{
Action action = new Action(()=> TimeLine3.Items = temps.ToArray());
TimeLine3.Invoke(action);
}
else
{
TimeLine3.Items = temps.ToArray();
}
}
public async void FormInit(UCTimeLine timeLine, List<string> record )
{
List<Word> words = new List<Word>();
List<TimeLineItem> temps = new List<TimeLineItem>();
if (record != null)
{
await Task.Run(() =>
{
foreach (string reco in record)
{
TimeLineItem temp = new TimeLineItem();
Word word = manager.getWord(reco);
temp.Details = word.Mean_cn + "\r\n" + word.Mean_en + "\r\n" + word.Sentence;
temp.Title = word.word;
temps.Add(temp);
}
});
timeLine.Items = temps.ToArray();
}
}
public void SetTree(int count, int needNum)
{
try
{
growth = count / needNum;
}catch(Exception e)
{
growth = 0.1f;
}
if (growth > 0.25 && growth < 0.75) plant_pictureBox.Image = Image.FromFile("..\\..\\..\\StatTracer\\Tree\\seedling.png");
if (growth > 0.75 && growth <= 1)//随机生成植物
{
int index = 1;
Random random = new Random();
index = random.Next(1, 3);
plant_pictureBox.Image = Image.FromFile($"..\\..\\..\\StatTracer\\Tree\\animatedplants\\{index}.gif");
copy1plant_pictureBox.Image = plant_pictureBox.Image;
copy3plant_pictureBox.Image = plant_pictureBox.Image;
}
}
private void PictureBoxInit(PictureBox son, PictureBox parent )
{
son.BackColor = Color.Transparent;
son.Parent = parent;
son.Location = new Point(10, -10);
}
}
internal class MemoryInfo
{
public int count = 0;
public int index = 0;
public List<Node> savedWords = new List<Node>();
public WordLinkedList changingWords = new WordLinkedList();
public MemoryInfo()
{
}
public MemoryInfo(int count, int index, List<Node> savedWords, WordLinkedList changingWords)
{
this.count = count;
this.index = index;
this.savedWords = savedWords;
this.changingWords = changingWords;
}
public bool IsAvailable()
{
return savedWords.Count != 0 && !changingWords.IsEmpty();
}
}
}
|
//
//Code for Research paper on neural networks.
//For questions contact: Sjoerdteunisse at google mail dot com
//
using System.Collections.Generic;
namespace NeuralEngine
{
/// <summary>
/// represents a layer of the neural network
/// </summary>
public class NeuralLayer : List<Neuron>
{
/// <summary>
/// Applies learning to each neuron in the layer
/// </summary>
public void ApplyLearning()
{
foreach (var neuron in this)
neuron.ApplyLearning();
}
/// <summary>
/// Pulse each neuron in layer
/// </summary>
public void Pulse()
{
foreach (var neuron in this)
neuron.Pulse();
}
}
}
|
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Witsml;
using Witsml.Data;
using Witsml.Extensions;
using WitsmlExplorer.Api.Jobs;
using WitsmlExplorer.Api.Models;
using WitsmlExplorer.Api.Query;
using WitsmlExplorer.Api.Services;
namespace WitsmlExplorer.Api.Workers
{
public class BatchModifyWellWorker : IWorker<BatchModifyWellJob>
{
private readonly IWitsmlClient witsmlClient;
public BatchModifyWellWorker(IWitsmlClientProvider witsmlClientProvider)
{
witsmlClient = witsmlClientProvider.GetClient();
}
public async Task<(WorkerResult, RefreshAction)> Execute(BatchModifyWellJob job)
{
Verify(job.Wells);
var wellsToUpdate = job.Wells.Select(well => WellQueries.UpdateWitsmlWell(well));
var updateWellTasks = wellsToUpdate.Select(wellToUpdate => witsmlClient.UpdateInStoreAsync(wellToUpdate));
Task resultTask = Task.WhenAll(updateWellTasks);
await resultTask;
if (resultTask.Status == TaskStatus.Faulted)
{
Log.Error("Job failed. An error occurred when batch updating wells");
return (new WorkerResult(witsmlClient.GetServerHostname(), false, "Failed to batch update well properties"), null);
}
Log.Information("{JobType} - Job successful", GetType().Name);
var workerResult = new WorkerResult(witsmlClient.GetServerHostname(), true, "Batch updated well properties");
var wells = job.Wells.Select(well => well.Uid).ToArray();
var refreshAction = new RefreshWells(witsmlClient.GetServerHostname(), wells, RefreshType.BatchUpdate);
return (workerResult, refreshAction);
}
private void Verify(IEnumerable<Well> wells)
{
if (!wells.Any()) throw new InvalidOperationException("payload cannot be empty");
}
}
}
|
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfApp2
{
/// <summary>
/// Interaction logic for ViewCheckIns.xaml
/// </summary>
public partial class ViewCheckIns : Window
{
public Business currentBus;
public ViewCheckIns(ref Business bus)
{
currentBus = bus;
InitializeComponent();
columnChart();
}
private void columnChart()
{
List<KeyValuePair<string, int>> myChartData = new List<KeyValuePair<string, int>>();
using (var conn = new NpgsqlConnection("Host=localhost; Username=postgres; Password= cpts451; Database=milestone2"))
{
conn.Open();
using (var cmd = new NpgsqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select month,COUNT(business_id) from checkin where business_id = '"+ currentBus.bid + "' group by month order by month";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
myChartData.Add(new KeyValuePair<string, int>(processData(reader.GetInt16(0)), reader.GetInt32(1)));
}
}
}
}
checkInChart.DataContext = myChartData;
}
private string processData(int month)
{
switch (month)
{
case 1: return "January";
case 2: return "February";
case 3: return "March";
case 4: return "April";
case 5: return "May";
case 6: return "June";
case 7: return "July";
case 8: return "Agust";
case 9: return "September";
case 10: return "October";
case 11: return "November";
case 12: return "December";
default: return "";
}
}
}
}
|
using System;
using System.Collections.Generic;
using Profiling2.Domain.Contracts.Queries;
using Profiling2.Domain.Contracts.Tasks;
using Profiling2.Domain.Contracts.Tasks.Sources;
using Profiling2.Domain.Prf.Events;
using Profiling2.Domain.Prf.Organizations;
using Profiling2.Domain.Prf.Persons;
using Profiling2.Domain.Prf.Sources;
using Profiling2.Domain.Prf.Units;
using SharpArch.NHibernate.Contracts.Repositories;
namespace Profiling2.Tasks.Sources
{
public class SourceAttachmentTasks : ISourceAttachmentTasks
{
protected readonly INHibernateRepository<PersonSource> personSourceRepo;
protected readonly INHibernateRepository<EventSource> eventSourceRepo;
protected readonly INHibernateRepository<OrganizationSource> orgSourceRepo;
protected readonly INHibernateRepository<UnitSource> unitSourceRepo;
protected readonly INHibernateRepository<OperationSource> operationSourceRepo;
protected readonly INHibernateRepository<AdminSourceSearch> adminSourceSearchRepository;
protected readonly INHibernateRepository<AdminReviewedSource> adminReviewedSourceRepository;
protected readonly ISourceCollectionsQuery sourceCollectionsQuery;
protected readonly IAdminSourceSearchQuery adminSourceSearchQuery;
protected readonly ISourceTasks sourceTasks;
protected readonly IPersonTasks personTasks;
public SourceAttachmentTasks(INHibernateRepository<PersonSource> personSourceRepo,
INHibernateRepository<EventSource> eventSourceRepo,
INHibernateRepository<OrganizationSource> orgSourceRepo,
INHibernateRepository<UnitSource> unitSourceRepo,
INHibernateRepository<OperationSource> operationSourceRepo,
INHibernateRepository<AdminSourceSearch> adminSourceSearchRepository,
INHibernateRepository<AdminReviewedSource> adminReviewedSourceRepository,
ISourceCollectionsQuery sourceCollectionsQuery,
IAdminSourceSearchQuery adminSourceSearchQuery,
ISourceTasks sourceTasks,
IPersonTasks personTasks)
{
this.personSourceRepo = personSourceRepo;
this.eventSourceRepo = eventSourceRepo;
this.orgSourceRepo = orgSourceRepo;
this.unitSourceRepo = unitSourceRepo;
this.operationSourceRepo = operationSourceRepo;
this.adminSourceSearchRepository = adminSourceSearchRepository;
this.adminReviewedSourceRepository = adminReviewedSourceRepository;
this.sourceCollectionsQuery = sourceCollectionsQuery;
this.adminSourceSearchQuery = adminSourceSearchQuery;
this.sourceTasks = sourceTasks;
this.personTasks = personTasks;
}
// AdminSourceSearches
public AdminSourceSearch GetAdminSourceSearch(int adminSourceSearchId)
{
return this.adminSourceSearchRepository.Get(adminSourceSearchId);
}
public AdminSourceSearch SaveOrUpdateAdminSourceSearch(AdminSourceSearch adminSourceSearch)
{
return this.adminSourceSearchRepository.SaveOrUpdate(adminSourceSearch);
}
public IList<int> GetAdminSourceSearchIds(AdminSourceSearch adminSourceSearch)
{
return this.adminSourceSearchQuery.GetAdminSourceSearchIds(adminSourceSearch);
}
// AdminReviewedSources
public AdminReviewedSource GetOrCreateAdminReviewedSource(int sourceId, int adminSourceSearchId)
{
Source source = this.sourceTasks.GetSource(sourceId);
AdminSourceSearch ass = this.adminSourceSearchRepository.Get(adminSourceSearchId);
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("Source", source);
criteria.Add("AdminSourceSearch", ass);
AdminReviewedSource ars = this.adminReviewedSourceRepository.FindOne(criteria);
if (ars == null)
{
// TODO when creating a new Reviewed record, this source might be marked relevant in another
// equivalent search. However this new Review will be more recent.
// We could prompt the user to remind them to mark it as relevant when they review the source...
ars = new AdminReviewedSource();
ars.ReviewedDateTime = DateTime.Now;
ars.Source = source;
ars.AdminSourceSearch = ass;
ars.Archive = false;
ars = this.adminReviewedSourceRepository.SaveOrUpdate(ars);
}
return ars;
}
public IList<AdminReviewedSource> GetReviewsForSource(int sourceId)
{
return this.sourceCollectionsQuery.GetReviewsForSource(sourceId);
}
// AdminSourceImports
public IList<AdminSourceImport> GetAdminImportsForSource(int sourceId)
{
return this.sourceCollectionsQuery.GetAdminImportsForSource(sourceId);
}
// SourceRelationships
public SourceRelationship GetParentSourceOf(int sourceId)
{
return this.sourceCollectionsQuery.GetParentSourceOf(sourceId);
}
public IList<SourceRelationship> GetChildSourcesOf(int sourceId)
{
return this.sourceCollectionsQuery.GetChildSourcesOf(sourceId);
}
// PersonSources
public PersonSource GetPersonSource(int id)
{
return this.personSourceRepo.Get(id);
}
public IList<PersonSource> GetPersonSources(int sourceId)
{
return this.sourceCollectionsQuery.GetPersonSources(sourceId);
}
public IList<PersonSource> GetPersonSources(Person person, Source source)
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("Person", person);
criteria.Add("Source", source);
return this.personSourceRepo.FindAll(criteria);
}
public PersonSource SavePersonSource(PersonSource ps)
{
ps.Person.AddPersonSource(ps);
ps.Source.AddPersonSource(ps);
if (!ps.Person.HasValidProfileStatus())
{
ps.Person.ProfileStatus = this.personTasks.GetProfileStatus(ProfileStatus.ROUGH_OUTLINE);
this.personTasks.SavePerson(ps.Person);
}
return this.personSourceRepo.SaveOrUpdate(ps);
}
public void DeletePersonSource(int id)
{
this.DeletePersonSource(this.personSourceRepo.Get(id));
}
private void DeletePersonSource(PersonSource ps)
{
if (ps != null)
{
ps.Source.RemovePersonSource(ps);
ps.Person.RemovePersonSource(ps);
this.personSourceRepo.Delete(ps);
}
}
// EventSources
public EventSource GetEventSource(int id)
{
return this.eventSourceRepo.Get(id);
}
public IList<EventSource> GetEventSources(int sourceId)
{
return this.sourceCollectionsQuery.GetEventSources(sourceId);
}
public IList<EventSource> GetEventSources(Event ev, Source source)
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("Event", ev);
criteria.Add("Source", source);
return this.eventSourceRepo.FindAll(criteria);
}
public IList<EventSource> SearchEventSources(string term)
{
return this.sourceCollectionsQuery.SearchEventSources(term);
}
public EventSource SaveEventSource(EventSource es)
{
es.Event.AddEventSource(es);
es.Source.AddEventSource(es);
return this.eventSourceRepo.SaveOrUpdate(es);
}
public void DeleteEventSource(int id)
{
this.DeleteEventSource(this.eventSourceRepo.Get(id));
}
public void DeleteEventSource(EventSource es)
{
if (es != null)
{
es.Source.RemoveEventSource(es);
es.Event.RemoveEventSource(es);
this.eventSourceRepo.Delete(es);
}
}
// OrganizationSources
public IList<OrganizationSource> GetOrganizationSources(Organization org, Source source)
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("Organization", org);
criteria.Add("Source", source);
return this.orgSourceRepo.FindAll(criteria);
}
public OrganizationSource SaveOrganizationSource(OrganizationSource os)
{
os.Organization.AddOrganizationSource(os);
os.Source.AddOrganizationSource(os);
return this.orgSourceRepo.SaveOrUpdate(os);
}
public void DeleteOrganizationSource(int id)
{
this.DeleteOrganizationSource(this.orgSourceRepo.Get(id));
}
private void DeleteOrganizationSource(OrganizationSource os)
{
if (os != null)
{
os.Source.RemoveOrganizationSource(os);
os.Organization.RemoveOrganizationSource(os);
this.orgSourceRepo.Delete(os);
}
}
// UnitSources
public UnitSource GetUnitSource(int id)
{
return this.unitSourceRepo.Get(id);
}
public IList<UnitSource> GetUnitSources(int sourceId)
{
return this.sourceCollectionsQuery.GetUnitSources(sourceId);
}
public UnitSource SaveUnitSource(UnitSource us)
{
us.Unit.AddUnitSource(us);
us.Source.AddUnitSource(us);
return this.unitSourceRepo.SaveOrUpdate(us);
}
public void DeleteUnitSource(int id)
{
this.DeleteUnitSource(this.unitSourceRepo.Get(id));
}
private void DeleteUnitSource(UnitSource us)
{
if (us != null)
{
us.Source.RemoveUnitSource(us);
us.Unit.RemoveUnitSource(us);
this.unitSourceRepo.Delete(us);
}
}
// OperationSources
public OperationSource GetOperationSource(int id)
{
return this.operationSourceRepo.Get(id);
}
public IList<OperationSource> GetOperationSources(int sourceId)
{
return this.sourceCollectionsQuery.GetOperationSources(sourceId);
}
public OperationSource SaveOperationSource(OperationSource us)
{
us.Operation.AddOperationSource(us);
us.Source.AddOperationSource(us);
return this.operationSourceRepo.SaveOrUpdate(us);
}
public void DeleteOperationSource(int id)
{
this.DeleteOperationSource(this.operationSourceRepo.Get(id));
}
private void DeleteOperationSource(OperationSource os)
{
if (os != null)
{
os.Source.RemoveOperationSource(os);
os.Operation.RemoveOperationSource(os);
this.operationSourceRepo.Delete(os);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using DBDiff.Schema.Model;
namespace DBDiff.Schema.SQLServer.Model
{
public class TableOptions:SchemaList<TableOption,Table>
{
public TableOptions(Table parent)
: base(parent)
{
}
/// <summary>
/// Clona el objeto Columns en una nueva instancia.
/// </summary>
public TableOptions Clone(Table parent)
{
TableOptions options = new TableOptions(parent);
for (int index = 0; index < this.Count; index++)
{
options.Add(this[index].Clone(parent));
}
return options;
}
/// <summary>
/// Agrega un objeto columna a la coleccion de columnas.
/// </summary>
public void Add(string name, string value)
{
TableOption prop = new TableOption(Parent);
prop.Name = name;
prop.Value = value;
prop.Status = Enums.ObjectStatusType.OriginalStatus;
base.Add(prop);
}
}
}
|
using System.Collections.Generic;
using System.Net.Http;
namespace ApiTemplate.Model.Rest
{
public class SendParameterModel
{
public string QueryString { get; set; }
public string BaseAddress { get; set; }
public bool HasApiKey { get; set; }
public bool SendApiKeyByHeader { get; set; }
public string ApiKeyName { get; set; }
public string ApiKeyValue { get; set; }
public string ApiName { get; set; }
public string BearerToken { get; set; }
public HttpMethod Method { get; set; } = HttpMethod.Post;
}
} |
using System;
namespace DelftTools.Utils.ComponentModel
{
/// <summary>
/// Used to mark method as a validation method used to check if property value can be set.
/// <seealso cref="DynamicReadOnlyAttribute"/>
/// </summary>
public class DynamicReadOnlyValidationMethodAttribute : Attribute
{
}
}
|
#if !NETFRAMEWORK
namespace Sentry.PlatformAbstractions;
/// <summary>
/// No-op version for netstandard targets
/// </summary>
public static partial class FrameworkInfo
{
/// <summary>
/// No-op version for netstandard targets
/// </summary>
/// <param name="clr"></param>
public static FrameworkInstallation? GetLatest(int clr) => null;
/// <summary>
/// No-op version for netstandard targets
/// </summary>
public static IEnumerable<FrameworkInstallation> GetInstallations()
=> Enumerable.Empty<FrameworkInstallation>();
}
#endif
|
using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Domain.AbstractRepository;
using Infrastructure.DomainBase;
using Infrastructure.Encryption;
using Web.Controllers.Base;
using Web.ViewModels.User;
namespace Web.Controllers
{
public class UserController : AuthorizedController
{
private readonly IUserRepository _userRepository;
private readonly IEncryptor _encryptor;
public UserController(IUserRepository userRepository, IEncryptor encryptor
)
{
_userRepository = userRepository;
_encryptor = encryptor;
}
public ActionResult Index()
{
return View();
}
public ActionResult UserList()
{
return PartialView("Partials/UserList");
}
public JsonResult GetUsers()
{
var users = _userRepository.GetAll()
.Select(x=> new DisplayUserViewModel(x, _encryptor))
.OrderBy(u=>u.DisplayName)
.ToList();
return Json(users, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult UpdateUser(UpdateUserViewModel userViewModel)
{
var user = _userRepository.Get(userViewModel.UserId);
if (user == null)
{
throw new HttpException(500, "User not found");
}
user.SetEmail(userViewModel.NewEmail, _userRepository);
user.DisplayName = userViewModel.NewDisplayName;
user.IsActive = userViewModel.NewIsActive;
foreach (var newRole in userViewModel.NewRoles)
{
if (newRole.IsSelected && !user.IsInRole(newRole.RoleName))
{
user.Roles.Add((Domain.Users.Role)Enum.Parse(typeof(Domain.Users.Role), newRole.RoleName));
}
if (!newRole.IsSelected && user.IsInRole(newRole.RoleName))
{
user.Roles.Remove((Domain.Users.Role)Enum.Parse(typeof(Domain.Users.Role), newRole.RoleName));
}
}
using (var transaction = new Transaction(_userRepository.Session))
{
_userRepository.Save(user);
transaction.Commit();
}
return Json(new DisplayUserViewModel(user, _encryptor));
}
}
}
|
using Presenter.Core.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Presenter.Core.Interfaces
{
public interface IScreenManager
{
Process StartPresentation(Presentation presentation);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class StartCounter : MonoBehaviour
{
[SerializeField]
Image maskImage;
[SerializeField]
Text text;
private bool isGameStart = false;
private void Awake()
{
}
private void OnEnable()
{
StopTime();
SetCount(3);
}
private void StopTime()
{
Time.timeScale = 0f;
}
private void ResumeTime()
{
Time.timeScale = 1.0f;
}
private float nowTimeCount =0f;
int nowCount = 3;
private void OnDisable()
{
nowTimeCount = 0f;
nowCount = 3;
ResumeTime();
}
private void Update()
{
nowTimeCount += Time.unscaledDeltaTime;
if (nowTimeCount >= 0.5f)
{
nowCount--;
SetCount(nowCount);
nowTimeCount = 0f;
}
}
private void GameStart()
{
this.gameObject.SetActive(false);
}
private void SetCount(int nowCount)
{
if (nowCount == 0)
{
if (text != null)
text.text = "Go!";
}
//게임 시작
else if(nowCount == -1)
{
GameStart();
}
else
{
if (text != null)
text.text = nowCount.ToString();
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Versioning;
using System.Transactions;
using PhobiaX.Assets;
using PhobiaX.Graphics;
using PhobiaX.Physics;
using PhobiaX.SDL2;
using SDL2;
namespace PhobiaX.Game.GameObjects
{
public class AnimatedGameObject : IGameObject
{
public Guid Id { get; } = Guid.NewGuid();
public int X
{
get
{
return this.ColladableObject.X;
}
set
{
this.RenderableObject.X = value;
this.ColladableObject.X = value;
}
}
public int Y
{
get
{
return this.ColladableObject.Y;
}
set
{
this.RenderableObject.Y = value;
this.ColladableObject.Y = value;
}
}
public double Speed { get; set; } = 4;
public IRenderableObject RenderableObject { get; set; }
public RenderablePeriodicAnimation RenderablePeriodicAnimation { get { return RenderableObject as RenderablePeriodicAnimation; } }
public ICollidableObject ColladableObject { get; set; }
public AnimatedGameObject(RenderablePeriodicAnimation renderablePeriodicAnimation, ICollidableObject colladableObject)
{
RenderableObject = renderablePeriodicAnimation ?? throw new ArgumentNullException(nameof(renderablePeriodicAnimation));
ColladableObject = colladableObject;
}
public void Stop()
{
if (this.ColladableObject == null)
{
return;
}
this.RenderablePeriodicAnimation.ChangeSet(AnimationSetType.Default);
}
public void TurnLeft()
{
if (this.ColladableObject == null)
{
return;
}
RenderablePeriodicAnimation.NextAngle();
}
public void TurnRight()
{
if (this.ColladableObject == null)
{
return;
}
RenderablePeriodicAnimation.PreviousAngle();
}
public void MoveForward()
{
if (this.ColladableObject == null)
{
return;
}
var (x, y) = MathFormulas.GetIncrementByAngle(Speed, this.RenderablePeriodicAnimation.Angle);
X += (int)(x);
Y -= (int)(y);
this.RenderablePeriodicAnimation.NextFrame();
}
public void MoveBackward()
{
if (this.ColladableObject == null)
{
return;
}
var (x, y) = MathFormulas.GetIncrementByAngle(Speed, this.RenderablePeriodicAnimation.Angle);
X -= (int)x;
Y += (int)y;
this.RenderablePeriodicAnimation.PreviousFrame();
}
public virtual void Hit()
{
this.RenderablePeriodicAnimation.ChangeSet(AnimationSetType.Final);
this.ColladableObject = null;
}
public override string ToString()
{
return $"Type: {this.GetType().Name} {nameof(Id)}: {Id} {nameof(ColladableObject)}: {ColladableObject}";
}
}
}
|
using System.Collections.Generic;
using Profiling2.Domain.Prf;
using Profiling2.Domain.Prf.Events;
namespace Profiling2.Domain.Contracts.Queries.Search
{
public interface IEventSearchQuery
{
IList<Event> GetResults(string term);
IList<Tag> SearchTags(string term);
}
}
|
using System;
public static class JadenCase {
public static string recursive(string input, string output, int i){
if(input.Length == output.Length){
return output;
}
if(i == 0){
return recursive(input, output + Char.ToUpper(input[i]), i + 1);
}
if(input[i] == ' '){
return recursive(input, output + ' ' + Char.ToUpper(input[i + 1]), i + 2);
}else{
return recursive(input, output + input[i], i + 1);
}
}
public static string ToJadenCase(this string phrase) {
return recursive(phrase, "", 0);
}
public static void Main(){
Console.WriteLine(ToJadenCase("guacamole con tostaditas y cebolla"));
}
}
|
using System;
namespace Zesty.Core.Entities
{
public class Translation
{
public string Original { get; set; }
public string Translated { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace ScheduleService.Model
{
public class Room
{
public int Id { get; }
public RoomType RoomType { get; }
private IEnumerable<Appointment> UnavailableAppointments { get; }
public Room(int id, RoomType roomType)
{
Id = id;
RoomType = roomType;
UnavailableAppointments = new List<Appointment>();
}
public Room(int id, RoomType roomType, IEnumerable<DateTime> unavailableAppointments)
{
Id = id;
RoomType = roomType;
if (unavailableAppointments is null)
UnavailableAppointments = new List<Appointment>();
else
UnavailableAppointments = unavailableAppointments.Select(a => new Appointment(a));
}
public bool IsAvailable(Appointment appointment)
{
return !UnavailableAppointments.Contains(appointment);
}
}
}
|
namespace NetEscapades.AspNetCore.SecurityHeaders.Headers.PermissionsPolicy
{
/// <summary>
/// Controls access to autoplay of media requested through the
/// <code>HTMLMediaElement</code> interface. If disabled in a document,
/// then calls to <code>play()</code> without a user gesture will
/// reject the promise with a <code>NotAllowedError</code> DOMException
/// object as its parameter. The autoplay attribute will be ignored.
/// </summary>
public class AutoplayPermissionsPolicyDirectiveBuilder : PermissionsPolicyDirectiveBuilder
{
/// <summary>
/// Initializes a new instance of the <see cref="AutoplayPermissionsPolicyDirectiveBuilder"/> class.
/// </summary>
public AutoplayPermissionsPolicyDirectiveBuilder() : base("autoplay")
{
}
}
}
|
using Cottle.Functions;
using Cottle.Values;
using EddiDataDefinitions;
using EddiDataProviderService;
using EddiSpeechResponder.Service;
using JetBrains.Annotations;
using System;
namespace EddiSpeechResponder.CustomFunctions
{
[UsedImplicitly]
public class MaterialDetails : ICustomFunction
{
public string name => "MaterialDetails";
public FunctionCategory Category => FunctionCategory.Details;
public string description => Properties.CustomFunctions_Untranslated.MaterialDetails;
public Type ReturnType => typeof( Material );
public NativeFunction function => new NativeFunction((values) =>
{
Material result = Material.FromName(values[0].AsString);
if (result?.edname != null && values.Count == 2)
{
StarSystem starSystem = StarSystemSqLiteRepository.Instance.GetOrFetchStarSystem(values[1].AsString, true);
if (starSystem != null)
{
Body body = Material.highestPercentBody(result.edname, starSystem.bodies);
result.bodyname = body?.bodyname;
result.bodyshortname = body?.shortname;
}
}
return new ReflectionValue(result ?? new object());
}, 1, 2);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms
{
public static class TogglTest
{
private static void ToggleInterview()
{
var ar = new[] { 1, 2 };
var ar2 = ar.Select(x =>
{
Console.WriteLine("{0} * 2", x);
return x * 2;
});
Console.WriteLine("Select finished");
Console.WriteLine("Total: {0}", ar2.Sum());
}
}
}
|
using System.Text.RegularExpressions;
namespace Infrastructure.PasswordPolicies
{
/// <summary>
/// Password policy based on regular expression
/// </summary>
public class RegularExpressionPasswordPolicy : IPasswordPolicy
{
private readonly string _regularExpression;
/// <summary>
/// Constructor
/// </summary>
/// <param name = "regularExpression">Regular expression to validate the password</param>
public RegularExpressionPasswordPolicy(string regularExpression)
{
_regularExpression = regularExpression;
}
#region IPasswordPolicy Members
/// <summary>
/// Validate password
/// </summary>
/// <param name = "password">Password</param>
/// <returns>Boolean indicating if password is valid according to policy</returns>
public bool Validate(string password)
{
// Validate password using regex
return new Regex(_regularExpression).IsMatch(password);
}
#endregion
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebAPI.Models;
namespace WebAPITest.Test
{
[TestClass]
public class ParallelExceptionHandlingTest : TestBase
{
[TestMethod]
public async Task ListsMatching()
{
//----------
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json;
using OrchardCore.ContentManagement;
using StockAndShare.OrchardCoreDemo.Models;
using StockAndShare.OrchardCoreDemo.Settings;
namespace StockAndShare.OrchardCoreDemo.ViewModels
{
public class StockPartViewModel
{
public string MySetting { get; set; }
[Required]
public string CompanyName { get; set; }
[Required]
public double CurrentStockPrice { get; set; }
[Required]
public DateTime? RecordedDate { get; set; }
public bool Show { get; set; }
[BindNever]
public ContentItem ContentItem { get; set; }
[BindNever]
public StockPart StockPart { get; set; }
[BindNever]
public StockPartSettings Settings { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aviso
{
abstract public class AvisoReporter
{
abstract public bool PrintCurrent(System.Windows.Forms.BindingSource bs, string result_file);
}
}
|
using System;
namespace Lesson4.Linq
{
class Program
{
static void Main(string[] args)
{
// Language-Integrated Query
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
// We will use Linq (Language-Integrated Query) to query our collections.
}
}
}
|
using Infrostructure.Exeption;
namespace DomainModel.Entity.ProductParts
{
/// <summary>
/// سرعت
/// </summary>
public class Speed
{
private const decimal MinValue = 0m;
public decimal Value { get; private set; }
public Speed(decimal value)
{
ValidateSpeedValue(value);
Value = value;
}
private void ValidateSpeedValue(decimal value)
{
if (value < MinValue) throw new InvalidSpeedMeasureValueException(value.ToString());
}
}
}
|
using System;
using System.CodeDom.Compiler;
using System.Diagnostics.CodeAnalysis;
using Atc.CodeAnalysis.CSharp.SyntaxFactories;
// ReSharper disable once CheckNamespace
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public static class ClassDeclarationSyntaxExtensions
{
public static ClassDeclarationSyntax AddSuppressMessageAttribute(this ClassDeclarationSyntax classDeclaration, SuppressMessageAttribute suppressMessage)
{
if (classDeclaration == null)
{
throw new ArgumentNullException(nameof(classDeclaration));
}
if (suppressMessage == null)
{
throw new ArgumentNullException(nameof(suppressMessage));
}
if (string.IsNullOrEmpty(suppressMessage.Justification))
{
throw new ArgumentPropertyNullException(nameof(suppressMessage), "Justification is invalid.");
}
var attributeArgumentList = SyntaxFactory.AttributeArgumentList(
SyntaxFactory.SeparatedList<AttributeArgumentSyntax>(SyntaxFactory.NodeOrTokenList(
SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(suppressMessage.Category)),
SyntaxTokenFactory.Comma(),
SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(suppressMessage.CheckId)),
SyntaxTokenFactory.Comma(),
SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(suppressMessage.Justification!))
.WithNameEquals(
SyntaxNameEqualsFactory.Create(nameof(SuppressMessageAttribute.Justification))
.WithEqualsToken(SyntaxTokenFactory.Equals())))));
return classDeclaration
.AddAttributeLists(SyntaxAttributeListFactory.Create(nameof(SuppressMessageAttribute), attributeArgumentList));
}
public static ClassDeclarationSyntax AddGeneratedCodeAttribute(this ClassDeclarationSyntax classDeclaration, string toolName, string version)
{
if (classDeclaration == null)
{
throw new ArgumentNullException(nameof(classDeclaration));
}
if (toolName == null)
{
throw new ArgumentNullException(nameof(toolName));
}
if (version == null)
{
throw new ArgumentNullException(nameof(version));
}
var attributeArgumentList = SyntaxFactory.AttributeArgumentList(
SyntaxFactory.SeparatedList<AttributeArgumentSyntax>(SyntaxFactory.NodeOrTokenList(
SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(toolName)),
SyntaxTokenFactory.Comma(),
SyntaxFactory.AttributeArgument(SyntaxLiteralExpressionFactory.Create(version)))));
return classDeclaration
.AddAttributeLists(SyntaxAttributeListFactory.Create(nameof(GeneratedCodeAttribute), attributeArgumentList));
}
}
} |
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
namespace SqlServerRunnerNet.Infrastructure
{
public sealed class TrulyObservableCollection<T> : ObservableCollection<T> where T : class, INotifyPropertyChanged, new()
{
private readonly object _lock = new object();
private volatile bool _willNotify = true;
public event EventHandler<ItemChangedEventArgs> ItemChanged;
private void OnItemChangedEventHandler(ItemChangedEventArgs e)
{
EventHandler<ItemChangedEventArgs> handler = ItemChanged;
if (handler != null) handler(this, e);
}
public TrulyObservableCollection()
{
CollectionChanged += OnCollectionChanged;
}
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
if (notifyCollectionChangedEventArgs.Action == NotifyCollectionChangedAction.Remove)
{
foreach (T item in notifyCollectionChangedEventArgs.OldItems)
{
//Removed items
item.PropertyChanged -= ItemPropertyChanged;
}
}
else if (notifyCollectionChangedEventArgs.Action == NotifyCollectionChangedAction.Add)
{
foreach (T item in notifyCollectionChangedEventArgs.NewItems)
{
//Added items
item.PropertyChanged += ItemPropertyChanged;
}
}
}
private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
lock (_lock)
{
if (_willNotify)
OnItemChangedEventHandler(new ItemChangedEventArgs());
}
}
public class ItemChangedEventArgs : EventArgs
{
}
public void InvokeWithoutNotify(Action<T> action)
{
if (action == null)
return;
lock (_lock)
{
_willNotify = false;
Items.ToList().ForEach(action);
_willNotify = true;
}
}
}
}
|
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
namespace AGCompressedAir.Windows.Validation
{
public class ValidationBuilder
{
public ValidationBuilder()
{
RuleMaps = new ObservableCollection<RuleMap>();
}
public ObservableCollection<RuleMap> RuleMaps { get; set; }
public void AddRule<T>(Expression<Func<T>> expression, Func<bool> ruleDelegate, string errorMessage)
{
var name = GetPropertyName(expression);
RuleMaps.Add(new RuleMap
{
Key = name,
Binder = new ValidationBinder(ruleDelegate, errorMessage)
});
}
public void UpdateRule<T>(Expression<Func<T>> expression, Func<bool> ruleDelegate, string errorMessage)
{
var name = GetPropertyName(expression);
var ruleMap = RuleMaps.First(x => x.Key == name);
if (ruleMap != null)
{
ruleMap.Binder = new ValidationBinder(ruleDelegate, errorMessage);
}
}
protected static string GetPropertyName<T>(Expression<Func<T>> expression)
{
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
var body = expression.Body;
var memberExpression = body as MemberExpression ?? (MemberExpression) ((UnaryExpression) body).Operand;
return memberExpression.Member.Name;
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using EZCameraShake;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
public float speed;
public float speedUpDown;
public int health = 100;
public int eggs = 0;
public GameObject moveEffect;
public Image playerHealthBar;
public Image eggsCollectedBar;
public GameObject damageTaken;
public GameObject eggCollectedPlus;
private Rigidbody2D _rb;
private BoxCollider2D _collider;
private Animator _playerAnim;
private SceneTransitions _sceneTransitions;
private GameController _gameController;
private Vector3 _touchPosition;
private Vector3 _direction;
private Vector2 _moveAmount;
void Start()
{
_rb = GetComponent<Rigidbody2D>();
_collider = GetComponent<BoxCollider2D>();
_playerAnim = gameObject.GetComponent<Animator>();
_sceneTransitions = FindObjectOfType<SceneTransitions>();
_gameController = GameObject.Find("GameController").GetComponent<GameController>();
health = _gameController.playerHealth;
UpdateHealthUI(health);
}
private void Update()
{
_playerAnim.SetBool("swimming", true);
}
private void FixedUpdate()
{
if (health <= 0)
{
return;
}
// For tests purposes
#if UNITY_EDITOR_WIN
Vector2 moveInput = new Vector2(0, Input.GetAxisRaw("Vertical"));
_moveAmount = moveInput.normalized * speed;
_playerAnim.SetBool("swimming", true);
_rb.MovePosition(_rb.position + _moveAmount * Time.fixedDeltaTime);
_playerAnim.SetFloat("swimmingUpOrDown", _moveAmount.y);
#endif
// For tests purposes
#if UNITY_ANDROID
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.position.x > Screen.width / 2)
{
// Right side
}
else
{
// Left side
_touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
_touchPosition.z = 0;
_direction = (_touchPosition - transform.position);
_rb.velocity = new Vector2(_direction.x, _direction.y) * speedUpDown;
_playerAnim.SetFloat("swimmingUpOrDown", _direction.y);
if (touch.phase == TouchPhase.Ended)
{
_rb.velocity = Vector2.zero;
_playerAnim.SetFloat("swimmingUpOrDown", 0f);
}
}
}
#endif
}
public void TakeDamage(int amount)
{
health -= amount;
_gameController.playerHealth = health;
UpdateHealthUI(health);
_playerAnim.SetTrigger("hurt");
var go = Instantiate(damageTaken, transform.position, Quaternion.identity, transform);
go.GetComponent<TextMesh>().text = amount.ToString();
if (health <= 0)
{
Die();
}
}
private void Die()
{
_playerAnim.SetTrigger("dead");
_rb.isKinematic = true;
_collider.enabled = false;
StartCoroutine(ShowLooseScreen());
}
IEnumerator ShowLooseScreen()
{
yield return new WaitForSeconds(3f);
Destroy(this.gameObject);
_sceneTransitions.LoadScene("Loose");
}
void UpdateHealthUI(float currentHealth)
{
var curHealth = playerHealthBar.transform.parent.Find("CurrentHealth");
curHealth.GetComponent<Text>().text = currentHealth.ToString();
playerHealthBar.fillAmount = currentHealth / 100;
}
public void CollectEgg(int amount)
{
eggs += amount;
UpdateEgghUI(eggs);
Instantiate(eggCollectedPlus, transform.position, Quaternion.identity, transform);
if (eggs >= _gameController.eggsToCollect)
{
_gameController.gameDifficulty++;
_gameController.eggsToCollect++;
_gameController.level++;
_gameController.startGame = false;
_sceneTransitions.LoadScene("Won");
}
}
void UpdateEgghUI(float eggsCurCollected)
{
var eggsCollected = eggsCollectedBar.transform.parent.Find("CurrentCollectedEggs");
eggsCollected.GetComponent<Text>().text = eggsCurCollected.ToString();
float progressPercent = (eggs * 100 / _gameController.eggsToCollect);
Debug.Log(eggs);
Debug.Log( _gameController.eggsToCollect);
Debug.Log(progressPercent);
eggsCollectedBar.fillAmount = (progressPercent / 100);
}
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using PterodactylCharts;
using Xunit;
namespace UnitTestEngine
{
public class TestGraphAxisHelper : TheoryData<string, string, string>
{
public TestGraphAxisHelper()
{
Add("XAxis", "Y Axis Name", "Graph Axises\r\nX Axis: XAxis\r\nY Axis: Y Axis Name");
}
}
public class TestGraphAxis
{
[Theory]
[ClassData(typeof(TestGraphAxisHelper))]
public void CorrectData(string xAxisName, string yAxisName, string toString)
{
GraphAxis testObject = new GraphAxis(xAxisName, yAxisName);
Assert.Equal(xAxisName, testObject.XAxisName);
Assert.Equal(yAxisName, testObject.YAxisName);
Assert.Equal(toString, testObject.ToString());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BHLD.Data.Infrastructure
{
public interface IDbFactory : IDisposable
{
BHLDDbContext Init();
}
}
|
using System.ComponentModel.DataAnnotations.Resources;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace System.ComponentModel.DataAnnotations
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = false)]
[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes", Justification = "We want users to be able to extend this class")]
public sealed class EnumDataTypeAttribute : DataTypeAttribute
{
public Type EnumType { get; private set; }
public EnumDataTypeAttribute(Type enumType)
: base("Enumeration")
{
this.EnumType = enumType;
}
internal override bool IsValid(object value)
{
if (this.EnumType == null)
{
throw new InvalidOperationException(DataAnnotationsResources.EnumDataTypeAttribute_TypeCannotBeNull);
}
if (!this.EnumType.IsEnum)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, DataAnnotationsResources.EnumDataTypeAttribute_TypeNeedsToBeAnEnum, this.EnumType.FullName));
}
if (value == null)
{
return true;
}
string stringValue = value as string;
if (stringValue != null && String.IsNullOrEmpty(stringValue))
{
return true;
}
Type valueType = value.GetType();
if (valueType.IsEnum && this.EnumType != valueType)
{
// don't match a different enum that might map to the same underlying integer
//
return false;
}
if (!valueType.IsValueType && valueType != typeof(string))
{
// non-value types cannot be converted
return false;
}
if (valueType == typeof(bool) ||
valueType == typeof(float) ||
valueType == typeof(double) ||
valueType == typeof(decimal) ||
valueType == typeof(char))
{
// non-integral types cannot be converted
return false;
}
object convertedValue;
if (valueType.IsEnum)
{
Debug.Assert(valueType == value.GetType(), "The valueType should equal the Type of the value");
convertedValue = value;
}
else
{
try
{
if (stringValue != null)
{
convertedValue = Enum.Parse(this.EnumType, stringValue, false);
}
else
{
convertedValue = Enum.ToObject(this.EnumType, value);
}
}
catch (ArgumentException)
{
//
return false;
}
}
if (IsEnumTypeInFlagsMode(this.EnumType))
{
//
string underlying = GetUnderlyingTypeValueString(this.EnumType, convertedValue);
string converted = convertedValue.ToString();
return !underlying.Equals(converted);
}
else
{
return Enum.IsDefined(this.EnumType, convertedValue);
}
}
private static bool IsEnumTypeInFlagsMode(Type enumType)
{
return enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Length != 0;
}
private static string GetUnderlyingTypeValueString(Type enumType, object enumValue)
{
return Convert.ChangeType(enumValue, Enum.GetUnderlyingType(enumType), CultureInfo.InvariantCulture).ToString();
}
}
} |
using System;
using System.IO;
using System.Reflection;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace HTBPdf
{
public class ECPPdfWriter
{
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected String filePath = "C:/temp/testPdfWriter.pdf";
protected String imagePath = "";
private const int IMAGE_MAX_WIDTH = 300;
private const int IMAGE_MAX_HEIGHT = 300;
private Document _document;
public Document Document
{
get { return _document; }
set { _document = value; }
}
protected iTextSharp.text.Rectangle pageSize;
public Rectangle PdfPageSize
{
get { return pageSize; }
}
public BaseFont font;
private PdfWriter _writer;
public PdfWriter Writer
{
get { return _writer; }
set { _writer = value; }
}
protected float orgLineWidth = .5f;
protected float lineWidth = .5f;
protected float barcodeX = 1;
protected float barcodeN = 2;
protected int fontSize = 12;
protected bool landscapeMode = false;
protected float marginLeft;
protected float marginRight;
protected float marginTop;
protected float marginBottom;
protected int pageHeight;
private bool canDrawRects = true;
private bool canDrawLines = true;
private bool canPrint = true;
private String _fontsDir = "c:/windows/fonts";
public String FontsDir
{
get { return _fontsDir; }
set { _fontsDir = value; }
}
public ECPPdfWriter() : this(PageSize.LETTER, 0, 0, 0, 0)
{
}
public ECPPdfWriter(iTextSharp.text.Rectangle ppageSize, int pmarginLeft, int pmarginRight, int pmarginTop,
int pmarginBottom) : this(ppageSize, pmarginLeft, pmarginRight, pmarginTop, pmarginBottom, BaseColor.WHITE)
{
}
public ECPPdfWriter(iTextSharp.text.Rectangle ppageSize, int pmarginLeft, int pmarginRight, int pmarginTop,
int pmarginBottom, BaseColor pbgColor)
{
pageSize = ppageSize;
//pageSize.BackgroundColor = pbgColor;
try
{
font = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
}
catch (DocumentException)
{
//e.printStackTrace();
}
catch (Exception)
{
//e.printStackTrace();
}
}
#region draw
public void drawLine(int urow, int ucol, int lrow, int lcol)
{
drawLine(urow, ucol, lrow, lcol, lineWidth);
}
public void drawLine(int urow, int ucol, int lrow, int lcol, float width)
{
if (canDrawLines)
{
float wx1 = (float) adjustX(ucol);
float wy1 = (float) adjustY(urow);
float wx2 = (float) adjustX(lcol);
float wy2 = (float) adjustY(lrow);
if (HTBUtilities.HTBUtils.AlmostEqual(width, 0, .005)) width = lineWidth;
_writer.DirectContent.SetLineWidth(width);
_writer.DirectContent.MoveTo(wx1, wy1);
_writer.DirectContent.LineTo(wx2, wy2);
_writer.DirectContent.Stroke();
}
}
public void drawLineGray(int px, int py, int pw, int ph)
{
drawLine(px, py, pw, ph, BaseColor.LIGHT_GRAY);
}
public void drawLine(int urow, int ucol, int lrow, int lcol, BaseColor pbgc)
{
if (canDrawLines)
{
float ww, wh = 0;
float wx1 = (float) adjustX(ucol);
float wy1 = (float) adjustY(urow);
float wx2 = (float) adjustX(lcol);
float wy2 = (float) adjustY(lrow);
ww = wx2 - wx1;
wh = wy1 - wy2;
_writer.DirectContentUnder.SetLineWidth(lineWidth);
_writer.DirectContentUnder.Rectangle(wx1, wy2, ww, wh);
_writer.DirectContentUnder.SetColorFill(pbgc);
_writer.DirectContentUnder.FillStroke();
_writer.DirectContentUnder.Stroke();
}
}
public void drawRectGray(int px, int py, int pw, int ph)
{
drawRectangle(px, py, pw, ph, BaseColor.LIGHT_GRAY);
}
public void drawRect(int px, int py, int pw, int ph)
{
drawRectangle(px, py, pw, ph, BaseColor.WHITE);
}
public void drawRectangle(int urow, int ucol, int lrow, int lcol, BaseColor pbgc)
{
if (canDrawRects)
{
float ww, wh = 0;
float wx1 = (float) adjustX(ucol);
float wy1 = (float) adjustY(urow);
float wx2 = (float) adjustX(lcol);
float wy2 = (float) adjustY(lrow);
ww = wx2 - wx1;
wh = wy1 - wy2;
_writer.DirectContentUnder.SetLineWidth(lineWidth);
_writer.DirectContentUnder.Rectangle(wx1, wy2, ww, wh);
_writer.DirectContentUnder.SetColorFill(pbgc);
_writer.DirectContentUnder.FillStroke();
_writer.DirectContentUnder.Stroke();
}
}
public void drawRoundRectGray(int px, int py, int pw, int ph)
{
drawRoundRectGray(px, py, pw, ph, 10);
}
public void drawRoundRectGray(int px, int py, int pw, int ph, int pr)
{
drawRoundRectangle(px, py, pw, ph, pr, BaseColor.LIGHT_GRAY);
}
public void drawRoundRect(int px, int py, int pw, int ph, int pr)
{
drawRoundRectangle(px, py, pw, ph, pr, BaseColor.WHITE);
}
public void drawRoundRect(int px, int py, int pw, int ph)
{
drawRoundRectangle(px, py, pw, ph);
}
public void drawRoundRectangle(int px, int py, int pw, int ph)
{
drawRoundRectangle(px, py, pw, ph, 10, BaseColor.WHITE);
}
public void drawRoundRectangle(int urow, int ucol, int lrow, int lcol, int pr, BaseColor pbgc)
{
if (canDrawRects)
{
float ww, wh, wr = 0;
float wx1 = (float) adjustX(ucol);
float wy1 = (float) adjustY(urow);
float wx2 = (float) adjustX(lcol);
float wy2 = (float) adjustY(lrow);
ww = wx2 - wx1;
wh = wy1 - wy2;
wr = wh / 4;
if (wr > 10)
{
wr = 10;
}
_writer.DirectContentUnder.SetLineWidth(lineWidth);
_writer.DirectContentUnder.RoundRectangle(wx1, wy2, ww, wh, wr);
_writer.DirectContentUnder.SetColorFill(pbgc);
_writer.DirectContentUnder.FillStroke();
_writer.DirectContentUnder.Stroke();
}
}
public void drawBitmap(int py, int px, String pname)
{
drawBitmap(py, px, pname, 100);
}
public void drawBitmap(int py, int px, String pname, int pspct)
{
try
{
Image img = Image.GetInstance(imagePath + "/" + pname);
drawBitmap(py, px, img, pspct);
}
catch (Exception)
{
//e.printStackTrace();
}
}
public void drawBitmapFromPath(int py, int px, String ppath, int pspct)
{
try
{
Image img = Image.GetInstance(ppath);
drawBitmap(py, px, img, pspct);
}
catch (Exception)
{
//e.printStackTrace();
}
}
public void drawBitmap(int py, int px, byte[] pimg, int pspct = 100)
{
drawBitmap(py, px, Image.GetInstance(pimg), pspct);
}
public void drawBitmap(int py, int px, Image pimg)
{
drawBitmap(py, px, pimg, 100);
}
public void drawBitmap(int py, int px, Image pimg, int pspct)
{
var wy = (float) adjustY(py);
var wx = (float) adjustX(px);
try
{
pimg.ScalePercent(pspct);
pimg.SetAbsolutePosition(wx, wy);
_document.Add(pimg);
}
catch (Exception)
{
//e.printStackTrace();
}
}
public int GetImageHeight(string pname)
{
if (File.Exists(imagePath + "/" + pname) && new FileInfo(imagePath + "/" + pname).Length > 0)
{
try
{
var img = Image.GetInstance(imagePath + "/" + pname);
if (img.Width > IMAGE_MAX_WIDTH || img.Height > IMAGE_MAX_HEIGHT)
{
img.ScaleToFit(IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT);
}
return (int)adjustY((int)img.ScaledHeight);
}
catch (Exception)
{
//e.printStackTrace();
}
}
return 0;
}
public int AddImageToDocument(int py, int px, string pname, string pdescription = null)
{
float height = 0;
if (File.Exists(imagePath + "/" + pname) && new FileInfo(imagePath + "/" + pname).Length > 0)
{
try
{
var img = Image.GetInstance(imagePath + "/" + pname);
if (img.Width > IMAGE_MAX_WIDTH || img.Height > IMAGE_MAX_HEIGHT)
{
img.ScaleToFit(IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT);
}
img.Border = Rectangle.BOX;
img.BorderWidth = 2f;
height = (float)adjustY((int)img.Height);
//img.SetAbsolutePosition((float)adjustX(px), (float)reverseY(py + (int)(img.Height)));
img.SetAbsolutePosition(0,0);
print(py, px, pdescription);
_document.Add(img);
}
catch (Exception)
{
//e.printStackTrace();
}
}
setFont("Calibri", 4);
for (int i = 0; i < 3000; i += 100)
{
drawLine(i, 0, i, 10);
print(i, 20, i);
}
return (int) height;
}
public void AddImageToDocument(String pname, String description = null)
{
if (File.Exists(imagePath + "/" + pname) && new FileInfo(imagePath + "/" + pname).Length > 0)
{
Image img = Image.GetInstance(imagePath + "/" + pname);
try
{
img.Alignment = Element.ALIGN_CENTER;
if (img.Width > IMAGE_MAX_WIDTH || img.Height > IMAGE_MAX_HEIGHT)
{
ResizeImage(img);
}
_document.Add(img);
if (!string.IsNullOrEmpty(description))
{
var p = new Paragraph(description)
{
Alignment = Element.ALIGN_CENTER
};
_document.Add(p);
}
}
catch (Exception)
{
//e.printStackTrace();
}
}
}
private PdfPTable pdfTable;
public void StartPdfTable2(int columns)
{
pdfTable = new PdfPTable(columns);
PdfPCell cell = new PdfPCell();
Paragraph p = new Paragraph();
var chunk = new Chunk("BILDER");
chunk.Font = FontFactory.GetFont(BaseFont.TIMES_BOLD, 18, BaseColor.BLUE);
p.Add(chunk);
cell.AddElement(p);
pdfTable.AddCell(cell);
}
public void StartPdfTable(int columns)
{
pdfTable = new PdfPTable(columns);
pdfTable.DefaultCell.Border = Rectangle.NO_BORDER;
pdfTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
var cell = new PdfPCell();
var p = new Paragraph();
var chunk = new Chunk("BILDER\n")
{
Font = FontFactory.GetFont(BaseFont.TIMES_BOLD, 18, BaseColor.BLUE)
};
p.Add(chunk);
cell.Colspan = 2;
cell.AddElement(p);
pdfTable.AddCell("");
pdfTable.AddCell("");
pdfTable.AddCell(cell);
}
public void AddImageToPdfTable2(string pname, string pdescription = null)
{
PdfPCell cell = new PdfPCell();
Paragraph p = new Paragraph();
float height = 0;
if (File.Exists(imagePath + "/" + pname) && new FileInfo(imagePath + "/" + pname).Length > 0)
{
try
{
var img = Image.GetInstance(imagePath + "/" + pname);
if (img.Width > IMAGE_MAX_WIDTH || img.Height > IMAGE_MAX_HEIGHT)
{
img.ScaleToFit(IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT);
}
p.Add(new Phrase(pdescription));
p.Add(new Chunk(img, 0, 0));
cell.AddElement(p);
pdfTable.AddCell(cell);
}
catch (Exception)
{
//e.printStackTrace();
}
}
}
public void AddImageToPdfTable(string pname, string pdescription = null)
{
PdfPCell cell = new PdfPCell();
Paragraph p = new Paragraph();
float height = 0;
if (File.Exists(imagePath + "/" + pname) && new FileInfo(imagePath + "/" + pname).Length > 0)
{
try
{
var img = Image.GetInstance(imagePath + "/" + pname);
// Setting image resolution
if (img.Height > img.Width)
{
var percentage = 0.0f;
percentage = 400 / img.Height;
img.ScalePercent(percentage * 100);
}
else
{
var percentage = 0.0f;
percentage = 240 / img.Width;
img.ScalePercent(percentage * 100);
}
img.Border = iTextSharp.text.Rectangle.BOX;
img.BorderColor = iTextSharp.text.BaseColor.BLACK;
img.BorderWidth = 3.0f;
pdfTable.AddCell(pdescription);
pdfTable.AddCell("");
pdfTable.AddCell(img);
pdfTable.AddCell("");
pdfTable.AddCell(" ");
pdfTable.AddCell(" ");
}
catch (Exception)
{
//e.printStackTrace();
}
}
}
public void FinishPdfTable()
{
_document.Add(pdfTable);
}
/*
public void AddImagesToDocument()
{
PdfPTable table = new PdfPTable(2);
PdfPCell cell = new PdfPCell();
Paragraph p = new Paragraph();
p.Add(new Phrase("Test "));
p.Add(new Chunk(image, 0, 0));
p.Add(new Phrase(" more text "));
p.Add(new Chunk(image, 0, 0));
p.Add(new Chunk(image, 0, 0));
p.Add(new Phrase(" end."));
cell.AddElement(p);
table.AddCell(cell);
table.AddCell(new PdfPCell(new Phrase("test 2")));
document.Add(table);
}*/
private void ResizeImage(Image img)
{
double srcWidth = img.Width;
double srcHeight = img.Height;
var resizeWidth = (float) srcWidth;
var resizeHeight = (float) srcHeight;
float aspect = resizeWidth / resizeHeight;
if (resizeWidth > IMAGE_MAX_WIDTH)
{
resizeWidth = IMAGE_MAX_WIDTH;
resizeHeight = resizeWidth / aspect;
}
if (resizeHeight > IMAGE_MAX_HEIGHT)
{
aspect = resizeWidth / resizeHeight;
resizeHeight = IMAGE_MAX_HEIGHT;
resizeWidth = resizeHeight * aspect;
}
img.ScaleAbsolute(resizeWidth, resizeHeight);
}
#endregion
#region print
public void print(int px, int py, long pvalue, String pedit)
{
print(px, py, pvalue.ToString(), 'L');
}
public void print(int px, int py, long pvalue, String pedit, char palign)
{
print(px, py, pvalue.ToString(), palign);
}
public void print(int px, int py, String pstr)
{
print(px, py, pstr, 'L');
}
public void print(int px, int py, String pstr, BaseColor pbgc)
{
print(px, py, pstr, 'L', pbgc);
}
public void print(int px, int py, double pdec)
{
print(px, py, pdec.ToString(), 'L');
}
public void print(int px, int py, double pdec, char palign)
{
print(px, py, pdec.ToString(), palign);
}
public void print(int py, int px, String pstr, char palign)
{
print(py, px, pstr, palign, BaseColor.BLACK);
}
public void print(int py, int px, String pstr, char palign, BaseColor pbgc)
{
if (canPrint)
{
float wy = (float) roundTo2(adjustY(py) + (fontSize / 10.0) - fontSize);
float wx = (float) adjustX(px);
_writer.DirectContent.SetLineWidth(lineWidth);
int walignment = PdfContentByte.ALIGN_LEFT;
_writer.DirectContent.BeginText();
_writer.DirectContent.SetFontAndSize(font, fontSize);
_writer.DirectContent.SetColorFill(pbgc);
if ('R' == palign)
{
wx = (float) roundTo2(wx - font.GetWidthPoint(pstr, fontSize));
}
else if ('C' == palign)
{
wx = (float) roundTo2(wx - (font.GetWidthPoint(pstr, fontSize) / 2.0));
}
_writer.DirectContent.ShowTextAligned(walignment, pstr, wx, wy, 0);
_writer.DirectContent.EndText();
}
}
public float GetTextWidth(string pstr)
{
var width = (double) roundTo2(font.GetWidthPoint(pstr, fontSize));
return (float)adjustXReverse(width);
}
public void printBarcode39(int py, int px, String pstr)
{
printBarcode39(py, px, pstr, 'L');
}
public void printBarcode39(int py, int px, String pstr, char palign)
{
/*
getContentByte();
int wx = px;
Barcode39 code = new Barcode39();
code.setCode(pstr);
code.setFont(font);
code.setX(barcodeX);
code.setN(barcodeN);
if (palign == 'C') {
wx -= code.getBarcodeSize().width() / 2;
}
else if (palign == 'R') {
wx -= code.getBarcodeSize().width();
}
Image img = code.createImageWithBarcode(contentByte, null, null);
drawBitmap(py, wx, img);
*/
}
#endregion
#region set
public void setFont(String pname, int psize)
{
setFont(pname, psize, false, false, false);
}
public void setFont(String pname, int psize, bool pbold, bool pitalics, bool punderline)
{
String wname = "Helvetica";
switch (pname.ToLower())
{
case "helvetica":
wname = BaseFont.HELVETICA;
if (pbold && pitalics)
{
wname = BaseFont.HELVETICA_BOLDOBLIQUE;
}
else if (pbold)
{
wname = BaseFont.HELVETICA_BOLD;
}
else if (pitalics)
{
wname = BaseFont.HELVETICA_OBLIQUE;
}
break;
case "arial":
wname = FontsDir + "/arial.ttf";
if (pbold && pitalics)
{
wname = FontsDir + "/arialbi.ttf";
}
else if (pbold)
{
wname = FontsDir + "/arialbd.ttf";
}
else if (pitalics)
{
wname = FontsDir + "/ariali.ttf";
}
break;
case "verdana":
wname = FontsDir + "/verdana.ttf";
if (pbold && pitalics)
{
wname = FontsDir + "/verdanaz.ttf";
}
else if (pbold)
{
wname = FontsDir + "/verdanab.ttf";
}
else if (pitalics)
{
wname = FontsDir + "/verdanai.ttf";
}
break;
case "calibri":
wname = FontsDir + "/calibri.ttf";
if (pbold && pitalics)
{
wname = FontsDir + "/calibriz.ttf";
}
else if (pbold)
{
wname = FontsDir + "/calibrib.ttf";
}
else if (pitalics)
{
wname = FontsDir + "/calibrii.ttf";
}
break;
case "letter gothic std":
wname = FontsDir + "/LetterGothicStd.otf";
if (pbold && pitalics)
{
wname = FontsDir + "/LetterGothicStd-BoldSlanted.otf";
}
else if (pbold)
{
wname = FontsDir + "/LetterGothicStd-Bold.otf";
}
else if (pitalics)
{
wname = FontsDir + "/LetterGothicStd-Slanted.otf";
}
break;
case "tahoma":
wname = FontsDir + "/tahoma.ttf";
if (pbold && pitalics)
{
wname = FontsDir + "/tahomabd.ttf";
}
else if (pbold)
{
wname = FontsDir + "/tahomabd.ttf";
}
else if (pitalics)
{
wname = FontsDir + "/tahoma.ttf";
}
break;
}
try
{
font = BaseFont.CreateFont(wname, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
}
catch (Exception)
{
//e.printStackTrace();
}
fontSize = psize;
}
public BaseFont GetFont(String pname, int psize, bool pbold, bool pitalics, bool punderline)
{
BaseFont wfont;
String wname = "Helvetica";
switch (pname.ToLower())
{
case "helvetica":
wname = BaseFont.HELVETICA;
if (pbold && pitalics)
{
wname = BaseFont.HELVETICA_BOLDOBLIQUE;
}
else if (pbold)
{
wname = BaseFont.HELVETICA_BOLD;
}
else if (pitalics)
{
wname = BaseFont.HELVETICA_OBLIQUE;
}
break;
case "arial":
wname = FontsDir + "/arial.ttf";
if (pbold && pitalics)
{
wname = FontsDir + "/arialbi.ttf";
}
else if (pbold)
{
wname = FontsDir + "/arialbd.ttf";
}
else if (pitalics)
{
wname = FontsDir + "/ariali.ttf";
}
break;
case "verdana":
wname = FontsDir + "/verdana.ttf";
if (pbold && pitalics)
{
wname = FontsDir + "/verdanaz.ttf";
}
else if (pbold)
{
wname = FontsDir + "/verdanab.ttf";
}
else if (pitalics)
{
wname = FontsDir + "/verdanai.ttf";
}
break;
case "calibri":
wname = FontsDir + "/calibri.ttf";
if (pbold && pitalics)
{
wname = FontsDir + "/calibriz.ttf";
}
else if (pbold)
{
wname = FontsDir + "/calibrib.ttf";
}
else if (pitalics)
{
wname = FontsDir + "/calibrii.ttf";
}
break;
case "letter gothic std":
wname = FontsDir + "/LetterGothicStd.otf";
if (pbold && pitalics)
{
wname = FontsDir + "/LetterGothicStd-BoldSlanted.otf";
}
else if (pbold)
{
wname = FontsDir + "/LetterGothicStd-Bold.otf";
}
else if (pitalics)
{
wname = FontsDir + "/LetterGothicStd-Slanted.otf";
}
break;
case "tahoma":
wname = FontsDir + "/tahoma.ttf";
if (pbold && pitalics)
{
wname = FontsDir + "/tahomabd.ttf";
}
else if (pbold)
{
wname = FontsDir + "/tahomabd.ttf";
}
else if (pitalics)
{
wname = FontsDir + "/tahoma.ttf";
}
break;
}
try
{
wfont = BaseFont.CreateFont(wname, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
}
catch (Exception)
{
//e.printStackTrace();
}
fontSize = psize;
return font;
}
public void setBarcodeX(float px)
{
if (px < 0)
{
px = 0;
}
barcodeX = px;
}
public void setBarcodeN(float pn)
{
if (pn < 0)
{
pn = 0;
}
barcodeN = pn;
}
public void setLandscapeMode(bool plandscapeMode)
{
if ((landscapeMode && !plandscapeMode) || (!landscapeMode && plandscapeMode))
{
pageSize = pageSize.Rotate();
_writer.SetPageSize(pageSize);
}
landscapeMode = plandscapeMode;
}
public void setFormName(String pname)
{
if (pname.ToLower().Equals("letter"))
{
pageSize = PageSize.LETTER;
}
else if (pname.ToLower().Equals("legal"))
{
pageSize = PageSize.LEGAL;
}
else if (pname.ToLower().Equals("a4"))
{
pageSize = PageSize.A4;
}
if (landscapeMode)
pageSize = pageSize.Rotate();
}
public void setImagePath(String pimgPath)
{
imagePath = pimgPath;
}
public void setFilePath(String pfilePath)
{
filePath = pfilePath;
}
public void setLineWidth(float pwidth)
{
lineWidth = pwidth;
}
/*
* this method sets the original line width. resetLineWidth() will set the line width to the
* value passed to this method.
*/
public void setOrgLineWidth(float pwidth)
{
orgLineWidth = pwidth;
}
public void resetLineWidth()
{
lineWidth = orgLineWidth;
}
public void newPage()
{
try
{
_document.NewPage();
}
catch (DocumentException)
{
//e.printStackTrace();
}
}
public void setMargins(float pmarginLeft, float pmarginRight, float pmarginTop, float pmarginBottom)
{
marginLeft = pmarginLeft;
marginRight = pmarginRight;
marginTop = pmarginTop;
marginBottom = pmarginBottom;
}
#endregion
public void open()
{
open(filePath);
}
public void open(String fileName)
{
open(new FileStream(fileName, FileMode.OpenOrCreate));
}
public void open(Stream os)
{
try
{
_document = new Document(pageSize);
_writer = PdfWriter.GetInstance(_document, os);
//writer.setPageSize(pageSize);
_document.SetMargins(marginLeft, marginRight, marginTop, marginBottom);
_document.Open();
newPage();
}
catch (DocumentException)
{
//e.printStackTrace();
}
catch (Exception)
{
//e.printStackTrace();
}
}
public void Close()
{
_document.Close();
_document.Dispose();
}
public double adjustX(int px)
{
double wx = metricToPoints(px) + 2.0;
return (roundTo2(wx));
}
public double adjustY(int py)
{
double wy = (double) pageSize.Height - metricToPoints(py) - 2.0;
// double wy = (double)pageSize.height() - 25 - metricToPoints(py) - 2.0;
return (roundTo2(wy));
}
public double adjustXReverse(int px)
{
double wx = pointsToMetric(px) - 2.0;
return (roundTo2(wx));
}
public double adjustXReverse(double px)
{
return pointsToMetric(px);
}
public double adjustYReverse(int py)
{
double wy = (metricToPoints(py) - pageSize.Height) *-1;
return (roundTo2(wy));
}
public double reverseY(int py)
{
double wy = (metricToPoints(py) - pageSize.Height + 2) * -1;
return (roundTo2(wy));
}
public double metricToPoints(int pm)
{
double wp = (((double) pm * 72.0) / 254.0);
return (roundTo2(wp));
}
public double pointsToMetric(double pp)
{
double wm = (((double) pp * 254.0) / 72.0);
return (roundTo2(wm));
}
public double roundTo2(double pnum)
{
long inum = (long) Math.Round((pnum * 100.0));
return (inum / 100.0);
}
public int getFontSize()
{
return fontSize;
}
public float getBarcodeX()
{
return barcodeX;
}
public float getBarcodeN()
{
return barcodeN;
}
public void PrintLeftEcpInfo()
{
int lin = 1500;
int gap = 33;
int col = 400;
BaseColor bc = BaseColor.BLUE;
setFont("Arial", 7, false, false, false);
print((lin += gap), col, "FIRMA", 'R', bc);
print((lin += gap), col, "E.C.P.", 'R', bc);
print((lin += gap), col, "EUROPEAN CAR PROTECT KG", 'R', bc);
lin += gap;
print((lin += gap), col, "ADRESSE", 'R', bc);
print((lin += gap), col, "Loigerstr. 89", 'R', bc);
print((lin += gap), col, "5071 Wals", 'R', bc);
print((lin += gap), col, "Austria", 'R', bc);
lin += gap;
print((lin += gap), col, "TELEFON", 'R', bc);
print((lin += gap), col, "+43 662 20 34 10 - 10", 'R', bc);
lin += gap;
print((lin += gap), col, "FAX", 'R', bc);
print((lin += gap), col, "+43 662 20 34 10 - 90", 'R', bc);
lin += gap;
print((lin += gap), col, "INTERNET / EMAIL", 'R', bc);
setFont("Arial", 7, true, false, false);
print((lin += gap), col, "www.ecp.or.at", 'R', bc);
setFont("Arial", 7, false, false, false);
print((lin += gap), col, "office@ecp.or.at", 'R', bc);
lin += gap;
print((lin += gap), col, "UID NUMMER", 'R', bc);
print((lin += gap), col, "ATU64079767", 'R', bc);
lin += gap;
print((lin += gap), col, "FIRMENBUCHGERICHT", 'R', bc);
print((lin += gap), col, "Landes- und Handelsgericht", 'R', bc);
print((lin += gap), col, "Salzburg", 'R', bc);
lin += gap;
print((lin += gap), col, "FIRMENBUCHNUMMER", 'R', bc);
print((lin += gap), col, "FN 305953g", 'R', bc);
lin += gap;
print((lin += gap), col, "BANKVERBINDUNG", 'R', bc);
print((lin += gap), col, "Raiffeisenbank Geretsberg", 'R', bc);
print((lin += gap), col, "IBAN: AT35 3411 8000 0002 9215", 'R', bc);
print((lin += gap), col, "BIC: RZOOAT2L118", 'R', bc);
lin += gap;
print((lin += gap), col, "GESCHÄFTSFÜHRUNG", 'R', bc);
print((lin += gap), col, "Thomas Jaky", 'R', bc);
print((lin += gap), col, "Helmut Ammer", 'R', bc);
}
public void AddPhrase(Phrase p, int lin, int col, int width, int height=39, int leadingLineHeight = 15)
{
ColumnText ct = new ColumnText(_writer.DirectContent);
/*
the phrase
the lower left x corner(left)
the lower left y corner(bottom)
the upper right x corner(right)
the upper right y corner(top)
line height (leading)
alignment.
*/
ct.SetSimpleColumn(
p,
(int)adjustX(col), // col
(int)adjustYReverse(lin), // lin
width, // width
col+height, // text height
leadingLineHeight,
Element.ALIGN_LEFT);
ct.Go();
}
public void test() {
log.Info("Testing.....");
testNewDocument();
log.Info("Testing Ended");
}
public int getTotalWidth(int[] warr, int pidx) {
int wrett = 0;
for (int i = 0; i <= pidx; i++) {
wrett += warr[i];
}
return wrett;
}
public void testNewDocument() {
// step 1: creation of a document-object
_document = new Document(PageSize.LEGAL);
try {
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
_writer = PdfWriter.GetInstance(_document, new FileStream(filePath, FileMode.OpenOrCreate));
// step 3: we open the document
// writer.setPageSize(PageSize.LEGAL);
_document.Open();
// step 4: we add a paragraph to the document
// document.add(new Paragraph("Hello World"));
// drawRoundRectangle(10, 10, 100, 50);
// drawRectangle(10, 70, 100, 50, Color.WHITE);
// drawRectGray (0, 0, 2500, 1950);
setFont("Arial", 9);
setBarcodeX(2);
printBarcode39(100, 100, "MDEMO2");
// writer.setPageSize(pageSize);
// mpdf.drawRect (0, 0, 2500, 1950);
// drawRoundRect (10, 10, 100, 100);
/*
* font = BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.CP1250,
* BaseFont.NOT_EMBEDDED); print(10, 10, "Test Text", "L"); font =
* BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
* print(110, 10, "Test Text", "L"); font =
* BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE, BaseFont.CP1252,
* BaseFont.NOT_EMBEDDED); print(210, 10, "Test Text", "L");
*/
// drawLine(100, 770, 110, 770);
}
catch (DocumentException de) {
log.Error(de.Message);
}
catch (Exception ioe) {
log.Error(ioe.Message);
}
// step 5: we close the document
_document.Close();
_document.Dispose();
}
}
}
|
// ReSharper disable InconsistentNaming
namespace Properties.Infrastructure.Rightmove.Objects
{
public class RmrtdfResponseProperty
{
public string agent_ref { get; set; }
public int? rightmove_id { get; set; }
public string rightmove_url { get; set; }
public string change_type { get; set; }
}
}
|
using System;
using BootLoader.Impl;
using BootLoader.Interfaces;
namespace BootLoaderUnitTestProject
{
public class FakeTimer : ITimer
{
private double _interval;
private double _currentTime;
private bool _isStarted;
public void Dispose() {
}
public void Start(double interval) {
_interval = interval;
_currentTime = 0.0;
_isStarted = true;
}
public void Advance(double interval) {
var prevCount = _currentTime/_interval;
_currentTime += interval;
var lastCount = _currentTime/_interval;
var count = (int)(lastCount - prevCount);
if (!_isStarted) return;
for (var x = 0; x < count; ++x) {
Elapsed(this, new TimerEventArg());
}
}
public void Stop() {
_isStarted = false;
}
public event TimerEventHandler Elapsed;
public object Clone() {
return this.MemberwiseClone();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class ProgressBar : MonoBehaviour //U use this script for do something with scene(chenge it)
{
public float F_speed;
public GameObject G_Fill; //To do something with fill
public Image I_EdgeFillAmount; //To change amount
void Start()
{
F_speed = 0.1f;
I_EdgeFillAmount = G_Fill.GetComponent<Image>();
I_EdgeFillAmount.fillAmount = 0f;
}
// Update is called once per frame
void Update()
{
I_EdgeFillAmount.fillAmount += F_speed * Time.deltaTime; //timer
if (I_EdgeFillAmount.fillAmount >= 1) //player will die
{
Ball_Controller.S_Happened = "lose";
SceneManager.LoadScene("Lose");
print("GG");
Ball_Controller.S_Happened = "nope";
}
if (Ball_Controller.S_Happened == "win")
{
if (F_speed <= 0.5)
{
F_speed += 0.004f;
}
I_EdgeFillAmount.fillAmount = 0f;
Ball_Controller.S_Happened = "nope";
}
if (Ball_Controller.S_Happened == "lose")
{
StartCoroutine(I_LoseScene());
}
if (Ball_Controller.S_Happened == "middle")
{
StartCoroutine(I_LoseScene());
}
}
public IEnumerator I_LoseScene()
{
yield return new WaitForSeconds(0.5f);
SceneManager.LoadScene("Lose");
}
}
|
namespace TripDestination.Web.MVC.Areas.UserProfile.ViewModels
{
using Common.Infrastructure.Constants;
using Common.Infrastructure.Mapping;
using Data.Models;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
public class EditProfileInputModel : IMapFrom<User>
{
public BaseEditModel BaseModel { get; set; }
[Required]
[MinLength(ModelConstants.UserFirstNameMinLength, ErrorMessage = "User first name can not be less than 3 symbols long.")]
[MaxLength(ModelConstants.UserFirstNameMaxLength, ErrorMessage = "User first name can not be more than 50 symbols long.")]
public string FirstName { get; set; }
[Required]
[MinLength(ModelConstants.UserLastNameMinLength, ErrorMessage = "User last name can not be less than 3 symbols long.")]
[MaxLength(ModelConstants.UserLastNameMaxLength, ErrorMessage = "User last name can not be more than 50 symbols long.")]
public string LastName { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Display(Name = "Phone number")]
public virtual string PhoneNumber { get; set; }
[AllowHtml]
[MinLength(ModelConstants.UserDescriptionMinLength, ErrorMessage = "Description can not be less than 20 symbols long.")]
[MaxLength(ModelConstants.UserDescriptionMaxLength, ErrorMessage = "Description can not be more than 1000 symbols long.")]
public string Description { get; set; }
}
} |
using System;
namespace Bookings.Models.Exceptions
{
public class SeatsAlreadyBookedException : Exception
{
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shipwreck.TypeScriptModels.Declarations
{
public sealed class Parameter : Syntax
{
public Parameter() { }
public Parameter(string parameterName, ITypeReference parameterType = null)
{
ParameterName = parameterName;
ParameterType = parameterType;
}
public AccessibilityModifier Accessibility { get; set; }
public string ParameterName { get; set; }
public ITypeReference ParameterType { get; set; }
/// <summary>
/// Gets or sets the expression to be assigned to the parameter if not specified.
/// </summary>
[DefaultValue(null)]
public Expression Initializer { get; set; }
public bool IsOptional { get; set; }
public bool IsRest { get; set; }
#region Decorators
private Collection<Decorator> _Decorators;
/// <summary>
/// Gets a value indicating whether the value of <see cref="Decorators" /> contains any element;
/// </summary>
public bool HasDecorator
=> _Decorators?.Count > 0;
/// <summary>
/// Gets or sets the all decorators of the parameter.
/// </summary>
public Collection<Decorator> Decorators
{
get
{
return CollectionHelper.GetOrCreate(ref _Decorators);
}
set
{
CollectionHelper.Set(ref _Decorators, value);
}
}
/// <summary>
/// Determines a value indicating whether the value of <see cref="Decorators" /> needs to be persisted.
/// </summary>
/// <returns><c>true</c> if the property should be persisted; otherwise, <c>false</c>.</returns>
public bool ShouldSerializeDecorators()
=> HasDecorator;
/// <summary>
/// Resets the value for <see cref="Decorators" /> of the parameter to the default value.
/// </summary>
public void ResetDecorators()
=> _Decorators?.Clear();
#endregion Decorators
}
}
|
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StarlightRiver.Abilities;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace StarlightRiver.NPCs.Passive
{
class DesertWisp : ModNPC
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Desert Wisp");
}
public override void SetDefaults()
{
npc.width = 18;
npc.height = 18;
npc.damage = 0;
npc.defense = 0;
npc.lifeMax = 1;
npc.noGravity = true;
npc.noTileCollide = true;
npc.immortal = true;
npc.value = 0f;
npc.knockBackResist = 0f;
npc.aiStyle = 65;
}
bool fleeing = false;
public override void AI()
{
npc.TargetClosest(true);
Player player = Main.player[npc.target];
AbilityHandler mp = player.GetModPlayer<AbilityHandler>();
Vector2 distance = player.Center - npc.Center;
Dust.NewDustPerfect(npc.Center, mod.DustType("Air"), new Vector2(Main.rand.Next(-20, 20) * 0.01f, Main.rand.Next(-20, 20) * 0.01f));
if (LegendWorld.rottime == 0)
{
for (float k = 0; k <= Math.PI * 2; k += (float)Math.PI / 20)
{
Dust.NewDustPerfect(npc.Center, mod.DustType("Air"), new Vector2((float)Math.Cos(k), (float)Math.Sin(k)), 0, default, 0.5f);
}
}
float range = 180;
if (npc.localAI[2] > 0)
{
npc.localAI[2] -= 3.5f;
return;
}
if ((distance.Length() <= range && !(mp.wisp.Active)) || Main.dayTime)
{
fleeing = true;
}
if (fleeing)
{
npc.velocity.Y = 10;
npc.velocity.X = 0;
Dust.NewDustPerfect(npc.Center, mod.DustType("Air"), new Vector2(Main.rand.Next(-10, 10) * 0.1f, Main.rand.Next(-10, 10) * 0.1f));
}
}
public override float SpawnChance(NPCSpawnInfo spawnInfo)
{
return (spawnInfo.player.ZoneOverworldHeight && !Main.dayTime && spawnInfo.player.ZoneDesert) ? 1f : 0f;
}
}
class DesertWisp2 : ModNPC
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Greater Desert Wisp");
}
public override void SetDefaults()
{
npc.width = 24;
npc.height = 24;
npc.damage = 0;
npc.defense = 0;
npc.lifeMax = 1;
npc.noGravity = true;
npc.noTileCollide = true;
npc.immortal = true;
npc.value = 0f;
npc.knockBackResist = 0f;
npc.aiStyle = 65;
}
bool fleeing = false;
public override void AI()
{
npc.TargetClosest(true);
Player player = Main.player[npc.target];
AbilityHandler mp = player.GetModPlayer<AbilityHandler>();
Vector2 distance = player.Center - npc.Center;
Dust.NewDustPerfect(npc.Center, mod.DustType("Air"), new Vector2(Main.rand.Next(-40, 40) * 0.01f, Main.rand.Next(-40, 40) * 0.01f));
if (LegendWorld.rottime == 0)
{
for (float k = 0; k <= Math.PI * 2; k += (float)Math.PI / 20)
{
Dust.NewDustPerfect(npc.Center, mod.DustType("Air"), new Vector2((float)Math.Cos(k), (float)Math.Sin(k)), 0, default, 0.6f);
}
}
float range = 120;
if (npc.localAI[2] > 0)
{
npc.localAI[2] -= 3.5f;
return;
}
if (distance.Length() <= range && !(mp.wisp.Active))
{
fleeing = true;
}
else
{
fleeing = false;
}
if (fleeing)
{
npc.velocity += Vector2.Normalize(distance) * -10;
Dust.NewDustPerfect(npc.Center, mod.DustType("Air"), new Vector2(Main.rand.Next(-10, 10) * 0.1f, Main.rand.Next(-10, 10) * 0.1f));
}
}
public override float SpawnChance(NPCSpawnInfo spawnInfo)
{
return (spawnInfo.player.ZoneRockLayerHeight && spawnInfo.player.GetModPlayer<BiomeHandler>().ZoneGlass) ? 3f : 0f;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScreenManager : MonoBehaviour
{
public delegate void GameEvent();
public static event GameEvent OnNewGame;
public static event GameEvent OnStartGame;
public static event GameEvent OnExitGame;
public enum Screens {
TitleScreen,
GameScreen,
ScoresScreen,
MainMenuScreen,
JoinGameScreen,
JoiningScreen,
CreateErrorScreen,
JoinErrorScreen,
DisconnectErrorScreen,
InstructionsScreen0,
InstructionsScreen1,
InstructionsScreen2,
InstructionsScreen3,
InstructionsScreen4,
InstructionsScreen5,
InstructionsScreen6,
NumScreens
}
private Canvas [] mScreens;
private Screens mCurrentScreen;
private NetworkManagerHUDCustom mNetHUD;
[SerializeField]
private Text[] ScoreTextElements;
// Special menu elements
// All of these exist in the GameScreen, but they have to be handled depending on the situation
// Several screens could be created, but then it would be difficult to have elements that are common to all of them.
[SerializeField]
private GameObject EscapeMenu;
[SerializeField]
private GameObject LobbyHostMenu;
[SerializeField]
private GameObject LobbyClientMenu;
[SerializeField]
private GameObject DefeatPanel;
[SerializeField]
private GameObject TimerBar;
void Awake()
{
mNetHUD = GetComponent<NetworkManagerHUDCustom>();
GameManager.OnGameOver += GameManager_OnGameOver;
GameManager.OnDefeat += GameManager_OnDefeat;
GameManager.OnStart += GameManager_OnStart;
GameManager.OnGameTimeLeftChange += GameManager_OnGameTimeLeftChange;
mScreens = new Canvas[(int)Screens.NumScreens];
Canvas[] screens = GetComponentsInChildren<Canvas>();
for (int count = 0; count < screens.Length; ++count)
{
for (int slot = 0; slot < mScreens.Length; ++slot)
{
if (mScreens[slot] == null && ((Screens)slot).ToString() == screens[count].name)
{
mScreens[slot] = screens[count];
break;
}
}
}
for (int screen = 1; screen < mScreens.Length; ++screen)
{
mScreens[screen].enabled = false;
}
mCurrentScreen = Screens.TitleScreen;
}
void Update()
{
if (mCurrentScreen == Screens.GameScreen && Input.GetKeyDown(KeyCode.Escape)) // Toggle in-game menu
{
EscapeMenu.SetActive(!EscapeMenu.activeSelf);
}
}
public void OpenMainMenu()
{
TransitionTo(Screens.MainMenuScreen);
}
public void StartGame()
{
if (mNetHUD.StartHost())
{
if (OnNewGame != null)
{
OnNewGame();
}
TransitionTo(Screens.GameScreen);
LobbyHostMenu.SetActive(true);
LobbyClientMenu.SetActive(false);
DefeatPanel.SetActive(false);
TimerBar.transform.parent.gameObject.SetActive(false);
EscapeMenu.SetActive(false);
}
else
{
TransitionTo(Screens.CreateErrorScreen);
}
}
public void LobbyStartGame()
{
if (OnStartGame != null)
{
TimerBar.transform.parent.gameObject.SetActive(true);
LobbyHostMenu.SetActive(false);
OnStartGame();
}
}
public void EndGame()
{
if (OnExitGame != null)
{
OnExitGame();
}
TransitionTo(Screens.MainMenuScreen);
mNetHUD.StopGame();
}
public void SelectHost()
{
TransitionTo(Screens.JoinGameScreen);
}
public void JoinGame(InputField inputField)
{
TransitionTo(Screens.JoiningScreen);
mNetHUD.StartClient(inputField.text.Length == 0 ? "localhost" : inputField.text);
}
public void OnGameJoined()
{
if (OnNewGame != null)
{
OnNewGame();
}
TransitionTo(Screens.GameScreen);
LobbyHostMenu.SetActive(false);
LobbyClientMenu.SetActive(true);
DefeatPanel.SetActive(false);
TimerBar.transform.parent.gameObject.SetActive(false);
EscapeMenu.SetActive(false);
}
public void CancelJoin()
{
mNetHUD.OnCancelJoin();
TransitionTo(Screens.MainMenuScreen);
}
public void OnJoinError()
{
TransitionTo(Screens.JoinErrorScreen);
}
public void ExitGame()
{
Application.Quit();
}
public void OnDisconnectError()
{
TransitionTo(Screens.DisconnectErrorScreen);
}
public void GoToInstructions(int index)
{
TransitionTo(Screens.InstructionsScreen0 + index);
}
private void TransitionTo(Screens screen)
{
mScreens[(int)mCurrentScreen].enabled = false;
mScreens[(int)screen].enabled = true;
mCurrentScreen = screen;
}
private void GameManager_OnGameOver(int[] scores)
{
for (int i = 0; i < ScoreTextElements.Length; i++)
{
if (ScoreTextElements[i] != null)
{
ScoreTextElements[i].text = "-";
if (i < scores.Length && scores[i] >= 0)
{
ScoreTextElements[i].text = "" + scores[i];
}
}
}
TransitionTo(Screens.ScoresScreen);
}
private void GameManager_OnDefeat()
{
DefeatPanel.SetActive(true);
}
private void GameManager_OnStart()
{
LobbyHostMenu.SetActive(false);
LobbyClientMenu.SetActive(false);
TimerBar.transform.parent.gameObject.SetActive(true);
}
private void GameManager_OnGameTimeLeftChange(float ratio)
{
Vector3 barScale = TimerBar.transform.localScale;
barScale.x = ratio;
TimerBar.transform.localScale = barScale;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Day3
{
class Program
{
static void Main(string[] args)
{
// Rinka linijas - apkartmers un laukums
//
Console.WriteLine("Ieraksti radiusu: ");
string RadiusX = Console.ReadLine();
double RadiusY = Convert.ToDouble(RadiusX);
Rinkis rinkis1 = new Rinkis();
double rezultats = rinkis1.Apkartmers1(RadiusY);
Console.WriteLine(rezultats + " ir rinka apkartmers.");
double rezultats2 = rinkis1.Laukums1(RadiusY);
Console.WriteLine(rezultats2 + " ir rinka laukums.");
string vards, uzvards; // deklarejam vairakus mainigos
Console.WriteLine("Ludzu ievadiet savu vardu!");
vards = Console.ReadLine();
Console.WriteLine("Ludzu ievadiet savu uzvardu!");
uzvards = Console.ReadLine();
IzvaditSveicienu(vards, uzvards);
/////// Diametrs un Laukums
Console.WriteLine("! Diametra un laukuma apreikinasana !");
Console.WriteLine("Ieraksti radiusu: ");
string Radius1 = Console.ReadLine();
double Radius2 = Convert.ToDouble(Radius1);
double Diametrs1 = RinkaLinija(Radius2);
Console.WriteLine(Diametrs1 + " ir diametrs");
double Laukums1 = RinkaLinija2(Radius2);
Console.WriteLine(Laukums1 + " ir laukums");
/////// Degvielas paterins
Console.WriteLine("! Degvielas paterina apreikinasanas programma !");
Console.WriteLine("Ievadi degvielas paterinu /100 km! ");
string DegPat = Console.ReadLine();
double DegPat2 = Convert.ToDouble(DegPat);
Console.WriteLine("Ievadi degvielas cenu Eur/litrs! ");
string DegCena = Console.ReadLine();
double DegCena2 = Convert.ToDouble(DegCena);
Console.WriteLine("Ievadi planoto distanci!");
string Distance = Console.ReadLine();
double Distance2 = Convert.ToDouble(Distance);
Degviela degviela1 = new Degviela();
double KopaIznak = degviela1.DegvielasPaterins(DegPat2, DegCena2, Distance2);
Console.WriteLine(KopaIznak + " Eur bus jasamaksa");
/////////////
//Radam objektu no klases
Console.WriteLine("! Jauns objekts un klase !");
JaunaKlase objekts1 = new JaunaKlase(); // izsaucam konstruktoru
JaunaKlase objekts2 = new JaunaKlase();
int Vetiba = objekts1.Saskaitit(8, 5);
objekts1.globals = 100 + 5;
Console.WriteLine(objekts1.globals);
Console.WriteLine(objekts2.globals);
////////
// Matematika, Jauna klase
Console.WriteLine("! jauna klase, Matematika !");
Matematika matematika1 = new Matematika();
int GalaRezultats = matematika1.AtnemamSkaitlus(20, 5);
int GalaRezultats2 = matematika1.SaskaitamSkaitlus(20, 5);
Console.WriteLine(GalaRezultats + " atnemsana done ");
Console.WriteLine(GalaRezultats2 + " saskaitisana done ");
Console.ReadLine();
}
static void IzvaditSveicienu(string a, string b)
{
Console.WriteLine("Sveiki " + a + " " + b + ", prieks tevi redzet!");
}
static double RinkaLinija(double a)
{
double Diametrs = 2 * a;
return Diametrs;
}
static double RinkaLinija2(double a)
{
double Pi = 3.14;
double Laukums = 2 * Pi * a;
return Laukums;
}
}
}
|
using Fingo.Auth.DbAccess.Repository.Interfaces;
using Fingo.Auth.Domain.Policies.Factories.Actions.Implementation;
using Fingo.Auth.Domain.Policies.Factories.Actions.Interfaces;
using Fingo.Auth.Domain.Policies.Factories.Interfaces;
using Fingo.Auth.Domain.Policies.Services.Interfaces;
namespace Fingo.Auth.Domain.Policies.Factories.Implementation
{
public class GetUserPolicyConfigurationOrDefaultFromProjectFactory :
IGetUserPolicyConfigurationOrDefaultFromProjectFactory
{
private readonly IPolicyJsonConvertService policyJsonConvertService;
private readonly IUserRepository userRepository;
public GetUserPolicyConfigurationOrDefaultFromProjectFactory(IUserRepository userRepository ,
IPolicyJsonConvertService policyJsonConvertService)
{
this.userRepository = userRepository;
this.policyJsonConvertService = policyJsonConvertService;
}
public IGetUserPolicyConfigurationOrDefaultFromProject Create()
{
return new GetUserPolicyConfigurationOrDefaultFromProject(userRepository , policyJsonConvertService);
}
}
} |
namespace P08PetClinic
{
using System;
public class Room : IComparable<Room>
{
public Room(int roomNumber, Pet petInRoom)
{
this.RoomNumber = roomNumber;
this.PetInRoom = petInRoom;
}
public Room(int roomNumber)
{
this.RoomNumber = roomNumber;
}
public int RoomNumber { get; }
public Pet PetInRoom { get; set; }
public int CompareTo(Room other)
{
return this.RoomNumber.CompareTo(other.RoomNumber);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
[SerializeField] private GameObject _gun = null;
[SerializeField] private GameObject _tower = null;
[Header("Rotation bounds"), Space(10)]
[SerializeField] private Vector2 _towerBounds = new Vector2(-40,40);
[SerializeField] private Vector2 _gunBounds = new Vector2(0,20);
[Header("Shooting"), Space(10)]
[SerializeField] private GameObject _shell = null;
[SerializeField] private Transform _shootingPoint = null;
[SerializeField] private GameObject _shotExplosion = null;
private Vector3 _towerEulerAngles;
private Cursor _cursor;
private void Start()
{
_cursor = FindObjectOfType<Cursor>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Shot();
}
}
private void FixedUpdate()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (!hit.collider.CompareTag("Wall"))
{
// rotate tower
var lookPos = hit.point - _tower.transform.position;
var rotation = Quaternion.LookRotation(lookPos);
// rotation boundaries
rotation.y = Mathf.Clamp(rotation.y, _towerBounds.x, _towerBounds.y);
rotation.z = 0;
rotation.x = 0;
_tower.transform.rotation = Quaternion.Slerp(_tower.transform.rotation, rotation, Time.deltaTime * 1.25f);
_tower.transform.rotation.eulerAngles.Set(0, rotation.y, 0);
_towerEulerAngles = _tower.transform.rotation.eulerAngles;
// rotate gun
lookPos = hit.point - _gun.transform.position;
rotation = Quaternion.LookRotation(lookPos);
// rotation boundaries
rotation.x = Mathf.Clamp(rotation.x, _gunBounds.x, _gunBounds.y);
_gun.transform.rotation = Quaternion.Slerp(_gun.transform.rotation, rotation, Time.deltaTime * 3);
_gun.transform.rotation.eulerAngles.Set(rotation.x, 0, 0);
// The cursor must not go outside the world
_cursor.SetGreenState();
} else
{
_cursor.SetRedState();
}
}
}
private void Shot()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (!hit.collider.CompareTag("Wall"))
{
// spawn new shell
Rigidbody newShell = Instantiate(_shell, _shootingPoint.position, Quaternion.identity).GetComponent<Rigidbody>();
// spawn particle explosion
Instantiate(_shotExplosion, _shootingPoint.position, Quaternion.identity);
// calculate force to the target
Vector3 force = calcBallisticVelocityVector(_shootingPoint.position, hit.point, 15);
newShell.AddForce(force, ForceMode.Impulse);
}
}
}
private Vector3 calcBallisticVelocityVector(Vector3 source, Vector3 target, float angle)
{
Vector3 direction = target - source;
float h = direction.y;
direction.y = 0;
float distance = direction.magnitude;
float a = angle * Mathf.Deg2Rad;
direction.y = distance * Mathf.Tan(a);
distance += h / Mathf.Tan(a);
// calculate velocity
float velocity = 1;
if (Vector3.Distance(source, target) > 10)
{
velocity = Mathf.Sqrt(distance * Physics.gravity.magnitude / Mathf.Sin(2 * a));
}
return velocity * direction.normalized;
}
public bool CanRotationTank()
{
return _towerEulerAngles.y <= _towerBounds.x || _towerEulerAngles.y >= _towerBounds.y;
}
}
|
internal class roomObject
{
} |
using ISE.Framework.Common.Aspects;
using ISE.Framework.Common.Service.Message;
using ISE.Framework.Common.Service.ServiceBase;
using ISE.SM.Common.DTO;
using ISE.SM.Common.DTOContainer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace ISE.SM.Common.Contract
{
[ServiceContract(Namespace = "http://www.iseikco.com/Sec")]
public interface IRoleService : IServiceBase
{
[OperationContract]
[Process]
ResponseDto ActivateRole(RoleDto role);
[OperationContract]
[Process]
ResponseDto DeActivateRole(RoleDto role);
[OperationContract]
[Process]
UserDtoContainer AssignedUsers(RoleDto role);
[OperationContract]
[Process]
ResponseDto AddInheritance(int parentRoleId, int childRoleId);
[OperationContract]
[Process]
ResponseDto DeleteInheritance(int parentRoleId, int childRoleId);
[OperationContract]
[Process]
ResponseDto AddAscendant(RoleDto parent, int childRoleId);
[OperationContract]
[Process]
ResponseDto AddDescendant(RoleDto child, int parentRoleId);
[OperationContract]
[Process]
RoleToRoleConstraintDto AddRoleToRoleConstraint(RoleToRoleConstraintDto constraint);
[OperationContract]
[Process]
UserToRoleConstraintDto AddUserToRoleConstraint(UserToRoleConstraintDto constraint);
[OperationContract]
[Process]
RoleToRoleConstraintDto UpdateRoleToRoleConstraint(RoleToRoleConstraintDto constraint);
[OperationContract]
[Process]
UserToRoleConstraintDto UpdateUserToRoleConstraint(UserToRoleConstraintDto constraint);
[OperationContract]
[Process]
ResponseDto RemoveRoleToRoleConstraint(RoleToRoleConstraintDto constraint);
[OperationContract]
[Process]
ResponseDto RemoveUserToRoleConstraint(UserToRoleConstraintDto constraint);
[OperationContract]
[Process]
SecurityGroupDtoContainer RoleGroups(RoleDto role);
}
}
|
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
namespace GridViewExtensions.GridFilters
{
/// <summary>
/// A control with a <see cref="ComboBox"/> and two <see cref="TextBox"/>es
/// needed in the <see cref="NumericGridFilter"/>.
/// </summary>
public class NumericGridFilterControl : System.Windows.Forms.UserControl
{
#region Fields
private System.Windows.Forms.TextBox _textBox1;
private System.Windows.Forms.TextBox _textBox2;
private System.Windows.Forms.ComboBox _comboBox;
private System.ComponentModel.Container components = null;
#endregion
#region Events
/// <summary>
/// Event firing when either the <see cref="ComboBox"/> or
/// the <see cref="TextBox"/> has changed.
/// </summary>
public event System.EventHandler Changed;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance
/// </summary>
public NumericGridFilterControl()
{
InitializeComponent();
_comboBox.SelectedIndex = 0;
}
#endregion
#region Overridden from UserControl
/// <summary>
/// Cleans up.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Resizes the contained <see cref="DateTimePicker"/>s so that they
/// have the same width.
/// </summary>
/// <param name="e">Event arguments.</param>
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
RefreshTextBoxWidth();
}
#endregion
#region Designer generated code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent()
{
this._textBox1 = new System.Windows.Forms.TextBox();
this._textBox2 = new System.Windows.Forms.TextBox();
this._comboBox = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// _textBox1
//
this._textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this._textBox1.Location = new System.Drawing.Point(40, 0);
this._textBox1.Name = "_textBox1";
this._textBox1.Size = new System.Drawing.Size(0, 20);
this._textBox1.TabIndex = 1;
this._textBox1.TextChanged += new System.EventHandler(this.OnChanged);
this._textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown);
this._textBox1.KeyUp += new System.Windows.Forms.KeyEventHandler(this.OnKeyUp);
this._textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.OnKeyPress);
//
// _textBox2
//
this._textBox2.Dock = System.Windows.Forms.DockStyle.Right;
this._textBox2.Location = new System.Drawing.Point(40, 0);
this._textBox2.Name = "_textBox2";
this._textBox2.Size = new System.Drawing.Size(104, 20);
this._textBox2.TabIndex = 2;
this._textBox2.TextChanged += new System.EventHandler(this.OnChanged);
this._textBox2.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown);
this._textBox2.KeyUp += new System.Windows.Forms.KeyEventHandler(this.OnKeyUp);
this._textBox2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.OnKeyPress);
//
// _comboBox
//
this._comboBox.Dock = System.Windows.Forms.DockStyle.Left;
this._comboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._comboBox.Items.AddRange(new object[] {
"*",
"=",
"<>",
">",
"<",
">=",
"<="});
this._comboBox.Location = new System.Drawing.Point(0, 0);
this._comboBox.Name = "_comboBox";
this._comboBox.Size = new System.Drawing.Size(40, 21);
this._comboBox.TabIndex = 0;
this._comboBox.SelectedIndexChanged += new System.EventHandler(this.OnChanged);
this._comboBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.OnKeyPress);
this._comboBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.OnKeyUp);
this._comboBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown);
//
// NumericGridFilterControl
//
this.Controls.Add(this._textBox1);
this.Controls.Add(this._textBox2);
this.Controls.Add(this._comboBox);
this.Name = "NumericGridFilterControl";
this.Size = new System.Drawing.Size(144, 21);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
#region Public interface
/// <summary>
/// Gets the first contained <see cref="TextBox"/> instance.
/// </summary>
public TextBox TextBox1
{
get { return _textBox1; }
}
/// <summary>
/// Gets the second contained <see cref="TextBox"/> instance.
/// </summary>
public TextBox TextBox2
{
get { return _textBox2; }
}
/// <summary>
/// Gets the contained <see cref="ComboBox"/> instance.
/// </summary>
public ComboBox ComboBox
{
get { return _comboBox; }
}
#endregion
#region Privates
private void RefreshTextBoxWidth()
{
_textBox2.Width = (this.Width - _comboBox.Width) / 2;
}
private void OnChanged(object sender, System.EventArgs e)
{
this._textBox2.Visible = _comboBox.Text == NumericGridFilter.IN_BETWEEN;
if (Changed != null)
Changed(this, e);
}
private void OnKeyPress(object sender, KeyPressEventArgs e)
{
base.OnKeyPress(e);
}
private void OnKeyUp(object sender, KeyEventArgs e)
{
base.OnKeyUp(e);
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
base.OnKeyDown(e);
}
#endregion
}
}
|
using UnityEngine;
using UnityEngine.Playables;
[System.Serializable]
public class BlendShapeBehaviour : PlayableBehaviour
{
public SkinnedMeshRenderer FaceMesh;
public BlendShapeClip.Shape[] Shapes;
public override void ProcessFrame(Playable playable, FrameData info, object playerData)
{
FaceMesh = playerData as SkinnedMeshRenderer;
if (Shapes != null && Shapes.Length != 0)
{
for (int i = 0; i < Shapes.Length; i++)
{
Shapes[i].CalculateWeight(playable.GetTime());
FaceMesh.SetBlendShapeWeight(Shapes[i].Index, Shapes[i].Weight);
}
}
}
public string[] GetShapeNames()
{
int count = FaceMesh.sharedMesh.blendShapeCount;
string[] names = new string[count];
for (int i = 0; i < count; ++i)
names[i] = FaceMesh.sharedMesh.GetBlendShapeName(i);
return names;
}
public string GetShapeName(int index)
{
return FaceMesh.sharedMesh.GetBlendShapeName(index);
}
}
|
//---------------------------------------------------------------------------------
// Copyright (c) December 2019, devMobile Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//---------------------------------------------------------------------------------
namespace devMobile.IoT.Rfm9x.RegisterRead
{
using System;
using System.Threading.Tasks;
using Meadow;
using Meadow.Devices;
using Meadow.Hardware;
public class MeadowApp : App<F7Micro, MeadowApp>
{
const byte RegVersion = 0x42;
SpiPeripheral sx127xDevice;
IDigitalOutputPort chipSelectGpioPin;
IDigitalOutputPort resetGpioPin;
public MeadowApp()
{
Console.WriteLine("Starting devMobile.IoT.Rfm9x.RegisterRead");
ConfigureSpiPort();
ReadDeviceID();
}
public void ConfigureSpiPort()
{
try
{
ISpiBus spiBus = Device.CreateSpiBus(500);
if (spiBus == null)
{
Console.WriteLine("spiBus == null");
}
Console.WriteLine("Creating SPI NSS Port...");
chipSelectGpioPin = Device.CreateDigitalOutputPort(Device.Pins.D09, initialState: true);
if (chipSelectGpioPin == null)
{
Console.WriteLine("chipSelectPin == null");
}
Console.WriteLine("sx127xDevice Device...");
sx127xDevice = new SpiPeripheral(spiBus, chipSelectGpioPin);
if (sx127xDevice == null)
{
Console.WriteLine("sx127xDevice == null");
}
// Factory reset pin configuration
resetGpioPin = Device.CreateDigitalOutputPort(Device.Pins.D10, true);
if (sx127xDevice == null)
{
Console.WriteLine("resetPin == null");
}
Console.WriteLine("ConfigureSpiPort Done...");
}
catch (Exception ex)
{
Console.WriteLine("ConfigureSpiPort " + ex.Message);
}
}
public void ReadDeviceID()
{
Task.Delay(500).Wait();
while (true)
{
try
{
byte registerValue;
// Using this device level approach works, without buffer size issues
Console.WriteLine("sx127xDevice.ReadRegister...1");
registerValue = sx127xDevice.ReadRegister(RegVersion);
Console.WriteLine("sx127xDevice.ReadRegister...2");
Console.WriteLine("Register 0x{0:x2} - Value 0X{1:x2} - Bits {2}", RegVersion, registerValue, Convert.ToString(registerValue, 2).PadLeft(8, '0'));
}
catch (Exception ex)
{
Console.WriteLine("ReadDeviceIDDiy " + ex.Message);
}
Task.Delay(10000).Wait();
}
}
}
}
|
namespace BattleEngine.Output
{
public class FinishEvent : OutputEvent
{
public FinishEvent()
{
}
}
}
|
using System;
using System.Threading;
using OpenQA.Selenium;
using Framework.Core.Common;
using OpenQA.Selenium.Support.PageObjects;
using Tests.Pages.Van.Main.Common;
namespace Tests.Pages.Van.Main.Demographic
{
public class DemographicsBasePage : VanBasePage
{
#region Page Element Declarations
public By ResultGridLocator = By.Id("ResultGrid");
public IWebElement ResultGrid { get { return _driver.FindElement(ResultGridLocator); } }
// displays "Loading..." while waiting for the grid to load - changes style : none when disappearing
public By DataPlaceHolderLocator = By.CssSelector("tr#DataPlaceHolder");
#endregion
public DemographicsBasePage(Driver driver) : base(driver) { }
#region Methods
/// <summary>
/// verifies result table count displays and is not empty
/// </summary>
public bool VerifyResultsDisplay()
{
int rowCount = _driver.GetRowCountInTable(ResultGrid);
rowCount = rowCount - 2; //subtracting header and footer
return rowCount >= 1;
}
#endregion
public void GoToPublicDemographicsLink(string url)
{
_driver.GoToPage(url);
WaitForLoadingPlaceHolderToDisappear();
_driver.WaitForElementToDisplayBy(ResultGridLocator);
}
public void WaitForLoadingPlaceHolderToDisappear()
{
_driver.WaitForAttributeToDisplayValue(DataPlaceHolderLocator, "style", "none");
}
}
}
|
using Uintra.Core.Member.Profile.Edit.Models;
using Uintra.Core.Member.Profile.Models;
namespace Uintra.Core.User
{
public interface IIntranetUserContentProvider
{
ProfilePageModel GetProfilePage();
ProfileEditPageModel GetEditPage();
}
}
|
using UnityEngine;
using System.Collections;
public class GameMenu : MonoBehaviour {
private Rect rect_menuBtn;
void Start () {
rect_menuBtn = new Rect(Screen.width - 85, 15, 70, 30);
}
void OnGUI() {
if (GUI.Button(rect_menuBtn, "Menu")) {
Application.LoadLevel(0);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
namespace DemoWebApp.Models
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class,AllowMultiple = false)]
public class ExportDemoAttribute : ExportAttribute
{
public ExportDemoAttribute(string demoName) : base(typeof(IDemo))
{
DemoName = demoName;
}
public string DemoName { get; set; }
}
public interface IDemo
{
IEnumerable<string> Run();
}
public interface IDemoMetadata
{
string DemoName { get; }
}
} |
using System;
using System.Collections.Generic;
namespace BlazorShared.Models.Doctor
{
public class ListDoctorResponse : BaseResponse
{
public List<DoctorDto> Doctors { get; set; } = new List<DoctorDto>();
public int Count { get; set; }
public ListDoctorResponse(Guid correlationId) : base(correlationId)
{
}
public ListDoctorResponse()
{
}
}
} |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Tails_Of_Joy.Models;
using Tails_Of_Joy.Repositories;
namespace Tails_Of_Joy.Controllers
{
//[Authorize]
[Route("api/[controller]")]
[ApiController]
public class AdoptionController : ControllerBase
{
private readonly IUserProfileRepository _userProfileRepository;
private readonly IAdoptionRepository _adoptionRepository;
public AdoptionController(IAdoptionRepository adoptionRepository,
IUserProfileRepository userProfileRepository)
{
_userProfileRepository = userProfileRepository;
_adoptionRepository = adoptionRepository;
}
// Displaying All Adopted Animals Attached to the User
// GET: api/<AdoptionController>
[HttpGet("user/{id}")]
public IActionResult GetbyUser(int id)
{
return Ok(_adoptionRepository.GetAllAdoptionsByUserProfileId(id));
}
// Displaying All the Pending Adoptions
// GET: api/<AdoptionController>
[HttpGet("pending")]
public IActionResult GetAllPending()
{
return Ok(_adoptionRepository.GetAllPendingAdoptions());
}
// Displaying All the Approved adoptions
// GET: api/<AdoptionController>
[HttpGet]
public IActionResult GetAllApproved()
{
var currentUserProfile = GetCurrentUserProfile();
if (currentUserProfile == null)
{
return Unauthorized();
}
return Ok(_adoptionRepository.GetAllApprovedAdoptions());
}
//Displaying details of one Adoption
// GET api/<AdoptionController>/5
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var adoption = _adoptionRepository.GetById(id);
if (adoption != null)
{
NotFound();
}
return Ok(adoption);
}
//Adding a new adoption
// POST api/<AdoptionController>
[HttpPost]
public IActionResult Post(Adoption adoption)
{
_adoptionRepository.Add(adoption);
return CreatedAtAction("Get", new { id = adoption.Id }, adoption);
}
// Updating a Single Adoption, Approving it
// PUT api/<AdoptionController>/5
[HttpPut("{id}")]
public IActionResult Put(int id, Adoption adoption)
{
if (id != adoption.Id)
{
return BadRequest();
}
_adoptionRepository.Update(adoption);
return Ok(adoption);
}
// Updating a single Adoption, Denying it
// DELETE api/<AnimalController>/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
_adoptionRepository.Delete(id);
return Ok(id);
}
private UserProfile GetCurrentUserProfile()
{
var firebaseUserId = User.FindFirst(ClaimTypes.NameIdentifier).Value;
return _userProfileRepository.GetByFirebaseUserId(firebaseUserId);
}
}
}
|
using Geolocator.Plugin.Abstractions;
using System;
using System.Collections.Generic;
using System.Text;
namespace surfnsail.Models
{
public class PositionItem
{
public int RouteID { get; set; }
public Position Position { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NSTOX.DAL.Model;
using NSTOX.DAL.Extensions;
namespace NSTOX.DAL.DAL
{
public class ItemDAL : BaseDAL
{
private DataErrorDAL DataErrDAL;
public ItemDAL(DataErrorDAL dataErrorDAL)
{
DataErrDAL = dataErrorDAL;
}
public byte InsertItem(Item item)
{
try
{
ExecuteNonQuery("usp_Insert_Item", item);
return 0;
}
catch (Exception ex)
{
string note = ex.Message;
if (ex.Message.Contains("dbo.Department_"))
{
note = string.Format("Error inserting Item. Department with ID: {0} does not exist.", item.DepartmentId);
}
DataError dataError = new DataError { RetailerId = item.RetailerId, Source = InputFileType.Items, ElementId = item.SKU, Note = note };
DataErrDAL.InsertDataError(dataError);
return 1;
}
}
public byte UpdateItem(Item item, Item oldItem)
{
try
{
ExecuteNonQuery("usp_Insert_ItemAudit", new { RetailerId = item.RetailerId, SKU = item.SKU, OldValue = oldItem.ToXML(), NewValue = item.ToXML() });
ExecuteNonQuery("usp_Update_Item", item);
return 0;
}
catch (Exception ex)
{
DataError dataError = new DataError { RetailerId = item.RetailerId, Source = InputFileType.Items, ElementId = item.SKU, Note = ex.Message };
DataErrDAL.InsertDataError(dataError);
return 1;
}
}
public byte DeleteItem(int retailerId, Int64 sku)
{
try
{
ExecuteNonQuery("usp_Delete_Item", new { RetailerId = retailerId, SKU = sku });
return 0;
}
catch (Exception ex)
{
DataError dataError = new DataError { RetailerId = retailerId, Source = InputFileType.Items, ElementId = sku, Note = ex.Message };
DataErrDAL.InsertDataError(dataError);
return 1;
}
}
public Item GetItemBySKU(int retailerId, int sku)
{
return GetFromDBAndMapToObjectsList<Item>("usp_Get_ItemBySKU", new { RetailerId = retailerId, SKU = sku }).FirstOrDefault();
}
public List<Item> GetAllItems(int retailerId)
{
return GetFromDBAndMapToObjectsList<Item>("usp_Get_Items", new { RetailerId = retailerId });
}
}
}
|
using UnityEngine;
using System.Collections;
public class LevelChanger : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.F1)){
LevelLoader.LoadLevel("Level1");
}else if(Input.GetKeyDown(KeyCode.F2)){
LevelLoader.LoadLevel("Level2");
}else if(Input.GetKeyDown(KeyCode.F3)){
LevelLoader.LoadLevel("Level3");
}else if(Input.GetKeyDown(KeyCode.F4)){
LevelLoader.LoadLevel("Level4");
}else if(Input.GetKeyDown(KeyCode.F5)){
LevelLoader.LoadLevel("Level5");
}else if(Input.GetKeyDown(KeyCode.F6)){
LevelLoader.LoadLevel("Level6");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterState : MonoBehaviour
{
//적과 플레이어의 동일한 상태
public bool isStunned;
public bool isSlowed;
public bool isInvulnerability;
public List<float> SlowAmountList;
public float SlowAmount;
PlayerControl pc;
CharacterStat cs;
private void Start()
{
pc = GetComponent<PlayerControl>();
cs = GetComponent<CharacterStat>();
}
private void Update()
{
CheckMaxAmount(); //혹은 리스트 변경때만
}
//효과
public void AffectSlow(float amount, float duration)
{
StartCoroutine(AffectSlowCoolControl(amount, duration));
}
IEnumerator AffectSlowCoolControl(float amount, float duration)
{
float slowCurCool = duration;
SlowAmountList.Add(amount);
while (slowCurCool >= 0)
{
slowCurCool -= Time.deltaTime;
yield return null;
}
SlowAmountList.Remove(amount);
}
//최대 효과 적용
void CheckMaxAmount()
{
SlowAmount = Mathf.Max(SlowAmountList.ToArray());
pc.speed = cs.MoveSpeed * (1 - (SlowAmount / 100));
}
} |
using DependencyViewModel;
using KinectSandbox.Common.Colors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
namespace KinectSandbox.ColorPicker.AllColorPicker
{
public class AllColorPickerViewModel : ViewModelBase, IAllColorPickerViewModel
{
/// <summary>
/// Gets and sets the view models for each supported layer
/// </summary>
public IEnumerable<ILayeredColor> Layers
{
get { return Get<IEnumerable<ILayeredColor>>(); }
private set { Set(value); }
}
public AllColorPickerViewModel(IPropertyStore propertyStore, Func<ILayeredColor> colorPickerViewModelFactory)
: base(propertyStore)
{
//init the layer collection
var layers = new List<ILayeredColor>();
var supportedLayers = Enum.GetValues(typeof(SupportedColorLayer)).Cast<SupportedColorLayer>().OrderBy(layer => layer);
int current = 500;
foreach (var layer in supportedLayers)
{
var layerVM = colorPickerViewModelFactory();
layerVM.SelectedLayer = layer;
layerVM.SelectedColor = Color.FromRgb(RGB.Blue.R, RGB.Blue.G, RGB.Blue.B);
layerVM.MinValue = current;
layerVM.MaxValue = current += 50;
layers.Add(layerVM);
}
this.Layers = layers;
}
}
}
|
using RogueDungeonCrawler.Enum;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RogueDungeonCrawler
{
class Program
{
static void Main(string[] args)
{
Level level = new Level();
//Gameloop
while (true)
{
var input = Console.ReadKey(true);
switch (input.Key)
{
case ConsoleKey.S:
level.HandleSetStart();
break;
case ConsoleKey.E:
level.HandleSetEnd();
break;
case ConsoleKey.T:
level.HandleTalisman();
break;
case ConsoleKey.G:
level.HandleGrenade();
break;
case ConsoleKey.C:
level.HandleCompass();
break;
case ConsoleKey.UpArrow:
level.Move(Direction.North);
break;
case ConsoleKey.RightArrow:
level.Move(Direction.East);
break;
case ConsoleKey.DownArrow:
level.Move(Direction.South);
break;
case ConsoleKey.LeftArrow:
level.Move(Direction.West);
break;
}
}
}
}
}
|
// ==========================================================================
// Copyright (c) 2011-2016, dlg.krakow.pl
// All Rights Reserved
//
// NOTICE: dlg.krakow.pl permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
// ==========================================================================
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gpx
{
public class GpxPoint : GeoPoint
{
protected GpxProperties Properties_ = new GpxProperties();
public double Elevation { get; set; }
public DateTime? Time { get; set; }
public double? MagneticVar
{
get { return Properties_.GetValueProperty<double>("MagneticVar"); }
set { Properties_.SetValueProperty<double>("MagneticVar", value); }
}
public double? GeoidHeight
{
get { return Properties_.GetValueProperty<double>("GeoidHeight"); }
set { Properties_.SetValueProperty<double>("GeoidHeight", value); }
}
public string Name
{
get { return Properties_.GetObjectProperty<string>("Name"); }
set { Properties_.SetObjectProperty<string>("Name", value); }
}
public string Comment
{
get { return Properties_.GetObjectProperty<string>("Comment"); }
set { Properties_.SetObjectProperty<string>("Comment", value); }
}
public string Description
{
get { return Properties_.GetObjectProperty<string>("Description"); }
set { Properties_.SetObjectProperty<string>("Description", value); }
}
public string Source
{
get { return Properties_.GetObjectProperty<string>("Source"); }
set { Properties_.SetObjectProperty<string>("Source", value); }
}
public IList<GpxLink> Links
{
get { return Properties_.GetListProperty<GpxLink>("Links"); }
}
public string Symbol
{
get { return Properties_.GetObjectProperty<string>("Symbol"); }
set { Properties_.SetObjectProperty<string>("Symbol", value); }
}
public string Type
{
get { return Properties_.GetObjectProperty<string>("Type"); }
set { Properties_.SetObjectProperty<string>("Type", value); }
}
public string FixType
{
get { return Properties_.GetObjectProperty<string>("FixType"); }
set { Properties_.SetObjectProperty<string>("FixType", value); }
}
public int? Satelites
{
get { return Properties_.GetValueProperty<int>("Satelites"); }
set { Properties_.SetValueProperty<int>("Satelites", value); }
}
public double? Hdop
{
get { return Properties_.GetValueProperty<double>("Hdop"); }
set { Properties_.SetValueProperty<double>("Hdop", value); }
}
public double? Vdop
{
get { return Properties_.GetValueProperty<double>("Vdop"); }
set { Properties_.SetValueProperty<double>("Vdop", value); }
}
public double? Pdop
{
get { return Properties_.GetValueProperty<double>("Pdop"); }
set { Properties_.SetValueProperty<double>("Pdop", value); }
}
public double? AgeOfData
{
get { return Properties_.GetValueProperty<double>("AgeOfData"); }
set { Properties_.SetValueProperty<double>("AgeOfData", value); }
}
public int? DgpsId
{
get { return Properties_.GetValueProperty<int>("DgpsId"); }
set { Properties_.SetValueProperty<int>("DgpsId", value); }
}
public GpxLink HttpLink
{
get
{
return Links.Where(l => l != null && l.Uri != null && l.Uri.Scheme == Uri.UriSchemeHttp).FirstOrDefault();
}
}
public GpxLink EmailLink
{
get
{
return Links.Where(l => l != null && l.Uri != null && l.Uri.Scheme == Uri.UriSchemeMailto).FirstOrDefault();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Anywhere2Go.DataAccess.Object;
using Anywhere2Go.DataAccess;
using Anywhere2Go.Library;
using Anywhere2Go.Business.Master;
using Anywhere2Go.DataAccess.Entity;
namespace Claimdi.WCF.Public
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Intergration" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Intergration.svc or Intergration.svc.cs at the Solution Explorer and start debugging.
public class Intergration : IIntergration
{
public BaseResult<APITasksIntergrationResponse> GetTasks(APITasksIntergrationRequest intergrationRequest)
{
BaseResult<APITasksIntergrationResponse> intergration = new BaseResult<APITasksIntergrationResponse>();
intergration.Result = new APITasksIntergrationResponse();
//intergration.Result.Criteria = DateTime.Now.ToString(Constant.Format.ApiDateFormat);
try
{
var validationResult = DataAnnotation.ValidateEntity<APITasksIntergrationRequest>(intergrationRequest);
if (validationResult.HasError)
{
intergration.StatusCode = Constant.ErrorCode.RequiredData;
intergration.Message = validationResult.HasErrorMessage;
}
else
{
TaskLogic task = new TaskLogic();
PicturePartLogic picturePart = new PicturePartLogic();
if (string.IsNullOrEmpty(intergrationRequest.StartDate))
{
intergrationRequest.StartDate = DateTime.Now.ToString("dd/MM/yyyy");
}
if (string.IsNullOrEmpty(intergrationRequest.EndDate))
{
intergrationRequest.EndDate = DateTime.Now.ToString("dd/MM/yyyy");
}
var getTask = task.getTask(null, new TaskLogicModel.TaskSearchModel
{
TaskProcessId = intergrationRequest.TaskProcessId,
InsurerId = intergrationRequest.InsurerId,
StartDate = intergrationRequest.StartDate,
EndDate = intergrationRequest.EndDate,
size = 999
});
if (getTask.Tasks.Count > 0)
{
intergration.Result.Tasks = new List<APIBaseTaskIntergration>();
foreach (var item in getTask.Tasks)
{
var tempTask = new APIBaseTaskIntergration
{
CarBrandName = (item.CarInfo.carBrand != null ? item.CarInfo.carBrand.carBrandName : ""),
CarModelName = (item.CarInfo.carModel != null ? item.CarInfo.carModel.carModelName : ""),
CarRegis = item.CarInfo.carRegis,
TaskId = item.taskId,
Reference1 = item.Inspection.ispRef1,
Reference2 = item.Inspection.ispRef2
};
//if (item.TaskPicture.Count > 0)
//{
// var PictureParents = item.TaskPicture.Where(t => t.PictureParentId != null && t.PictureParentId != 0).Select(s => s.PictureParentId).ToList();
// tempTask.TaskPictures = new List<APIBasePictureIntergration>();
// foreach (var picture in item.TaskPicture)
// {
// if (!PictureParents.Contains(picture.PictureId))
// {
// var picturePartInfo = picturePart.GetPicturePartByName(picture.PictureName);
// tempTask.TaskPictures.Add(new APIBasePictureIntergration
// {
// DamageLevelCode = picture.DamageLevelCode,
// PictureDamage = (picturePartInfo != null ? new APIDamagePart
// {
// ExcelColumn = picturePartInfo.ExcelColumn,
// PicturePartCode = picturePartInfo.PicturePartCode,
// PicturePartId = picturePartInfo.PicturePartId.ToString(),
// PicturePartName = picturePartInfo.PicturePartName
// } : null),
// PictureDesc = picture.PictureDesc,
// PictureId = picture.PictureId,
// PictureName = picture.PictureName,
// PicturePath = (!string.IsNullOrEmpty(picture.PicturePath) ? Configurator.HostPicture + picture.PicturePath : picture.PicturePath),
// PictureType = (picture.PictureType != null ? new APIPictureType
// {
// pictureType = picture.PictureType.pictureType,
// pictureTypeId = picture.PictureTypeId,
// sort = picture.PictureType.sort
// } : null),
// Sequence = picture.Sequence
// });
// }
// }
//}
intergration.Result.Tasks.Add(tempTask);
}
}
}
}
catch (Exception ex)
{
intergration.StatusCode = Constant.ErrorCode.SystemError;
intergration.Message = Constant.ErrorMessage.SystemError;
intergration.SystemErrorMessage = ex.Message;
}
return intergration;
}
public BaseResult<APITaskPicturesIntergrationResponse> GetTaskPictures(string taskId)
{
BaseResult<APITaskPicturesIntergrationResponse> task = new BaseResult<APITaskPicturesIntergrationResponse>();
task.Result = new APITaskPicturesIntergrationResponse();
try
{
if (string.IsNullOrEmpty(taskId))
{
task.StatusCode = Constant.ErrorCode.RequiredData;
task.Message = "task_id is required";
}
else
{
TaskLogic taskLogic = new TaskLogic();
PicturePartLogic picturePart = new PicturePartLogic();
var taskInfo = taskLogic.GetTaskById(taskId);
if (taskInfo != null && taskInfo.TaskPicture != null)
{
task.Result.TaskPictures = new List<APIBasePictureIntergration>();
var PictureParents = taskInfo.TaskPicture.Where(t => t.PictureParentId != null && t.PictureParentId != 0).Select(s => s.PictureParentId).ToList();
foreach (var item in taskInfo.TaskPicture)
{
if (!PictureParents.Contains(item.PictureId))
{
var picturePartInfo = picturePart.GetPicturePartByName(item.PictureName);
task.Result.TaskPictures.Add(new APIBasePictureIntergration
{
DamageLevelCode = item.DamageLevelCode,
PictureDamage = (picturePartInfo != null ? new APIDamagePart
{
ExcelColumn = (picturePartInfo.ExcelColumn != null ? picturePartInfo.ExcelColumn.Trim() : ""),
PicturePartCode = (picturePartInfo.PicturePartCode != null ? picturePartInfo.PicturePartCode.Trim() : ""),
PicturePartId = picturePartInfo.PicturePartId.ToString(),
PicturePartName = picturePartInfo.PicturePartName
} : null),
PicturePath = (!string.IsNullOrEmpty(item.PicturePath) ? Configurator.HostPicture(taskInfo.IsWinAppDownloadImage.GetValueOrDefault(false)) + item.PicturePath : item.PicturePath),
PictureTypeId = item.PictureType.pictureTypeId,
PictureTypeName = item.PictureType.pictureType
});
}
}
}
}
}
catch (Exception ex)
{
task.StatusCode = Constant.ErrorCode.SystemError;
task.Message = Constant.ErrorMessage.SystemError;
task.SystemErrorMessage = ex.Message;
}
return task;
}
public MTIAPITasksIntergrationResponse MTIGetTasks(MTIAPITasksIntergrationRequest request)
{
MTIAPITasksIntergrationResponse task = new MTIAPITasksIntergrationResponse();
task.Result = new MTIAPIResult();
task.HaveMore = false;
try
{
DateTime? lastedSync = null;
if (!string.IsNullOrEmpty(request.Criteria))
{
try
{
lastedSync = DateTime.Parse(request.Criteria);
}
catch (Exception)
{ }
}
GetInspections(request, task, lastedSync);
}
catch
{
task.Result = new MTIAPIResult
{
Message = "Access denied.",
Success = false
};
task.Policies = null;
}
return task;
}
private List<MTIPictureItem> GetPictures(List<TaskPicture> pictures, string[] PictureTypeId, bool isWinAppDownloadImage)
{
List<MTIPictureItem> result = new List<MTIPictureItem>();
DamageLevelLogic damage = new DamageLevelLogic();
if (pictures.Count > 0)
{
var PictureParents = pictures.Where(t => t.PictureParentId != null && t.PictureParentId != 0).Select(s => s.PictureParentId).ToList();
foreach (var item in pictures)
{
// filter out picture history and match picture type
if (!PictureParents.Contains(item.PictureId) && PictureTypeId.Contains(item.PictureTypeId))
{
string damageDesc = "";
if (item.PictureTypeId == TaskLogic.PictureTypeDamage)
{
var damageLevel = damage.GetDamageLevelById(item.DamageLevelCode);
if (damageLevel != null)
{
damageDesc = " " + damageLevel.DamageLevelDescription;
}
}
result.Add(new MTIPictureItem
{
CreateDate = item.CreateDate.Value.ToString(Constant.Format.ApiDateFormat),
Description = item.PictureName + " " + item.PictureDesc + damageDesc,
Id = item.PictureId,
Location = new MTILocation
{
Latitude = double.Parse(item.Latitude),
Longitude = double.Parse(item.Longitude)
},
PictureLink = new MTIPictureItem.MTIPictureLink
{
Source = (!string.IsNullOrEmpty(item.PicturePath) ? Configurator.HostPicture(isWinAppDownloadImage) + item.PicturePath : item.PicturePath),
Thumb = (!string.IsNullOrEmpty(item.PicturePath) ? Configurator.HostPicture(isWinAppDownloadImage) + item.PicturePath : item.PicturePath)
},
Revision = 0,
Sequence = item.Sequence,
Status = new MTIPictureItem.MTIPictureStatus
{
Id = "A",
Name = "Accept"
},
UpdateDate = item.UpdateDate.Value.ToString(Constant.Format.ApiDateFormat)
});
}
}
}
return result;
}
private List<MTIPictureItem> GetAccessories(List<TaskPicture> pictures, bool isWinAppDownloadImage)
{
return GetPictures(pictures, new string[] { TaskLogic.PictureTypeAccessory, TaskLogic.PictureTypeDocument, TaskLogic.PictureTypeInspectionDocument }, isWinAppDownloadImage);
}
private List<MTIPictureItem> GetParts(List<TaskPicture> pictures, bool isWinAppDownloadImage)
{
return GetPictures(pictures, new string[] { TaskLogic.PictureTypePart }, isWinAppDownloadImage);
}
private List<MTIPictureItem> GetDamages(List<TaskPicture> pictures, bool isWinAppDownloadImage)
{
return GetPictures(pictures, new string[] { TaskLogic.PictureTypeDamage }, isWinAppDownloadImage);
}
private string GetBookLink(List<TaskPicture> pictures, bool isWinAppDownloadImage)
{
string carBook = "เอกสารยืนยันตัวรถ";
var pictureCarBook = pictures.Where(t => t.PictureApprove.HasValue && t.PictureApprove.Value && (t.isActive.HasValue && t.isActive.Value) && t.PictureName.ToLower().Trim() == carBook).FirstOrDefault();
return (pictureCarBook != null ? Configurator.HostPicture(isWinAppDownloadImage) + pictureCarBook.PicturePath : "");
}
public MTIAPITaskIntergrationResponse MTIGetTask(MTIAPITaskIntergrationRequest request)
{
MTIAPITaskIntergrationResponse task = new MTIAPITaskIntergrationResponse();
task.Result = new MTIAPIResult();
try
{
TaskLogic taskLogic = new TaskLogic();
MappingAPILogic mappingLogic = new MappingAPILogic();
var mapping = mappingLogic.GetMappingAPIById(request.Integrate.Key, request.Integrate.Secret);
if (mapping == null)
{
task.Result = new MTIAPIResult
{
Message = "Access denied.",
Success = false
};
task.Policy = null;
}
if (request.Policy == null)
{
task.Result = new MTIAPIResult
{
Message = "Incorrect request.",
Success = false
};
}
else
{
GetInspection(request, task, taskLogic, mapping.MappingAPIINSId);
}
}
catch
{
task.Result = new MTIAPIResult
{
Message = "Access denied.",
Success = false
};
task.Policy = null;
}
return task;
}
private void GetInspections(MTIAPITasksIntergrationRequest request, MTIAPITasksIntergrationResponse task, DateTime? lastedSync)
{
TaskLogic taskLogic = new TaskLogic();
MappingAPILogic mappingLogic = new MappingAPILogic();
SortingCriteria sorting = new SortingCriteria();
sorting.Add(new SortBy { Name = "updateDate", Direction = SortDirection.ASC });
var mapping = mappingLogic.GetMappingAPIById(request.Integrate.Key, request.Integrate.Secret);
if (mapping == null)
{
task.Result = new MTIAPIResult
{
Message = "Access denied.",
Success = false
};
task.Policies = null;
}
else
{
var obj = taskLogic.getTask(null, new TaskLogicModel.TaskSearchModel
{
InsurerId = mapping.MappingAPIINSId,
Criteria = lastedSync,
TaskProcessIds = new int[] { TaskLogic.StatusApproveImage, TaskLogic.StatusPolicyApprove },
size = 100,
TaskTypeId = PolicyTypeIdEnum.INS.ToString()
}, sorting);
int totalTask = obj.Tasks.Count();
task.Criteria = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
if (totalTask > 50)
{
totalTask = 50;
task.HaveMore = true;
task.Criteria = obj.Tasks[50].updateDate.Value.ToString("yyyy-MM-dd HH:mm:ss");
}
task.Policies = new List<MTIAPIPolicyDetail>();
for (int i = 0; i < totalTask; i++)
{
var item = obj.Tasks[i];
var pictures = item.TaskPicture.Where(t => t.isActive != false).ToList();
var pictureSignature = item.TaskPicture.Where(t => t.PictureTypeId == TaskLogic.PictureTypeSignature).OrderByDescending(o => o.CreateDate).FirstOrDefault();
var accessories = GetAccessories(pictures, item.IsWinAppDownloadImage.GetValueOrDefault(false));
var parts = GetParts(pictures, item.IsWinAppDownloadImage.GetValueOrDefault(false));
var damages = GetDamages(pictures, item.IsWinAppDownloadImage.GetValueOrDefault(false));
var ownerName = (string.IsNullOrEmpty(item.Inspection.ispPolicyPerson) ? item.informerName.Split(' ') : item.Inspection.ispPolicyPerson.Split(' '));
task.Policies.Add(new MTIAPIPolicyDetail
{
CreateDate = item.createDate.Value.ToString(Constant.Format.ApiDateFormat),
Creator = (item.assignAcc != null ? new MTICreator
{
AccId = 0,
FirstName = item.assignAcc.first_name,
LastName = item.assignAcc.last_name,
RoleId = item.assignAcc.role_id.Value,
Insurances = (item.Inspection.ispInsurer != null ? new List<MTIInsurance>(){
new MTIInsurance(){
Id = item.Inspection.ispInsurer.InsID,
IsActive = item.Inspection.ispInsurer.isActive,
Name = item.Inspection.ispInsurer.InsName,
Phone = item.Inspection.ispInsurer.InsTel
}
} : null)
} : null),
Id = GetTaskIdForIntergration(item.taskId),
Location = new MTILocation
{
Latitude = double.Parse(item.scheduleLatitude),
Longitude = double.Parse(item.scheduleLongitude)
},
Mile = item.CarInfo.carMile,
Reference1 = (!string.IsNullOrEmpty(item.Inspection.ispRef1) ? item.Inspection.ispRef1 : ""),
Reference2 = (!string.IsNullOrEmpty(item.Inspection.ispRef2) ? item.Inspection.ispRef2 : ""),
SignatureLink = new MTIPictureLink
{
Source = (pictureSignature != null && !string.IsNullOrEmpty(pictureSignature.PicturePath) ? Configurator.HostPicture(item.IsWinAppDownloadImage.GetValueOrDefault(false)) + pictureSignature.PicturePath : "")
},
Status = new MTIStatus
{
Id = item.taskProcessId.ToString(),
Name = item.taskProcess.taskProcessName,
Note = item.note,
Read = false
},
Type = (item.taskTypeId == "INS" ? "inspection" : item.taskTypeId),
UpdateDate = item.updateDate.Value.ToString(Constant.Format.ApiDateFormat),
Insurance = (item.Inspection.ispInsurer != null ? new MTIBaseInsurance
{
Id = item.Inspection.ispInsurer.InsID.ToString(),
Name = item.Inspection.ispInsurer.InsName
} : null),
Car = new MTICar
{
Accessories = accessories,
BookLink = new MTIPictureLink
{
Source = GetBookLink(item.TaskPicture, item.IsWinAppDownloadImage.GetValueOrDefault(false))
},
Brand = (item.CarInfo.carBrand != null ? new MTIMasterItem
{
Id = item.CarInfo.carBrandId,
Name = item.CarInfo.carBrand.carBrandName
} : null),
CarType = (item.CarInfo.carType != null ? new MTIMasterItem
{
Id = item.CarInfo.carTypeID.ToString(),
Name = item.CarInfo.carType.carTypeName
} : null),
Damages = damages,
Id = GetTaskIdForIntergration(item.taskId),
LicenseNo = item.CarInfo.carRegis,
LicenseNoIsCorrect = true,
Model = (item.CarInfo.carModel != null ? new MTIMasterItem
{
Id = item.CarInfo.carModelId,
Name = item.CarInfo.carModel.carModelName
} : null),
NumberOfAccessories = accessories.Count(),
NumberOfDamages = damages.Count(),
NumberOfParts = parts.Count(),
Parts = parts,
Owner = new MTICarOwner
{
FirstName = ownerName[0],
LastName = (ownerName.Count() > 1 ? ownerName[1] : ""),
Mobile = item.Inspection.ispPolicyTel
},
Province = (item.CarInfo.carRegisProvince != null ? new MTIMasterItem
{
Id = item.CarInfo.carRegisProvince.provinceCode,
Name = item.CarInfo.carRegisProvince.provinceName.Trim()
} : null),
Description = (damages.Count > 0 ? damages.Select(t => t.Description).Aggregate((t, j) => t + "|" + j) : "")
}
});
}
task.Result = new MTIAPIResult
{
Success = true
};
}
}
private void GetInspection(MTIAPITaskIntergrationRequest request, MTIAPITaskIntergrationResponse task, TaskLogic taskLogic, string insId)
{
string taskId = "CLM-INS-" + request.Policy.Id.ToString();
var obj = taskLogic.GetTaskById(taskId, insId);
if (obj != null)
{
var item = obj;
var pictures = item.TaskPicture.Where(t => t.isActive != false).ToList();
var pictureSignature = item.TaskPicture.Where(t => t.PictureTypeId == TaskLogic.PictureTypeSignature).OrderByDescending(o => o.CreateDate).FirstOrDefault();
var accessories = GetAccessories(pictures, item.IsWinAppDownloadImage.GetValueOrDefault(false));
var parts = GetParts(pictures, item.IsWinAppDownloadImage.GetValueOrDefault(false));
var damages = GetDamages(pictures, item.IsWinAppDownloadImage.GetValueOrDefault(false));
var ownerName = (string.IsNullOrEmpty(item.Inspection.ispPolicyPerson) ? item.informerName.Split(' ') : item.Inspection.ispPolicyPerson.Split(' '));
task.Policy = new MTIAPIPolicyDetail
{
CreateDate = item.createDate.Value.ToString(Constant.Format.ApiDateFormat),
Creator = new MTICreator
{
AccId = 0,
FirstName = item.assignAcc.first_name,
LastName = item.assignAcc.last_name,
RoleId = item.assignAcc.role_id.Value,
Insurances = (item.Inspection.ispInsurer != null ? new List<MTIInsurance>(){
new MTIInsurance(){
Id = item.Inspection.ispInsurer.InsID,
IsActive = item.Inspection.ispInsurer.isActive,
Name = item.Inspection.ispInsurer.InsName,
Phone = item.Inspection.ispInsurer.InsTel
}
} : null)
},
Id = GetTaskIdForIntergration(item.taskId),
Location = new MTILocation
{
Latitude = double.Parse(item.scheduleLatitude),
Longitude = double.Parse(item.scheduleLongitude)
},
Mile = item.CarInfo.carMile,
AppointAddress = item.schedulePlance,
AppointDateTime = item.scheduleDate.Value.ToString(Constant.Format.ApiDateFormat),
Reference1 = (!string.IsNullOrEmpty(item.Inspection.ispRef1) ? item.Inspection.ispRef1 : ""),
Reference2 = (!string.IsNullOrEmpty(item.Inspection.ispRef2) ? item.Inspection.ispRef2 : ""),
SignatureLink = new MTIPictureLink
{
Source = (pictureSignature != null && !string.IsNullOrEmpty(pictureSignature.PicturePath) ? Configurator.HostPicture(item.IsWinAppDownloadImage.GetValueOrDefault(false)) + pictureSignature.PicturePath : "")
},
Status = new MTIStatus
{
Id = item.taskProcessId.ToString(),
Name = item.taskProcess.taskProcessName,
Note = item.note,
Read = false
},
Type = (item.taskTypeId == "INS" ? "inspection" : item.taskTypeId),
UpdateDate = item.updateDate.Value.ToString(Constant.Format.ApiDateFormat),
Insurance = (item.Inspection.ispInsurer != null ? new MTIBaseInsurance
{
Id = item.Inspection.ispInsurer.InsID.ToString(),
Name = item.Inspection.ispInsurer.InsName
} : null),
Car = new MTICar
{
Accessories = accessories,
BookLink = new MTIPictureLink
{
Source = GetBookLink(item.TaskPicture, item.IsWinAppDownloadImage.GetValueOrDefault(false))
},
Brand = (item.CarInfo.carBrand != null ? new MTIMasterItem
{
Id = item.CarInfo.carBrandId,
Name = item.CarInfo.carBrand.carBrandName
} : null),
CarType = (item.CarInfo.carType != null ? new MTIMasterItem
{
Id = item.CarInfo.carTypeID.ToString(),
Name = item.CarInfo.carType.carTypeName
} : null),
Damages = damages,
Id = GetTaskIdForIntergration(item.taskId),
LicenseNo = item.CarInfo.carRegis,
LicenseNoIsCorrect = true,
Model = (item.CarInfo.carModel != null ? new MTIMasterItem
{
Id = item.CarInfo.carModelId,
Name = item.CarInfo.carModel.carModelName
} : null),
NumberOfAccessories = accessories.Count(),
NumberOfDamages = damages.Count(),
NumberOfParts = parts.Count(),
Parts = parts,
Owner = new MTICarOwner
{
FirstName = ownerName[0],
LastName = (ownerName.Count() > 1 ? ownerName[1] : ""),
Mobile = item.Inspection.ispPolicyTel
},
Province = (item.CarInfo.carRegisProvince != null ? new MTIMasterItem
{
Id = item.CarInfo.carRegisProvince.provinceCode,
Name = item.CarInfo.carRegisProvince.provinceName.Trim()
} : null),
Description = (damages.Count > 0 ? damages.Select(t => t.Description).Aggregate((t, j) => t + "|" + j) : "") + (!string.IsNullOrEmpty(item.OverallDamageInfo) ? "|" + item.OverallDamageInfo : "")
}
};
task.Result = new MTIAPIResult
{
Success = true
};
}
else
{
task.Result = new MTIAPIResult
{
Success = true,
Message = "Policy not found."
};
}
}
private int GetTaskIdForIntergration(string taskId)
{
int startIndex = 8;
int stopIndex = taskId.Length - startIndex;
return Convert.ToInt32(taskId.Substring(startIndex, stopIndex));
}
public BaseResult<APITaskCarInsurerChromeExtensionResponse> GetTaskCarInsurerForChromeExtension(string id)
{
BaseResult<APITaskCarInsurerChromeExtensionResponse> res = new BaseResult<APITaskCarInsurerChromeExtensionResponse>();
try
{
TaskLogic task = new TaskLogic();
if (string.IsNullOrEmpty(id))
{
res.StatusCode = Constant.ErrorCode.ExistingData;
res.Message = Constant.ErrorMessage.ExistingData;
}
else
{
res = task.GetTaskDetailForChromeExtension(id);
}
}
catch (Exception ex)
{
res.StatusCode = Constant.ErrorCode.SystemError;
res.Message = Constant.ErrorMessage.SystemError;
res.SystemErrorMessage = ex.Message;
}
return res;
}
public BaseResult<APITaskCarPartiesChromeExtensionResponse> GetTaskCarPartiesForChromeExtension(string id)
{
BaseResult<APITaskCarPartiesChromeExtensionResponse> res = new BaseResult<APITaskCarPartiesChromeExtensionResponse>();
try
{
TaskLogic task = new TaskLogic();
if (string.IsNullOrEmpty(id))
{
res.StatusCode = Constant.ErrorCode.ExistingData;
res.Message = Constant.ErrorMessage.ExistingData;
}
else
{
res = task.GetTaskCarPartiesForChromeExtension(id);
}
}
catch (Exception ex)
{
res.StatusCode = Constant.ErrorCode.SystemError;
res.Message = Constant.ErrorMessage.SystemError;
res.SystemErrorMessage = ex.Message;
}
return res;
}
public BaseResult<APITaskPropertyDamagesChromeExtensionResponse> GetTaskPropertyDamagesForChromeExtension(string id)
{
BaseResult<APITaskPropertyDamagesChromeExtensionResponse> res = new BaseResult<APITaskPropertyDamagesChromeExtensionResponse>();
try
{
TaskLogic task = new TaskLogic();
if (string.IsNullOrEmpty(id))
{
res.StatusCode = Constant.ErrorCode.ExistingData;
res.Message = Constant.ErrorMessage.ExistingData;
}
else
{
res = task.GetTaskPropertyDamagesForChromeExtension(id);
}
}
catch (Exception ex)
{
res.StatusCode = Constant.ErrorCode.SystemError;
res.Message = Constant.ErrorMessage.SystemError;
res.SystemErrorMessage = ex.Message;
}
return res;
}
public BaseResult<APITaskWoundedsChromeExtensionResponse> GetTaskWoundedsForChromeExtension(string id)
{
BaseResult<APITaskWoundedsChromeExtensionResponse> res = new BaseResult<APITaskWoundedsChromeExtensionResponse>();
try
{
TaskLogic task = new TaskLogic();
if (string.IsNullOrEmpty(id))
{
res.StatusCode = Constant.ErrorCode.ExistingData;
res.Message = Constant.ErrorMessage.ExistingData;
}
else
{
res = task.GetTaskWoundedsForChromeExtension(id);
}
}
catch (Exception ex)
{
res.StatusCode = Constant.ErrorCode.SystemError;
res.Message = Constant.ErrorMessage.SystemError;
res.SystemErrorMessage = ex.Message;
}
return res;
}
public BaseResult<APITaskDetailForWinAppResponse> GetTasksForWinApp(APITasksForWinAppRequest request)
{
BaseResult<APITaskDetailForWinAppResponse> res = new BaseResult<APITaskDetailForWinAppResponse>();
try
{
TaskLogic task = new TaskLogic();
var validationResult = DataAnnotation.ValidateEntity<APITasksForWinAppRequest>(request);
if (validationResult.HasError)
{
res.StatusCode = Constant.ErrorCode.RequiredData;
res.Message = validationResult.HasErrorMessage;
}
else
{
res = task.GetTaskDownloadImageForWinApp(request.StartDate, request.EndDate, request.Limit);
}
}
catch (Exception ex)
{
res.StatusCode = Constant.ErrorCode.SystemError;
res.Message = Constant.ErrorMessage.SystemError;
res.SystemErrorMessage = ex.Message;
}
return res;
}
public BaseResult<bool> SetTaskDownloadSuccess(APITaskDownloadSuccessRequest request)
{
BaseResult<bool> res = new BaseResult<bool>();
try
{
TaskLogic task = new TaskLogic();
var validationResult = DataAnnotation.ValidateEntity<APITaskDownloadSuccessRequest>(request);
if (validationResult.HasError)
{
res.StatusCode = Constant.ErrorCode.RequiredData;
res.Message = validationResult.HasErrorMessage;
}
else
{
res = task.SetTaskDownloadSuccess(request.TaskId);
}
}
catch (Exception ex)
{
res.StatusCode = Constant.ErrorCode.SystemError;
res.Message = Constant.ErrorMessage.SystemError;
res.SystemErrorMessage = ex.Message;
}
return res;
}
public BaseResult<APITaskFullReportForTransferDataToThirdParty> GetTaskFullReportForTransferDataToThirdParty(string id)
{
BaseResult<APITaskFullReportForTransferDataToThirdParty> res = new BaseResult<APITaskFullReportForTransferDataToThirdParty>();
try
{
TaskLogic task = new TaskLogic();
if (string.IsNullOrEmpty(id))
{
res.StatusCode = Constant.ErrorCode.ExistingData;
res.Message = Constant.ErrorMessage.ExistingData;
}
else
{
res = task.GetTaskFullReportForTransferDataToThirdParty(id);
}
}
catch (Exception ex)
{
res.StatusCode = Constant.ErrorCode.SystemError;
res.Message = Constant.ErrorMessage.SystemError;
res.SystemErrorMessage = ex.Message;
}
return res;
}
public BaseResult<APITasksForTransferDataToThirdParty> GetTasksForTransferDataToThirdParty(APITasksForTransferDataToThirdPartyRequest request)
{
BaseResult<APITasksForTransferDataToThirdParty> res = new BaseResult<APITasksForTransferDataToThirdParty>();
try
{
TaskLogic task = new TaskLogic();
var validationResult = DataAnnotation.ValidateEntity<APITasksForTransferDataToThirdPartyRequest>(request);
if (validationResult.HasError)
{
res.StatusCode = Constant.ErrorCode.RequiredData;
res.Message = validationResult.HasErrorMessage;
}
else
{
res = task.GetTasksForTransferDataToThirdParty(request.StartDate, request.EndDate, request.InsurerID);
}
}
catch (Exception ex)
{
res.StatusCode = Constant.ErrorCode.SystemError;
res.Message = Constant.ErrorMessage.SystemError;
res.SystemErrorMessage = ex.Message;
}
return res;
}
public BaseResult<bool> SetTaskTrasnferToThirdPartyResult(APITaskTransferToThirdPartyResultRequest request)
{
BaseResult<bool> res = new BaseResult<bool>();
try
{
TaskLogic task = new TaskLogic();
var validationResult = DataAnnotation.ValidateEntity<APITaskTransferToThirdPartyResultRequest>(request);
if (validationResult.HasError)
{
res.StatusCode = Constant.ErrorCode.RequiredData;
res.Message = validationResult.HasErrorMessage;
}
else
{
res = task.SetTaskTrasnferToThirdPartyResult(request.TaskID, request.Status, request.Description);
}
}
catch (Exception ex)
{
res.StatusCode = Constant.ErrorCode.SystemError;
res.Message = Constant.ErrorMessage.SystemError;
res.SystemErrorMessage = ex.Message;
}
return res;
}
}
}
|
using Backend.Model;
using Backend.Model.Users;
using System.Linq;
namespace Backend.Repository
{
public class MySqlActivePatientCardRepository : IActivePatientCardRepository
{
private readonly MyDbContext _context;
public MySqlActivePatientCardRepository(MyDbContext context)
{
_context = context;
}
public void DeletePatientCard(string patientJmbg)
{
PatientCard patientCard = GetPatientCardByJmbg(patientJmbg);
_context.Remove(patientCard);
_context.SaveChanges();
}
public PatientCard GetPatientCardByJmbg(string jmbg)
{
return _context.PatientCards.Where(patientCard => patientCard.PatientJmbg == jmbg).FirstOrDefault();
}
public void AddPatientCard(PatientCard patientCard)
{
_context.PatientCards.Add(patientCard);
_context.SaveChanges();
}
public void UpdatePatientCard(PatientCard patientCard)
{
_context.PatientCards.Update(patientCard);
_context.SaveChanges();
}
public bool CheckIfPatientCardExists(int patientCardId)
{
if (_context.PatientCards.Find(patientCardId) == null)
return false;
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace FamousQuoteQuiz.Data.EntityContracts
{
public interface IRepository<T1, T2>
where T1 : class
where T2 : class
{
IQueryable<T2> GetAll();
IQueryable<T2> Where(Expression<Func<T1, bool>> predicate);
int Count();
Task<int> CountAsync();
int Count(Expression<Func<T1, bool>> predicate);
Task<int> CountAsync(Expression<Func<T1, bool>> predicate);
bool Any();
Task<bool> AnyAsync();
Task<bool> AnyAsync(Expression<Func<T1, bool>> predicate);
bool Any(Expression<Func<T1, bool>> predicate);
T2 FirstOrDefault();
T2 FirstOrDefault(Expression<Func<T1, bool>> predicate);
Task<T2> FirstOrDefaultAsync();
Task<T2> FirstOrDefaultAsync(Expression<Func<T1, bool>> predicate);
T2 First();
T2 First(Expression<Func<T1, bool>> predicate);
Task<T2> FirstAsync();
Task<T2> FirstAsync(Expression<Func<T1, bool>> predicate);
T2 SingleOrDefault();
T2 SingleOrDefault(Expression<Func<T1, bool>> predicate);
Task<T2> SingleOrDefaultAsync();
Task<T2> SingleOrDefaultAsync(Expression<Func<T1, bool>> predicate);
T2 Single();
T2 Single(Expression<Func<T1, bool>> predicate);
Task<T2> SingleAsync();
Task<T2> SingleAsync(Expression<Func<T1, bool>> predicate);
void Add(T1 entity);
Task AddAsync(T1 entity);
void AddRange(T1[] entity);
Task AddRangeAsync(T1[] entity);
void Remove(int Id);
void Remove(T1 entity);
List<T2> ToList(IQueryable<T1> queryable);
T2[] ToArray(IQueryable<T1> queryable);
Task Update(T2 repositoryModel);
IQueryable<T1> GetDbSet();
void SaveChanges();
Task SaveChangesAsync();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KartSystem
{
public class ParameterReportPrintForm : ParameterDocumentPrintForm
{
public override string FriendlyName
{
get { return "Настроки просмотра отчетов"; }
}
}
}
|
using System;
using Faker.ValueGenerator.PrimitiveTypes;
namespace DataTimeGenerator
{
public class DateTimeGenerator : IPrimitiveTypeGenerator
{
private static readonly Random Random = new Random();
public Type GenerateType {
get => typeof(DateTime);
set
{
}
}
public DateTimeGenerator()
{
GenerateType = typeof(DateTime);
}
public object Generate()
{
int year = Random.Next(DateTime.MinValue.Year, DateTime.MaxValue.Year + 1);
int month = Random.Next(1, 13);
int day = Random.Next(1, DateTime.DaysInMonth(year, month) + 1);
int hour = Random.Next(0, 24);
int minute = Random.Next(0, 60);
int second = Random.Next(0, 60);
int millisecond = Random.Next(0, 1000);
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
}
} |
using System;
using System.ComponentModel.DataAnnotations;
using com.Sconit.Entity.INV;
namespace com.Sconit.Entity.PRD
{
[Serializable]
public partial class ProductLineLocationDetail : EntityBase, IAuditable
{
#region O/R Mapping Properties
//[Display(Name = "Id", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public Int32 Id { get; set; }
[Display(Name = "ProductLineLocationDetail_ProductLine", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string ProductLine { get; set; }
[Display(Name = "ProductLineLocationDetail_ProductLineFacility", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string ProductLineFacility { get; set; }
[Display(Name = "ProductLineLocationDetail_OrderNo", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string OrderNo { get; set; }
//[Display(Name = "OrderDetailId", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public Int32? OrderDetailId { get; set; }
[Display(Name = "ProductLineLocationDetail_Operation", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public Int32? Operation { get; set; }
[Display(Name = "ProductLineLocationDetail_OpReference", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string OpReference { get; set; }
[Display(Name = "ProductLineLocationDetail_TraceCode", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string TraceCode { get; set; }
[Display(Name = "ProductLineLocationDetail_Item", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string Item { get; set; }
[Display(Name = "ProductLineLocationDetail_ItemDescription", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string ItemDescription { get; set; }
[Display(Name = "ProductLineLocationDetail_ReferenceItemCode", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string ReferenceItemCode { get; set; }
[Display(Name = "ProductLineLocationDetail_HuId", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string HuId { get; set; }
[Display(Name = "ProductLineLocationDetail_LotNo", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string LotNo { get; set; }
//[Display(Name = "IsConsignment", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public Boolean IsConsignment { get; set; }
//[Display(Name = "PlanBill", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public Int32? PlanBill { get; set; }
//[Display(Name = "QualityType", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public com.Sconit.CodeMaster.QualityType QualityType { get; set; }
[Display(Name = "ProductLineLocationDetail_Qty", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public Decimal Qty { get; set; }
[Display(Name = "ProductLineLocationDetail_BackFlushQty", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public Decimal BackFlushQty { get; set; }
[Display(Name = "ProductLineLocationDetail_VoidQty", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public Decimal VoidQty { get; set; }
[Display(Name = "ProductLineLocationDetail_IsClose", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public Boolean IsClose { get; set; }
[Display(Name = "ProductLineLocationDetail_LocationFrom", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string LocationFrom { get; set; }
//[Display(Name = "CreateUserId", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public Int32 CreateUserId { get; set; }
[Display(Name = "ProductLineLocationDetail_CreateUserName", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string CreateUserName { get; set; }
[Display(Name = "ProductLineLocationDetail_CreateDate", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public DateTime CreateDate { get; set; }
//[Display(Name = "LastModifyUserId", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public Int32 LastModifyUserId { get; set; }
//[Display(Name = "LastModifyUserName", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public string LastModifyUserName { get; set; }
//[Display(Name = "LastModifyDate", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public DateTime LastModifyDate { get; set; }
//[Display(Name = "Version", ResourceType = typeof(Resources.PRD.ProductLineLocationDetail))]
public Int32 Version { get; set; }
public string ReserveNo { get; set; } //预留号
public string ReserveLine { get; set; } //预留行号
public string AUFNR { get; set; } //SAP生产单号
public string ICHARG { get; set; } //SAP批次号
public string BWART { get; set; } //移动类型
public bool NotReport { get; set; } //不导给SAP
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
ProductLineLocationDetail another = obj as ProductLineLocationDetail;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
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 BoloDeCenoura
{
public partial class Form1 : Form
{
string nome;
string tipo;
int tamanho;
string recheio;
string tipoBiscoito;
public Form1()
{
InitializeComponent();
lblTipoBiscoito.Visible = false;
cbxTipoBiscoito.Visible = false;
cbxRecheio.Visible = false;
lblRecheio.Visible = false;
cbxRecheio.Items.Add("Chocolate");
cbxRecheio.Items.Add("Doce de Leite");
cbxRecheio.Items.Add("Paçoca");
cbxTipoBiscoito.Items.Add("Trakinas");
cbxTipoBiscoito.Items.Add("Passatempo");
cbxTipoBiscoito.Items.Add("Fandangos");
}
private void btnExibir_Click(object sender, EventArgs e)
{
ObterDados();
if (tipo == "Bolo")
{
Bolo b = new Bolo(nome, tamanho, tipo, recheio);
MessageBox.Show("Nome:" + b.Nome + "\nTamanho:" + b.Tamanho + "cm" + "\nTipo:" + b.Tipo + "\nRecheio:" + b.Recheio);
}
else if (tipo == "Torta Alemã")
{
TortaAlema ta = new TortaAlema(nome, tamanho, tipo, tipoBiscoito);
MessageBox.Show("Nome:" + ta.Nome + "\nTamanho:" + ta.Tamanho + "cm" + "\nTipo:" + ta.Tipo + "\nTipo do Biscoito:" + ta.TipoDoBiscoito);
}
}
public void ObterDados() {
nome = tbxNome.Text;
tamanho =Int32.Parse(tbxTamanho.Text);
if (rbtBolo.Checked)
{
tipo = "Bolo";
recheio = cbxRecheio.Text;
}
else if(rbtTA.Checked) {
tipo = "Torta Alemã";
tipoBiscoito = cbxTipoBiscoito.Text;
}
}
private void rbtBolo_CheckedChanged(object sender, EventArgs e)
{
lblTipoBiscoito.Visible = false;
cbxTipoBiscoito.Visible = false;
lblRecheio.Visible = true;
cbxRecheio.Visible = true;
}
private void rbtTA_CheckedChanged(object sender, EventArgs e)
{
lblTipoBiscoito.Visible = true;
cbxTipoBiscoito.Visible = true;
lblRecheio.Visible = false;
cbxRecheio.Visible = false;
}
private void rbtBolo_MouseEnter(object sender, EventArgs e)
{
if (!rbtTA.Checked)
{
lblRecheio.Visible = true;
cbxRecheio.Visible = true;
lblTipoBiscoito.Visible = false;
cbxTipoBiscoito.Visible = false;
}
}
private void rbtTA_MouseEnter(object sender, EventArgs e)
{
if (!rbtBolo.Checked)
{
lblTipoBiscoito.Visible = true;
cbxTipoBiscoito.Visible = true;
lblRecheio.Visible = false;
cbxRecheio.Visible = false;
}
}
private void rbtTA_MouseLeave(object sender, EventArgs e)
{
if (!rbtTA.Checked&&!rbtBolo.Checked)
{
lblTipoBiscoito.Visible = false;
cbxTipoBiscoito.Visible = false;
lblRecheio.Visible = false;
cbxRecheio.Visible = false;
}
}
private void rbtBolo_MouseLeave(object sender, EventArgs e)
{
if (!rbtBolo.Checked&&!rbtTA.Checked)
{
lblRecheio.Visible = false;
cbxRecheio.Visible = false;
lblTipoBiscoito.Visible = false;
cbxTipoBiscoito.Visible = false;
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class ScoreManager : MonoBehaviour {
int score = 0;
int level = 1;
int lives = 3;
void Start() {
//Make sure the object persists
DontDestroyOnLoad (gameObject);
Application.LoadLevel ("Level1");
}
public int GetLevel(){
return level;
}
public void NextLevel(){
level++;
}
public int GetScore(){
return score;
}
public void AddScore( int i) {
score += i;
}
public int GetLives(){
return lives;
}
public void LoseLife()
{
lives--;
if (lives == 0) {
Application.LoadLevel("GameOver");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttackInput : MonoBehaviour {
private CharacterAnimations playerAnimation;
public GameObject attackPoint;
// Use this for initialization
void Awake()
{
playerAnimation = GetComponent<CharacterAnimations>();
}
// Update is called once per frame
void Update()
{
//defend when J pressed
if (Input.GetKeyDown(KeyCode.J))
{
playerAnimation.Defend(true);
}
if (Input.GetKeyUp(KeyCode.J))
{
playerAnimation.Defend(false);
}
//attack when K pressed
if (Input.GetKeyDown(KeyCode.K))
{
if (Random.Range(0, 2) > 0)
{
playerAnimation.Attack_1();
}
else
{
playerAnimation.Attack_2();
}
}
}
void Activate_AttackPoint()
{
attackPoint.SetActive(true);
}
void Deactivate_AttackPoint()
{
if (attackPoint.activeInHierarchy)
{
attackPoint.SetActive(false);
}
}
}
|
using AutoMapper;
using Web.Models;
using Web.Representer;
namespace Web
{
public static class AutoMapper
{
public static IMapper Mapper;
static AutoMapper()
{
Mapper = new Mapper(new MapperConfiguration(cfg =>
{
cfg.CreateMap<RoleRepresenter, Role>().ForMember(roleDataModel => roleDataModel.Users, options => options.MapFrom(roleRepresenter => roleRepresenter.UserRepresenters));
cfg.CreateMap<Role, RoleRepresenter>().ForMember(roleRepresenter => roleRepresenter.UserRepresenters, options => options.MapFrom(roleDataModel => roleDataModel.Users));
cfg.CreateMap<UserRepresenter, User>().ForMember(userDataModel => userDataModel.Roles, options => options.MapFrom(userRepresenter => userRepresenter.RoleRepresenters));
cfg.CreateMap<User, UserRepresenter>().ForMember(userRepresenter => userRepresenter.RoleRepresenters, options => options.MapFrom(userDataModel => userDataModel.Roles));
}));
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
//TODO: Add other using statements here
namespace com.Sconit.Entity.MRP.TRANS
{
public partial class InventoryBalance
{
[Display(Name = "OrderDetail_ItemDescription", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string ItemDescription { get; set; }
public Double ActiveQty
{
get
{
return Qty - MaxStock;
}
}
}
}
|
using System;
using Gtk;
//using System.Drawing;
using System.Collections;
using System.ComponentModel;
//using System.Windows.Forms;
//using System.Data;
using System.Text;
namespace BitwiseOperations
{
class MainClass
{
public static void Main (string[] args)
{
Application.Init ();
MainWindow win = new MainWindow ();
win.Show ();
Application.Run ();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Domain.Data.DataModels;
using Domain.Ef.Repository;
using Microsoft.EntityFrameworkCore;
using Services.Abstractions.Services;
namespace Services.Implementations.Services
{
public class TripService: ITripService
{
private readonly ITripRepository _tripRepository;
public TripService(IUnitOfWork unitOfWork)
{
_tripRepository = unitOfWork.TripRepository;
}
public async Task<ICollection<Trips>> GetAllTripsAsync()
{
return await _tripRepository.GetAllTrips().ToListAsync();
}
}
}
|
using System;
using System.Collections.Generic;
namespace Substrate
{
/// <summary>
/// Provides read-only indexed access to an underlying resource.
/// </summary>
/// <typeparam name="T">The type of the underlying resource.</typeparam>
public interface ICacheTable<T>
{
/// <summary>
/// Gets the value at the given index.
/// </summary>
/// <param name="index">The index to fetch.</param>
T this[int index] { get; }
}
/*internal class CacheTableArray<T> : ICacheTable<T>
{
private T[] _cache;
public T this[int index]
{
get { return _cache[index]; }
}
public CacheTableArray (T[] cache)
{
_cache = cache;
}
}
internal class CacheTableDictionary<T> : ICacheTable<T>
{
private Dictionary<int, T> _cache;
private static Random _rand = new Random();
public T this[int index]
{
get
{
T val;
if (_cache.TryGetValue(index, out val)) {
return val;
}
return default(T);
}
}
public CacheTableDictionary (Dictionary<int, T> cache)
{
_cache = cache;
}
}
/// <summary>
/// Provides read-only indexed access to an underlying resource.
/// </summary>
/// <typeparam name="T">The type of the underlying resource.</typeparam>
public class CacheTable<T>
{
ICacheTable<T> _cache;
/// <summary>
/// Gets the value at the given index.
/// </summary>
/// <param name="index"></param>
public T this[int index]
{
get { return _cache[index]; }
}
internal CacheTable (T[] cache)
{
_cache = new CacheTableArray<T>(cache);
}
internal CacheTable (Dictionary<int, T> cache)
{
_cache = new CacheTableDictionary<T>(cache);
}
}*/
}
|
using System.Collections.Generic;
namespace KioskClient.Domain
{
public class AuditoriumRow
{
public int Number { get; set; }
public List<AuditoriumSeat> Seats { get; set; }
}
} |
using System.Collections.Generic;
using ticketarena.lib.model;
namespace ticketarena.lib.services
{
public interface IVendService
{
IEnumerable<Product> ListProducts();
VendResult Purchase(int productId);
void AddCoin(Coin coin);
IEnumerable<Coin> Coins {get;}
ReturnResult Return();
decimal GetCurrentValue();
IEnumerable<CoinTypes> ListCoinsAccepted();
}
}
|
namespace Atc.OpenApi
{
public class AtcOpenApiAssemblyTypeInitializer
{
// Dummy
}
} |
using System;
using System.Diagnostics;
using System.IO;
using Ionic.Zip;
using Microsoft.Build.Evaluation;
namespace BuildZipper
{
public static class BuildZipper
{
static void Main(string[] args)
{
if (args.Length ==1)
{
addPostBuildEvent(args[0].Trim());
}
else if(args.Length ==3)
{
postBuild(args[0].Trim(), args[1].Trim(), args[2].Trim());
}
else
{
usage();
}
}
private static void postBuild(string targetDir, string targetName, string solutionDir)
{
zip(targetDir, Path.Combine(solutionDir, targetName+ ".zip"),targetName);
}
private static void zip(string dir, string dest, string folderName)
{
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(dir, folderName);
zip.Save(dest);
}
}
private static void addPostBuildEvent(string path)
{
Project project = new Project(path);
project.SetProperty("PostBuildEvent",
string.Format(
@"""{0}"" "" $(TargetDir) "" "" $(TargetName) "" "" $(SolutionDir) """,
Process.GetCurrentProcess().MainModule.FileName));
project.Save();
}
private static void usage()
{
Console.WriteLine("Usage:");
Console.WriteLine("BuildZipper ProjectPath");
Console.WriteLine("Add BuildZipper to the post build event, it will archive the build result to the solution root folder.");
}
}
}
|
using System;
using UnityEngine;
public class PlatformerCharacter2D : MonoBehaviour
{
[SerializeField] private float m_MaxSpeed = 10f;
[SerializeField] private LayerMask m_WhatIsGround; // A mask determining what is ground to the character
private Rigidbody2D m_Rigidbody2D;
public bool m_FacingRight = true; // For determining which way the player is currently facing.
private void Awake()
{
m_Rigidbody2D = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
// m_Grounded = false;
// Set the vertical animation
//m_Anim.SetFloat("vSpeed", m_Rigidbody2D.velocity.y);
}
public void Move(float move)
{
// The Speed animator parameter is set to the absolute value of the horizontal input.
// m_Anim.SetFloat("Speed", Mathf.Abs(move));
// Move the character
m_Rigidbody2D.velocity = new Vector2(move*m_MaxSpeed, m_Rigidbody2D.velocity.y);
// If the input is moving the player right and the player is facing left...
if (move > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (move < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
}
private void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
|
using System;
using System.Reflection;
namespace Mesco.Base
{
internal static class PropertyInfoExtensions
{
internal static object TryGetValue(this PropertyInfo property, object element)
{
object value;
try
{
value = property.GetValue(element);
}
catch (Exception ex)
{
value = $"{{{ex.Message}}}";
}
return value;
}
}
}
|
using System.Xml.Serialization;
using Witsml.Data.Curves;
namespace Witsml.Data
{
public class WitsmlIndex
{
[XmlAttribute("uom")]
public string Uom { get; set; } = "";
[XmlText]
public string Value { get; set; } = "";
public WitsmlIndex() { }
public WitsmlIndex(DepthIndex depthIndex)
{
Uom = depthIndex.Uom.ToString();
Value = depthIndex.GetValueAsString();
}
public WitsmlIndex(string value)
{
Value = value;
}
public override string ToString()
{
return $"{Value}{Uom}";
}
}
}
|
namespace Igorious.StardewValley.DynamicApi2.Utils
{
public interface IConstructor<out TClass>
{
TClass Invoke();
}
public interface IConstructor<in TArg, out TClass>
{
TClass Invoke(TArg arg);
}
public interface IConstructor<in TArg1, in TArg2, out TClass>
{
TClass Invoke(TArg1 arg1, TArg2 arg2);
}
} |
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using static ProgressQuest.GameStrings;
using static ProgressQuest.GameManager;
namespace ProgressQuest.Models
{
public class Player : INotifyPropertyChanged
{
private string name { get; set; }
public string Name { get { return name; } set {
if (!string.IsNullOrWhiteSpace(value) && name != value) { name = value; NotifyPropertyChanged(); } } }
public Dictionary<string, PlayerStat> Stats;
private BigInteger hp { get; set; }
public BigInteger HP
{
get { return hp; }
set { if (value != hp) { hp = Math.Max(0, (int)value); NotifyPropertyChanged("HPLabel"); NotifyPropertyChanged("HPPercent"); } }
}
private BigInteger maxHP { get; set; }
public BigInteger MaxHP
{
get { return maxHP; }
set { if (value != maxHP) { maxHP = value; NotifyPropertyChanged("HPLabel"); NotifyPropertyChanged("HPPercent"); } }
}
public int HPPercent { get { if (maxHP == 0) return 0; return (int)(hp * 100 / maxHP); } }
public string HPLabel { get { return HP + " / " + MaxHP; } }
private BigInteger cash { get; set; }
public BigInteger Cash { get { return cash; } set { if (cash != value) { cash = value; NotifyPropertyChanged(); } } }
private BigInteger dmgMin { get; set; }
public BigInteger DmgMin { get { return dmgMin; } set { if (dmgMin != value) { dmgMin = value; NotifyPropertyChanged(); } } }
private BigInteger dmgMax { get; set; }
public BigInteger DmgMax { get { return dmgMax; } set { if (dmgMax != value) { dmgMax = value; NotifyPropertyChanged(); } } }
public BindingList<LootItem> Inventory { get; set; }
public BindingList<ArmorItem> Equipment { get; set; }
private int lastEquipped;
public int LastEquipped { get { return lastEquipped; } set { if (lastEquipped != value) { lastEquipped = value; NotifyPropertyChanged(); } } }
public Player()
{
var input = Interaction.InputBox("Enter your name", "New game");
Name = string.IsNullOrWhiteSpace(input) ? "a noob" : input;
Inventory = new BindingList<LootItem>();
Equipment = new BindingList<ArmorItem>();
DmgMin = 1;
DmgMax = 1;
foreach (PLAYER_ARMOR_SLOT slot in Enum.GetValues(typeof(PLAYER_ARMOR_SLOT)))
{
Equipment.Add(new ArmorItem { Name = "empty", Value = 0, Slot = slot });
}
Stats = new Dictionary<string, PlayerStat>();
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
namespace Core
{
public class Client : ClientBase
{
public string SecondName { get; }
public string ClientPhone2 { get; }
public string ClientAddress { get; }
public string ClientEmail { get; }
public string ClientNote { get; }
public bool ClientIsRegular { get; }
public double ClientBalance { get; }
public string FullName { get => LastName + " " + FirstName + " " + SecondName;}
#region конструкторы
public Client(int id, string last_name, string first_name, string second_name, string phone1, string phone2, string address, string email, string note, bool regular, double balance)
:base(id, last_name, first_name, phone1)
{
SecondName = second_name;
ClientPhone2 = phone2;
ClientAddress = address;
ClientEmail = email;
ClientNote = note;
ClientIsRegular = regular;
ClientBalance = balance;
}
public Client(int id, string last_name, string first_name, string phone1):base(id, last_name, first_name, phone1){}
public Client(ClientBase clientBase, string second_name, string phone2, string address, string email, string note, bool regular, double balance)
:base(clientBase.ClientID, clientBase.LastName, clientBase.FirstName, clientBase.Phone)
{
SecondName = second_name;
ClientPhone2 = phone2;
ClientAddress = address;
ClientEmail = email;
ClientNote = note;
ClientIsRegular = regular;
ClientBalance = balance;
}
#endregion
}
}
|
using ServiceCenter.ViewModel.Storage;
using System.Windows.Controls;
using System.Windows.Input;
namespace ServiceCenter.View.Storage
{
public partial class PageSelectComponent : Page
{
public PageSelectComponent()
{
InitializeComponent();
}
private void tbSearch_KeyUp(object sender, KeyEventArgs e)
{
if (DataContext != null)
{
var context = (PageSelectComponentViewModel)DataContext;
if (e.Key == Key.Enter)
{
context.SearchComponentCommand.Execute(new object());
}
}
}
private void btnClear_Click(object sender, System.Windows.RoutedEventArgs e)
{
if (DataContext != null)
{
var context = (PageSelectComponentViewModel)DataContext;
context.SearchField = string.Empty;
context.ComponentList.Clear();
}
}
private void btnCancel_Click(object sender, System.Windows.RoutedEventArgs e)
{
if (NavigationService.CanGoBack) NavigationService.GoBack();
}
private void gridComponent_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (DataContext != null)
{
var context = (PageSelectComponentViewModel)DataContext;
context.DataGridClick();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class VIdeoScreen : MonoBehaviour
{
public UnityEngine.Video.VideoPlayer videoPlayer;
public RawImage rawImage;
public Button button;
private void Start()
{
videoPlayer.loopPointReached += EndReached;
}
// Start is called before the first frame update
public void VideoPlay()
{
print("Corrotine Appear");
StartCoroutine(PlayVideo());
button.gameObject.SetActive(false);
}
public void VideoPause()
{
videoPlayer.Stop();
button.gameObject.SetActive(true);
}
IEnumerator PlayVideo()
{
print("Corrotine Started");
videoPlayer.Prepare();
WaitForSeconds waitForSeconds = new WaitForSeconds(1f);
while(!videoPlayer.isPrepared)
{
yield return waitForSeconds;
break;
}
rawImage.texture = videoPlayer.texture;
videoPlayer.Play();
print("Corrotine Done");
}
void EndReached(UnityEngine.Video.VideoPlayer vp)
{
print("Acabou");
VideoPause();
}
}
|
using UnityEngine;
using Assets.Code.Items;
using Assets.Code.Actors;
public class attackTest : MonoBehaviour
{
KeyCode sb = KeyCode.Space;
Weapon wp = new Weapon();
BoxCollider enemyCollider;
GameObject player;
GameObject[] enemies;
bool enemyInRange;
Enemy target;
void Awake()
{
// TODO: How to initialize new weapon? Active weapon if more than 1?
wp.Name = "Shitty sword";
wp.Damage = 10;
wp.Range = 12.1f;
// TODO: Is there better way to do this? Direction?
// TODO: Also, case for multiple enemies?
enemies = GameObject.FindGameObjectsWithTag("Enemy");
player = GameObject.FindGameObjectWithTag("Player");
//enemy = GameObject.FindGameObjectWithTag ("Enemy");
BoxCollider b = player.GetComponent<BoxCollider>();
// weapon range
if (b != null)
{
b.size = new Vector3(wp.Range, 2.0f, wp.Range);
}
Debug.Log(player); // PlayerTest, ok!
}
// Use this for initialization
void Start()
{
}
static int i = 0;
// Set states if in range
void OnTriggerEnter(Collider other)
{
Debug.Log("OnTriggerEnter: " + i++);
foreach (GameObject en in enemies)
{
var tmp = other.gameObject.GetComponentsInParent<Enemy>();
//Debug.Log (en); EnemyTest, EnemyTest (1)
if (other.gameObject == en)
{
Debug.Log(other.gameObject);
enemyInRange = true;
//target = other.gameObject;
target = Enemy.ToEnemy(en);
}
}
}
void OnTriggerExit(Collider other)
{
foreach (GameObject en in enemies)
{
if (other.gameObject == en)
{
enemyInRange = false;
target = null;
}
}
}
// Update is called once per frame
void Update()
{
// If pressed Spacebar (Attack input key)
if (Input.GetKeyDown(sb))
{
//Debug.Log ("hit pressed");
// class Weapon Attack() method
// wp.Attack(enemyInRange, target);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace Terminal.Gui {
/// <summary>
/// Provides a platform-independent API for managing ANSI escape sequence codes.
/// </summary>
public static class EscSeqUtils {
/// <summary>
/// Represents the escape key.
/// </summary>
public static readonly char KeyEsc = (char)Key.Esc;
/// <summary>
/// Represents the CSI (Control Sequence Introducer).
/// </summary>
public static readonly string KeyCSI = $"{KeyEsc}[";
/// <summary>
/// Represents the CSI for enable any mouse event tracking.
/// </summary>
public static readonly string CSI_EnableAnyEventMouse = KeyCSI + "?1003h";
/// <summary>
/// Represents the CSI for enable SGR (Select Graphic Rendition).
/// </summary>
public static readonly string CSI_EnableSgrExtModeMouse = KeyCSI + "?1006h";
/// <summary>
/// Represents the CSI for enable URXVT (Unicode Extended Virtual Terminal).
/// </summary>
public static readonly string CSI_EnableUrxvtExtModeMouse = KeyCSI + "?1015h";
/// <summary>
/// Represents the CSI for disable any mouse event tracking.
/// </summary>
public static readonly string CSI_DisableAnyEventMouse = KeyCSI + "?1003l";
/// <summary>
/// Represents the CSI for disable SGR (Select Graphic Rendition).
/// </summary>
public static readonly string CSI_DisableSgrExtModeMouse = KeyCSI + "?1006l";
/// <summary>
/// Represents the CSI for disable URXVT (Unicode Extended Virtual Terminal).
/// </summary>
public static readonly string CSI_DisableUrxvtExtModeMouse = KeyCSI + "?1015l";
/// <summary>
/// Control sequence for enable mouse events.
/// </summary>
public static string EnableMouseEvents { get; set; } =
CSI_EnableAnyEventMouse + CSI_EnableUrxvtExtModeMouse + CSI_EnableSgrExtModeMouse;
/// <summary>
/// Control sequence for disable mouse events.
/// </summary>
public static string DisableMouseEvents { get; set; } =
CSI_DisableAnyEventMouse + CSI_DisableUrxvtExtModeMouse + CSI_DisableSgrExtModeMouse;
/// <summary>
/// Ensures a console key is mapped to one that works correctly with ANSI escape sequences.
/// </summary>
/// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
/// <returns>The <see cref="ConsoleKeyInfo"/> modified.</returns>
public static ConsoleKeyInfo GetConsoleInputKey (ConsoleKeyInfo consoleKeyInfo)
{
ConsoleKeyInfo newConsoleKeyInfo = consoleKeyInfo;
ConsoleKey key;
var keyChar = consoleKeyInfo.KeyChar;
switch ((uint)keyChar) {
case 0:
if (consoleKeyInfo.Key == (ConsoleKey)64) { // Ctrl+Space in Windows.
newConsoleKeyInfo = new ConsoleKeyInfo (' ', ConsoleKey.Spacebar,
(consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
(consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
(consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
}
break;
case uint n when (n >= '\u0001' && n <= '\u001a'):
if (consoleKeyInfo.Key == 0 && consoleKeyInfo.KeyChar == '\r') {
key = ConsoleKey.Enter;
newConsoleKeyInfo = new ConsoleKeyInfo (consoleKeyInfo.KeyChar,
key,
(consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
(consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
(consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
} else if (consoleKeyInfo.Key == 0) {
key = (ConsoleKey)(char)(consoleKeyInfo.KeyChar + (uint)ConsoleKey.A - 1);
newConsoleKeyInfo = new ConsoleKeyInfo ((char)key,
key,
(consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
(consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
true);
}
break;
case 127:
newConsoleKeyInfo = new ConsoleKeyInfo (consoleKeyInfo.KeyChar, ConsoleKey.Backspace,
(consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
(consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
(consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
break;
default:
newConsoleKeyInfo = consoleKeyInfo;
break;
}
return newConsoleKeyInfo;
}
/// <summary>
/// A helper to resize the <see cref="ConsoleKeyInfo"/> as needed.
/// </summary>
/// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
/// <param name="cki">The <see cref="ConsoleKeyInfo"/> array to resize.</param>
/// <returns>The <see cref="ConsoleKeyInfo"/> resized.</returns>
public static ConsoleKeyInfo [] ResizeArray (ConsoleKeyInfo consoleKeyInfo, ConsoleKeyInfo [] cki)
{
Array.Resize (ref cki, cki == null ? 1 : cki.Length + 1);
cki [cki.Length - 1] = consoleKeyInfo;
return cki;
}
/// <summary>
/// Decodes a escape sequence to been processed in the appropriate manner.
/// </summary>
/// <param name="escSeqReqProc">The <see cref="EscSeqReqProc"/> which may contain a request.</param>
/// <param name="newConsoleKeyInfo">The <see cref="ConsoleKeyInfo"/> which may changes.</param>
/// <param name="key">The <see cref="ConsoleKey"/> which may changes.</param>
/// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
/// <param name="mod">The <see cref="ConsoleModifiers"/> which may changes.</param>
/// <param name="c1Control">The control returned by the <see cref="GetC1ControlChar(char)"/> method.</param>
/// <param name="code">The code returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
/// <param name="values">The values returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
/// <param name="terminating">The terminating returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
/// <param name="isKeyMouse">Indicates if the escape sequence is a mouse key.</param>
/// <param name="buttonState">The <see cref="MouseFlags"/> button state.</param>
/// <param name="pos">The <see cref="MouseFlags"/> position.</param>
/// <param name="isReq">Indicates if the escape sequence is a response to a request.</param>
/// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
public static void DecodeEscSeq (EscSeqReqProc escSeqReqProc, ref ConsoleKeyInfo newConsoleKeyInfo, ref ConsoleKey key, ConsoleKeyInfo [] cki, ref ConsoleModifiers mod, out string c1Control, out string code, out string [] values, out string terminating, out bool isKeyMouse, out List<MouseFlags> buttonState, out Point pos, out bool isReq, Action<MouseFlags, Point> continuousButtonPressedHandler)
{
char [] kChars = GetKeyCharArray (cki);
(c1Control, code, values, terminating) = GetEscapeResult (kChars);
isKeyMouse = false;
buttonState = new List<MouseFlags> () { 0 };
pos = default;
isReq = false;
switch (c1Control) {
case "ESC":
if (values == null && string.IsNullOrEmpty (terminating)) {
key = ConsoleKey.Escape;
newConsoleKeyInfo = new ConsoleKeyInfo (cki [0].KeyChar, key,
(mod & ConsoleModifiers.Shift) != 0,
(mod & ConsoleModifiers.Alt) != 0,
(mod & ConsoleModifiers.Control) != 0);
} else if ((uint)cki [1].KeyChar >= 1 && (uint)cki [1].KeyChar <= 26) {
key = (ConsoleKey)(char)(cki [1].KeyChar + (uint)ConsoleKey.A - 1);
newConsoleKeyInfo = new ConsoleKeyInfo (cki [1].KeyChar,
key,
false,
true,
true);
} else {
if (cki [1].KeyChar >= 97 && cki [1].KeyChar <= 122) {
key = (ConsoleKey)cki [1].KeyChar.ToString ().ToUpper () [0];
} else {
key = (ConsoleKey)cki [1].KeyChar;
}
newConsoleKeyInfo = new ConsoleKeyInfo ((char)key,
(ConsoleKey)Math.Min ((uint)key, 255),
false,
true,
false);
}
break;
case "SS3":
key = GetConsoleKey (terminating [0], values [0], ref mod);
newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
key,
(mod & ConsoleModifiers.Shift) != 0,
(mod & ConsoleModifiers.Alt) != 0,
(mod & ConsoleModifiers.Control) != 0);
break;
case "CSI":
if (!string.IsNullOrEmpty (code) && code == "<") {
GetMouse (cki, out buttonState, out pos, continuousButtonPressedHandler);
isKeyMouse = true;
return;
} else if (escSeqReqProc != null && escSeqReqProc.Requested (terminating)) {
isReq = true;
escSeqReqProc.Remove (terminating);
return;
}
key = GetConsoleKey (terminating [0], values [0], ref mod);
if (key != 0 && values.Length > 1) {
mod |= GetConsoleModifiers (values [1]);
}
newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
key,
(mod & ConsoleModifiers.Shift) != 0,
(mod & ConsoleModifiers.Alt) != 0,
(mod & ConsoleModifiers.Control) != 0);
break;
}
}
/// <summary>
/// Gets all the needed information about a escape sequence.
/// </summary>
/// <param name="kChar">The array with all chars.</param>
/// <returns>
/// The c1Control returned by <see cref="GetC1ControlChar(char)"/>, code, values and terminating.
/// </returns>
public static (string c1Control, string code, string [] values, string terminating) GetEscapeResult (char [] kChar)
{
if (kChar == null || kChar.Length == 0) {
return (null, null, null, null);
}
if (kChar [0] != '\x1b') {
throw new InvalidOperationException ("Invalid escape character!");
}
if (kChar.Length == 1) {
return ("ESC", null, null, null);
}
if (kChar.Length == 2) {
return ("ESC", null, null, kChar [1].ToString ());
}
string c1Control = GetC1ControlChar (kChar [1]);
string code = null;
int nSep = kChar.Count (x => x == ';') + 1;
string [] values = new string [nSep];
int valueIdx = 0;
string terminating = "";
for (int i = 2; i < kChar.Length; i++) {
var c = kChar [i];
if (char.IsDigit (c)) {
values [valueIdx] += c.ToString ();
} else if (c == ';') {
valueIdx++;
} else if (valueIdx == nSep - 1 || i == kChar.Length - 1) {
terminating += c.ToString ();
} else {
code += c.ToString ();
}
}
return (c1Control, code, values, terminating);
}
/// <summary>
/// Gets the c1Control used in the called escape sequence.
/// </summary>
/// <param name="c">The char used.</param>
/// <returns>The c1Control.</returns>
public static string GetC1ControlChar (char c)
{
// These control characters are used in the vtXXX emulation.
switch (c) {
case 'D':
return "IND"; // Index
case 'E':
return "NEL"; // Next Line
case 'H':
return "HTS"; // Tab Set
case 'M':
return "RI"; // Reverse Index
case 'N':
return "SS2"; // Single Shift Select of G2 Character Set: affects next character only
case 'O':
return "SS3"; // Single Shift Select of G3 Character Set: affects next character only
case 'P':
return "DCS"; // Device Control String
case 'V':
return "SPA"; // Start of Guarded Area
case 'W':
return "EPA"; // End of Guarded Area
case 'X':
return "SOS"; // Start of String
case 'Z':
return "DECID"; // Return Terminal ID Obsolete form of CSI c (DA)
case '[':
return "CSI"; // Control Sequence Introducer
case '\\':
return "ST"; // String Terminator
case ']':
return "OSC"; // Operating System Command
case '^':
return "PM"; // Privacy Message
case '_':
return "APC"; // Application Program Command
default:
return ""; // Not supported
}
}
/// <summary>
/// Gets the <see cref="ConsoleModifiers"/> from the value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The <see cref="ConsoleModifiers"/> or zero.</returns>
public static ConsoleModifiers GetConsoleModifiers (string value)
{
switch (value) {
case "2":
return ConsoleModifiers.Shift;
case "3":
return ConsoleModifiers.Alt;
case "4":
return ConsoleModifiers.Shift | ConsoleModifiers.Alt;
case "5":
return ConsoleModifiers.Control;
case "6":
return ConsoleModifiers.Shift | ConsoleModifiers.Control;
case "7":
return ConsoleModifiers.Alt | ConsoleModifiers.Control;
case "8":
return ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control;
default:
return 0;
}
}
/// <summary>
/// Gets the <see cref="ConsoleKey"/> depending on terminating and value.
/// </summary>
/// <param name="terminating">The terminating.</param>
/// <param name="value">The value.</param>
/// <param name="mod">The <see cref="ConsoleModifiers"/> which may changes.</param>
/// <returns>The <see cref="ConsoleKey"/> and probably the <see cref="ConsoleModifiers"/>.</returns>
public static ConsoleKey GetConsoleKey (char terminating, string value, ref ConsoleModifiers mod)
{
ConsoleKey key;
switch (terminating) {
case 'A':
key = ConsoleKey.UpArrow;
break;
case 'B':
key = ConsoleKey.DownArrow;
break;
case 'C':
key = ConsoleKey.RightArrow;
break;
case 'D':
key = ConsoleKey.LeftArrow;
break;
case 'F':
key = ConsoleKey.End;
break;
case 'H':
key = ConsoleKey.Home;
break;
case 'P':
key = ConsoleKey.F1;
break;
case 'Q':
key = ConsoleKey.F2;
break;
case 'R':
key = ConsoleKey.F3;
break;
case 'S':
key = ConsoleKey.F4;
break;
case 'Z':
key = ConsoleKey.Tab;
mod |= ConsoleModifiers.Shift;
break;
case '~':
switch (value) {
case "2":
key = ConsoleKey.Insert;
break;
case "3":
key = ConsoleKey.Delete;
break;
case "5":
key = ConsoleKey.PageUp;
break;
case "6":
key = ConsoleKey.PageDown;
break;
case "15":
key = ConsoleKey.F5;
break;
case "17":
key = ConsoleKey.F6;
break;
case "18":
key = ConsoleKey.F7;
break;
case "19":
key = ConsoleKey.F8;
break;
case "20":
key = ConsoleKey.F9;
break;
case "21":
key = ConsoleKey.F10;
break;
case "23":
key = ConsoleKey.F11;
break;
case "24":
key = ConsoleKey.F12;
break;
default:
key = 0;
break;
}
break;
default:
key = 0;
break;
}
return key;
}
/// <summary>
/// A helper to get only the <see cref="ConsoleKeyInfo.KeyChar"/> from the <see cref="ConsoleKeyInfo"/> array.
/// </summary>
/// <param name="cki"></param>
/// <returns>The char array of the escape sequence.</returns>
public static char [] GetKeyCharArray (ConsoleKeyInfo [] cki)
{
if (cki == null) {
return null;
}
char [] kChar = new char [] { };
var length = 0;
foreach (var kc in cki) {
length++;
Array.Resize (ref kChar, length);
kChar [length - 1] = kc.KeyChar;
}
return kChar;
}
private static MouseFlags? lastMouseButtonPressed;
//private static MouseFlags? lastMouseButtonReleased;
private static bool isButtonPressed;
//private static bool isButtonReleased;
private static bool isButtonClicked;
private static bool isButtonDoubleClicked;
private static bool isButtonTripleClicked;
private static Point point;
/// <summary>
/// Gets the <see cref="MouseFlags"/> mouse button flags and the position.
/// </summary>
/// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
/// <param name="mouseFlags">The mouse button flags.</param>
/// <param name="pos">The mouse position.</param>
/// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
public static void GetMouse (ConsoleKeyInfo [] cki, out List<MouseFlags> mouseFlags, out Point pos, Action<MouseFlags, Point> continuousButtonPressedHandler)
{
MouseFlags buttonState = 0;
pos = new Point ();
int buttonCode = 0;
bool foundButtonCode = false;
int foundPoint = 0;
string value = "";
var kChar = GetKeyCharArray (cki);
//System.Diagnostics.Debug.WriteLine ($"kChar: {new string (kChar)}");
for (int i = 0; i < kChar.Length; i++) {
var c = kChar [i];
if (c == '<') {
foundButtonCode = true;
} else if (foundButtonCode && c != ';') {
value += c.ToString ();
} else if (c == ';') {
if (foundButtonCode) {
foundButtonCode = false;
buttonCode = int.Parse (value);
}
if (foundPoint == 1) {
pos.X = int.Parse (value) - 1;
}
value = "";
foundPoint++;
} else if (foundPoint > 0 && c != 'm' && c != 'M') {
value += c.ToString ();
} else if (c == 'm' || c == 'M') {
//pos.Y = int.Parse (value) + Console.WindowTop - 1;
pos.Y = int.Parse (value) - 1;
switch (buttonCode) {
case 0:
case 8:
case 16:
case 24:
case 32:
case 36:
case 40:
case 48:
case 56:
buttonState = c == 'M' ? MouseFlags.Button1Pressed
: MouseFlags.Button1Released;
break;
case 1:
case 9:
case 17:
case 25:
case 33:
case 37:
case 41:
case 45:
case 49:
case 53:
case 57:
case 61:
buttonState = c == 'M' ? MouseFlags.Button2Pressed
: MouseFlags.Button2Released;
break;
case 2:
case 10:
case 14:
case 18:
case 22:
case 26:
case 30:
case 34:
case 42:
case 46:
case 50:
case 54:
case 58:
case 62:
buttonState = c == 'M' ? MouseFlags.Button3Pressed
: MouseFlags.Button3Released;
break;
case 35:
//// Needed for Windows OS
//if (isButtonPressed && c == 'm'
// && (lastMouseEvent.ButtonState == MouseFlags.Button1Pressed
// || lastMouseEvent.ButtonState == MouseFlags.Button2Pressed
// || lastMouseEvent.ButtonState == MouseFlags.Button3Pressed)) {
// switch (lastMouseEvent.ButtonState) {
// case MouseFlags.Button1Pressed:
// buttonState = MouseFlags.Button1Released;
// break;
// case MouseFlags.Button2Pressed:
// buttonState = MouseFlags.Button2Released;
// break;
// case MouseFlags.Button3Pressed:
// buttonState = MouseFlags.Button3Released;
// break;
// }
//} else {
// buttonState = MouseFlags.ReportMousePosition;
//}
//break;
case 39:
case 43:
case 47:
case 51:
case 55:
case 59:
case 63:
buttonState = MouseFlags.ReportMousePosition;
break;
case 64:
buttonState = MouseFlags.WheeledUp;
break;
case 65:
buttonState = MouseFlags.WheeledDown;
break;
case 68:
case 72:
case 80:
buttonState = MouseFlags.WheeledLeft; // Shift/Ctrl+WheeledUp
break;
case 69:
case 73:
case 81:
buttonState = MouseFlags.WheeledRight; // Shift/Ctrl+WheeledDown
break;
}
// Modifiers.
switch (buttonCode) {
case 8:
case 9:
case 10:
case 43:
buttonState |= MouseFlags.ButtonAlt;
break;
case 14:
case 47:
buttonState |= MouseFlags.ButtonAlt | MouseFlags.ButtonShift;
break;
case 16:
case 17:
case 18:
case 51:
buttonState |= MouseFlags.ButtonCtrl;
break;
case 22:
case 55:
buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonShift;
break;
case 24:
case 25:
case 26:
case 59:
buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonAlt;
break;
case 30:
case 63:
buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonShift | MouseFlags.ButtonAlt;
break;
case 32:
case 33:
case 34:
buttonState |= MouseFlags.ReportMousePosition;
break;
case 36:
case 37:
buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonShift;
break;
case 39:
case 68:
case 69:
buttonState |= MouseFlags.ButtonShift;
break;
case 40:
case 41:
case 42:
buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonAlt;
break;
case 45:
case 46:
buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonAlt | MouseFlags.ButtonShift;
break;
case 48:
case 49:
case 50:
buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl;
break;
case 53:
case 54:
buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonShift;
break;
case 56:
case 57:
case 58:
buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonAlt;
break;
case 61:
case 62:
buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonShift | MouseFlags.ButtonAlt;
break;
}
}
}
mouseFlags = new List<MouseFlags> () { MouseFlags.AllEvents };
if (lastMouseButtonPressed != null && !isButtonPressed && !buttonState.HasFlag (MouseFlags.ReportMousePosition)
&& !buttonState.HasFlag (MouseFlags.Button1Released)
&& !buttonState.HasFlag (MouseFlags.Button2Released)
&& !buttonState.HasFlag (MouseFlags.Button3Released)
&& !buttonState.HasFlag (MouseFlags.Button4Released)) {
lastMouseButtonPressed = null;
isButtonPressed = false;
}
if (!isButtonClicked && !isButtonDoubleClicked && ((buttonState == MouseFlags.Button1Pressed || buttonState == MouseFlags.Button2Pressed ||
buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed) && lastMouseButtonPressed == null) ||
isButtonPressed && lastMouseButtonPressed != null && buttonState.HasFlag (MouseFlags.ReportMousePosition)) {
mouseFlags [0] = buttonState;
lastMouseButtonPressed = buttonState;
isButtonPressed = true;
if ((mouseFlags [0] & MouseFlags.ReportMousePosition) == 0) {
point = new Point () {
X = pos.X,
Y = pos.Y
};
Application.MainLoop.AddIdle (() => {
Task.Run (async () => await ProcessContinuousButtonPressedAsync (buttonState, continuousButtonPressedHandler));
return false;
});
} else if (mouseFlags [0] == MouseFlags.ReportMousePosition) {
isButtonPressed = false;
}
} else if (isButtonDoubleClicked && (buttonState == MouseFlags.Button1Pressed || buttonState == MouseFlags.Button2Pressed ||
buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed)) {
mouseFlags [0] = GetButtonTripleClicked (buttonState);
isButtonDoubleClicked = false;
isButtonTripleClicked = true;
} else if (isButtonClicked && (buttonState == MouseFlags.Button1Pressed || buttonState == MouseFlags.Button2Pressed ||
buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed)) {
mouseFlags [0] = GetButtonDoubleClicked (buttonState);
isButtonClicked = false;
isButtonDoubleClicked = true;
Application.MainLoop.AddIdle (() => {
Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
return false;
});
}
//else if (isButtonReleased && !isButtonClicked && buttonState == MouseFlags.ReportMousePosition) {
// mouseFlag [0] = GetButtonClicked ((MouseFlags)lastMouseButtonReleased);
// lastMouseButtonReleased = null;
// isButtonReleased = false;
// isButtonClicked = true;
// Application.MainLoop.AddIdle (() => {
// Task.Run (async () => await ProcessButtonClickedAsync ());
// return false;
// });
//}
else if (!isButtonClicked && !isButtonDoubleClicked && (buttonState == MouseFlags.Button1Released || buttonState == MouseFlags.Button2Released ||
buttonState == MouseFlags.Button3Released || buttonState == MouseFlags.Button4Released)) {
mouseFlags [0] = buttonState;
isButtonPressed = false;
if (isButtonTripleClicked) {
isButtonTripleClicked = false;
} else if (pos.X == point.X && pos.Y == point.Y) {
mouseFlags.Add (GetButtonClicked (buttonState));
isButtonClicked = true;
Application.MainLoop.AddIdle (() => {
Task.Run (async () => await ProcessButtonClickedAsync ());
return false;
});
}
point = pos;
//if ((lastMouseButtonPressed & MouseFlags.ReportMousePosition) == 0) {
// lastMouseButtonReleased = buttonState;
// isButtonPressed = false;
// isButtonReleased = true;
//} else {
// lastMouseButtonPressed = null;
// isButtonPressed = false;
//}
} else if (buttonState == MouseFlags.WheeledUp) {
mouseFlags [0] = MouseFlags.WheeledUp;
} else if (buttonState == MouseFlags.WheeledDown) {
mouseFlags [0] = MouseFlags.WheeledDown;
} else if (buttonState == MouseFlags.WheeledLeft) {
mouseFlags [0] = MouseFlags.WheeledLeft;
} else if (buttonState == MouseFlags.WheeledRight) {
mouseFlags [0] = MouseFlags.WheeledRight;
} else if (buttonState == MouseFlags.ReportMousePosition) {
mouseFlags [0] = MouseFlags.ReportMousePosition;
} else {
mouseFlags [0] = buttonState;
//foreach (var flag in buttonState.GetUniqueFlags()) {
// mouseFlag [0] |= flag;
//}
}
mouseFlags [0] = SetControlKeyStates (buttonState, mouseFlags [0]);
//buttonState = mouseFlags;
//System.Diagnostics.Debug.WriteLine ($"buttonState: {buttonState} X: {pos.X} Y: {pos.Y}");
//foreach (var mf in mouseFlags) {
// System.Diagnostics.Debug.WriteLine ($"mouseFlags: {mf} X: {pos.X} Y: {pos.Y}");
//}
}
private static async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag, Action<MouseFlags, Point> continuousButtonPressedHandler)
{
while (isButtonPressed) {
await Task.Delay (100);
//var me = new MouseEvent () {
// X = point.X,
// Y = point.Y,
// Flags = mouseFlag
//};
var view = Application.WantContinuousButtonPressedView;
if (view == null)
break;
if (isButtonPressed && lastMouseButtonPressed != null && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
Application.MainLoop.Invoke (() => continuousButtonPressedHandler (mouseFlag, point));
}
}
}
private static async Task ProcessButtonClickedAsync ()
{
await Task.Delay (300);
isButtonClicked = false;
}
private static async Task ProcessButtonDoubleClickedAsync ()
{
await Task.Delay (300);
isButtonDoubleClicked = false;
}
private static MouseFlags GetButtonClicked (MouseFlags mouseFlag)
{
MouseFlags mf = default;
switch (mouseFlag) {
case MouseFlags.Button1Released:
mf = MouseFlags.Button1Clicked;
break;
case MouseFlags.Button2Released:
mf = MouseFlags.Button2Clicked;
break;
case MouseFlags.Button3Released:
mf = MouseFlags.Button3Clicked;
break;
}
return mf;
}
private static MouseFlags GetButtonDoubleClicked (MouseFlags mouseFlag)
{
MouseFlags mf = default;
switch (mouseFlag) {
case MouseFlags.Button1Pressed:
mf = MouseFlags.Button1DoubleClicked;
break;
case MouseFlags.Button2Pressed:
mf = MouseFlags.Button2DoubleClicked;
break;
case MouseFlags.Button3Pressed:
mf = MouseFlags.Button3DoubleClicked;
break;
}
return mf;
}
private static MouseFlags GetButtonTripleClicked (MouseFlags mouseFlag)
{
MouseFlags mf = default;
switch (mouseFlag) {
case MouseFlags.Button1Pressed:
mf = MouseFlags.Button1TripleClicked;
break;
case MouseFlags.Button2Pressed:
mf = MouseFlags.Button2TripleClicked;
break;
case MouseFlags.Button3Pressed:
mf = MouseFlags.Button3TripleClicked;
break;
}
return mf;
}
private static MouseFlags SetControlKeyStates (MouseFlags buttonState, MouseFlags mouseFlag)
{
if ((buttonState & MouseFlags.ButtonCtrl) != 0 && (mouseFlag & MouseFlags.ButtonCtrl) == 0)
mouseFlag |= MouseFlags.ButtonCtrl;
if ((buttonState & MouseFlags.ButtonShift) != 0 && (mouseFlag & MouseFlags.ButtonShift) == 0)
mouseFlag |= MouseFlags.ButtonShift;
if ((buttonState & MouseFlags.ButtonAlt) != 0 && (mouseFlag & MouseFlags.ButtonAlt) == 0)
mouseFlag |= MouseFlags.ButtonAlt;
return mouseFlag;
}
/// <summary>
/// Get the terminal that holds the console driver.
/// </summary>
/// <param name="process">The process.</param>
/// <returns>If supported the executable console process, null otherwise.</returns>
public static Process GetParentProcess (Process process)
{
if (!RuntimeInformation.IsOSPlatform (OSPlatform.Windows)) {
return null;
}
string query = "SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = " + process.Id;
using (ManagementObjectSearcher mos = new ManagementObjectSearcher (query)) {
foreach (ManagementObject mo in mos.Get ()) {
if (mo ["ParentProcessId"] != null) {
try {
var id = Convert.ToInt32 (mo ["ParentProcessId"]);
return Process.GetProcessById (id);
} catch {
}
}
}
}
return null;
}
}
}
|
using MySql.Data.MySqlClient;
using ProyectoLP2;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccesoDatos
{
public class PedidoDA
{
public PedidoDA()
{
}
public int agregar(Pedido pedido)
{
MySqlConnection conn = new MySqlConnection(DBManager.cadena);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "insertarPedido";
cmd.Parameters.Add("_llegada", MySqlDbType.VarChar).Value =pedido.Direccion.DetalleDireccion;
cmd.Parameters.Add("_dniVendedor", MySqlDbType.VarChar).Value = pedido.Cliente.Dni_vendedor;
cmd.Parameters.Add("_idCliente", MySqlDbType.Int32).Value = pedido.Cliente.Id;
cmd.Parameters.Add("_idAgencia", MySqlDbType.Int32).Value = pedido.Transportista.Id;
cmd.Parameters.Add("_idDireccion", MySqlDbType.Int32).Value = pedido.Direccion.Id;
cmd.Parameters.Add("_etapaPedido", MySqlDbType.Int32).Value = (int)pedido.Etapa;
cmd.Parameters.Add("_idPedido", MySqlDbType.Int32).Direction = System.Data.ParameterDirection.Output;
cmd.ExecuteNonQuery();
int idPedidoIngresado = Int32.Parse(cmd.Parameters["_idPedido"].Value.ToString());
conn.Close();
return idPedidoIngresado;
}
public void AgregarDetalle(int idPedido,DetallePedido detalle)
{
MySqlConnection conn = new MySqlConnection(DBManager.cadena);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
String sql = "INSERT INTO n_detalle_pedido ( cantidad, descuento1, subtotal, id_pedido, id_producto, estado) values " +
"("+detalle.Cantidad+","+detalle.Desc+","+detalle.Subtotal+","+idPedido+",'"+detalle.proCod+"',1)";
cmd.CommandText = sql;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
public BindingList<Pedido> listarPedidos()
{
BindingList<Pedido> lista = new BindingList<Pedido>();
MySqlConnection conn = new MySqlConnection(DBManager.cadena);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
String sql = "SELECT p.*,cli.ruc,cli.nombre nombrecli ,cli.apellido apelCli ,dircli.direccion direccion, user.nombre nombreVendedor,user.apellido_paterno apelVendedor,user.comision comision,agen.nombre nombreAgencia FROM n_pedido p,n_cliente cli,n_usuarios user,n_direccion_cli dircli, n_agencia agen where p.id_cliente = cli.id_cliente and p.estado=1 and p.dni_vendedor = user.dni_empleado and p.id_direccion = dircli.id_direccion and p.id_agencia = agen.id_agencia and etapaProceso != 4;";
cmd.CommandText = sql;
cmd.Connection = conn;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Cliente cliente = new Cliente();
cliente.Ruc = reader.GetString("ruc");
cliente.Nombre = reader.GetString("nombrecli");
cliente.ApellidoPaterno = reader.GetString("apelCli");
cliente.Dni_vendedor= reader.GetString("dni_vendedor");
cliente.Id = reader.GetInt32("id_cliente");
Vendedor vendedor = new Vendedor();
vendedor.Dni = reader.GetString("dni_vendedor");
vendedor.Nombre = reader.GetString("nombreVendedor");
vendedor.Apellido = reader.GetString("apelVendedor");
Transportista trans = new Transportista();
trans.Nombre = reader.GetString("nombreAgencia");
trans.Id = reader.GetInt32("id_agencia");
Direccion direccion = new Direccion();
direccion.Id = reader.GetInt32("id_agencia");
direccion.DetalleDireccion = reader.GetString("direccion");
Pedido pedido = new Pedido();
pedido.IdVenta = reader.GetInt32("id_pedido");
pedido.Cliente = cliente;
pedido.Vendedor = vendedor;
pedido.Transportista = trans;
pedido.Direccion = direccion;
pedido.Etapa = (EtapaPedido)reader.GetInt32("etapaProceso");
pedido.Fecha_e = reader.GetDateTime("fecha_recepcion");
//pedido.Etapa =
pedido.Etapa = (EtapaPedido)reader.GetInt32("etapaProceso");
lista.Add(pedido);
}
conn.Close();
return lista;
}
public BindingList<Pedido> listarPedidos(int tipo)
{
BindingList<Pedido> lista = new BindingList<Pedido>();
MySqlConnection conn = new MySqlConnection(DBManager.cadena);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
String sql = "SELECT p.*,cli.ruc,cli.nombre nombrecli ,cli.apellido apelCli ,dircli.direccion direccion, user.nombre nombreVendedor,user.apellido_paterno apelVendedor,user.comision comision,agen.nombre nombreAgencia FROM n_pedido p,n_cliente cli,n_usuarios user,n_direccion_cli dircli, n_agencia agen where p.id_cliente = cli.id_cliente and p.estado=1 and p.dni_vendedor = user.dni_empleado and p.id_direccion = dircli.id_direccion and p.id_agencia = agen.id_agencia and etapaProceso ="+tipo.ToString()+";";
cmd.CommandText = sql;
cmd.Connection = conn;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Cliente cliente = new Cliente();
cliente.Ruc = reader.GetString("ruc");
cliente.Nombre = reader.GetString("nombrecli");
cliente.ApellidoPaterno = reader.GetString("apelCli");
cliente.Dni_vendedor = reader.GetString("dni_vendedor");
cliente.Id = reader.GetInt32("id_cliente");
Vendedor vendedor = new Vendedor();
vendedor.Dni = reader.GetString("dni_vendedor");
vendedor.Nombre = reader.GetString("nombreVendedor");
vendedor.Apellido = reader.GetString("apelVendedor");
vendedor.Comision = reader.GetDouble("comision");
Transportista trans = new Transportista();
trans.Nombre = reader.GetString("nombreAgencia");
trans.Id = reader.GetInt32("id_agencia");
Direccion direccion = new Direccion();
direccion.Id = reader.GetInt32("id_agencia");
direccion.DetalleDireccion = reader.GetString("direccion");
Pedido pedido = new Pedido();
pedido.IdVenta = reader.GetInt32("id_pedido");
pedido.Cliente = cliente;
pedido.Vendedor = vendedor;
pedido.Transportista = trans;
pedido.Direccion = direccion;
pedido.Etapa = (EtapaPedido)reader.GetInt32("etapaProceso");
pedido.Fecha_e = reader.GetDateTime("fecha_recepcion");
//pedido.Etapa =
pedido.Etapa = (EtapaPedido)reader.GetInt32("etapaProceso");
lista.Add(pedido);
}
conn.Close();
return lista;
}
public void eliminar(int id)
{
MySqlConnection conn = new MySqlConnection(DBManager.cadena);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "ELIMINAR_PEDIDO";
cmd.Parameters.Add("_IDPEDIDO", MySqlDbType.Int32).Value = id;
cmd.ExecuteNonQuery();
conn.Close();
}
public BindingList<DetallePedido> listarDetallePedido(int id)
{
BindingList<DetallePedido> lista = new BindingList<DetallePedido>();
MySqlConnection conn = new MySqlConnection(DBManager.cadena);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "listarDetallesPedido";
cmd.Parameters.Add("_idPedido", MySqlDbType.Int32).Value = id;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Producto producto = new Producto();
producto.Codigo = reader.GetString("id_producto");
producto.Nombre = reader.GetString("nombre");
switch (reader.GetString("UnidMedida"))
{
case "UNIDAD":
producto.Um = Medida.unidad;
break;
case "CIENTO":
producto.Um = Medida.ciento;
break;
case "METRO":
producto.Um = Medida.metro;
break;
case "BOLSA":
producto.Um = Medida.bolsa;
break;
case "DOCENA":
producto.Um = Medida.docena;
break;
case "KILOGRAMO":
producto.Um = Medida.kilogramo;
break;
}
producto.Precio = reader.GetDouble("precio");
producto.Descripcion = reader.GetString("descripcion");
producto.Stock = reader.GetInt32("stock");
//producto.MinimoStock = reader.GetInt32("stockMinimo");
DetallePedido detallePedido = new DetallePedido();
detallePedido.Producto = producto;
detallePedido.Cantidad = reader.GetInt32("cantidad");
detallePedido.Subtotal = reader.GetDouble("subtotal");
detallePedido.Desc = reader.GetInt32("descuento1");
lista.Add(detallePedido);
}
conn.Close();
return lista;
}
public void agregarFactura(int idPedido,double totalDescuento, double totalImpuesto, double totalValorNeto, double netoApagar,int estadoVenta, int estadoPagoVendedor, double montoPagoVendedor)
{
MySqlConnection conn = new MySqlConnection(DBManager.cadena);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "AGREGAR_FACTURA";
cmd.Parameters.Add("_TOTALDESCUENTO", MySqlDbType.Double).Value = totalDescuento;
cmd.Parameters.Add("_TOTALIMPUESTO", MySqlDbType.Double).Value = totalImpuesto;
cmd.Parameters.Add("_TOTALVALORNETO", MySqlDbType.Double).Value = totalValorNeto;
cmd.Parameters.Add("_NETOAPAGAR", MySqlDbType.Double).Value = netoApagar;
cmd.Parameters.Add("_ESTADOVENTA", MySqlDbType.Int32).Value = estadoVenta;
cmd.Parameters.Add("_ESTADOPAGOVENDEDOR", MySqlDbType.Int32).Value = estadoPagoVendedor;
cmd.Parameters.Add("_MONTOPAGOVENDEDOR", MySqlDbType.Double).Value = montoPagoVendedor;
cmd.Parameters.Add("_IDPEDIDO", MySqlDbType.Int32).Value = idPedido;
cmd.ExecuteNonQuery();
conn.Close();
}
public void facturarPedido(int idPedido)
{
MySqlConnection conn = new MySqlConnection(DBManager.cadena);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "FACTURAR_PEDIDO";
cmd.Parameters.Add("_IDPEDIDO", MySqlDbType.Int32).Value = idPedido;
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entities;
using DataAccessLayer;
namespace BLL
{
public class ProjectBusiness : IBusiness<Project>
{
UnitOfWork _uof;
Employee _emp;
public ProjectBusiness(Employee employee)
{
_emp = employee;
_uof = new UnitOfWork();
}
public bool Add(Project item)
{
if (item!=null)
{
if (item.CustomerID==null )
{
throw new Exception("Projenin mutlaka bir müşterisi olmalıdır");
}
//Bir projenin 4 tane çalışanı olmak zorunda ve çalışanı boş geçileme<
if (item.Employees.Count < 4 || item.Employees == null)
{
throw new Exception("Projenin mutlaka en az 4 farklı çalışanı olmalıdır");
}
if (item.PlannedEndDate==null )
{
throw new Exception("Projenin planlanan başlangıç tarihi belirlenmelidir");
}
if (item.PlannedStartDate==null)
{
throw new Exception("Projenin planlanan bitiş tarihi belirlenmelidir");
}
if (item.State==null)
{
item.State = "Oluşturuldu";
}
if (item.Name==null)
{
throw new Exception("Proje ismi mutlaka girilmelidir");
}
if (item.Description==null)
{
throw new Exception("Proje oluşturulurken mutlaka detay kısmı doldurulmalıdır");
}
if (true)
{
_uof.ProjectRepository.Add(item);
return _uof.ApplyChanges();
}
}
return false;
}
public Project Get(int id)
{
if (id>0)
{
return _uof.ProjectRepository.Get(id);
}
return null;
}
public ICollection<Project> GetAll()
{
return _uof.ProjectRepository.GetAll();
}
public bool Remove(Project item)
{
if (item!=null)
{
_uof.ProjectRepository.Remove(item);
return _uof.ApplyChanges();
}
return false;
}
public bool Update(Project item)
{
if (item != null)
{
if (item.Customer == null )
{
throw new Exception("Projenin mutlaka bir müşterisi olmalıdır");
}
//Bir projenin 4 tane çalışanı olmak zorunda ve çalışanı boş geçileme<
if (item.Employees.Count<4 || item.Employees==null)
{
throw new Exception("Projenin mutlaka en az 4 farklı çalışanı olmalıdır");
}
if (item.PlannedEndDate == null)
{
throw new Exception("Projenin planlanan başlangıç tarihi belirlenmelidir");
}
if (item.PlannedStartDate == null)
{
throw new Exception("Projenin planlanan bitiş tarihi belirlenmelidir");
}
if (item.State == null)
{
item.State = "Güncellendi";
}
if (item.Name == null)
{
throw new Exception("Proje ismi mutlaka girilmelidir");
}
if (item.Description == null)
{
throw new Exception("Proje oluşturulurken mutlaka detay kısmı doldurulmalıdır");
}
if (true)
{
_uof.ProjectRepository.Update(item);
_uof.ApplyChanges();
return true;
}
}
return false;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.