text stringlengths 13 6.01M |
|---|
namespace Olive.Desktop.WPF.ViewModels
{
using System.ComponentModel;
using System.Windows;
using Olive.Data.Uow;
using System.Collections.Generic;
using System.Windows.Data;
using System.Reflection;
using System.Diagnostics;
using System.IO;
using System;
public abstract class ViewModelBase : DependencyObject,INotifyPropertyChanged
{
private IUowData db;
private string assemblyPath = null;
public string AssemblyPath
{
get
{
string process = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
string environment = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
this.assemblyPath = AppDomain.CurrentDomain.BaseDirectory;
this.assemblyPath = Assembly.GetExecutingAssembly().Location;
this.assemblyPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
return assemblyPath;
}
}
public IUowData Db
{
get
{
if (this.db==null)
{
this.db=new UowData();
}
return this.db;
}
set
{
this.db=value;
}
}
protected IUowData GetUowDataInstance()
{
UowData db = new UowData();
return db;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
protected ICollectionView GetDefaultView<T>(IEnumerable<T> collection)
{
return CollectionViewSource.GetDefaultView(collection);
}
}
}
|
using gView.Framework.Data;
using gView.Framework.Data.Cursors;
using gView.Framework.Data.Filters;
using gView.Framework.Geometry;
using gView.Framework.SpatialAlgorithms;
using gView.Framework.system;
using LuceneServerNET.Client;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace gView.Cmd.FillLuceneServer
{
class Program
{
private static IFormatProvider _nhi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
async static Task<int> Main(string[] args)
{
try
{
string cmd = "fill", jsonFile = (args.Length == 1 && args[0] != "fill" ? args[0] : String.Empty), indexUrl = String.Empty, indexName = String.Empty, category = String.Empty;
string proxyUrl = String.Empty, proxyUser = String.Empty, proxyPassword = String.Empty;
string basicAuthUser = String.Empty, basicAuthPassword = String.Empty;
int packageSize = 50000;
//bool replace = false;
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "fill" && i < args.Length - 1)
{
cmd = "fill";
jsonFile = args[i + 1];
i++;
}
if (args[i] == "remove-category")
{
cmd = "remove-category";
}
if (args[i] == "-s" && i < args.Length - 1)
{
indexUrl = args[i + 1];
}
if (args[i] == "-i" && i < args.Length - 1)
{
indexName = args[i + 1];
}
if (args[i] == "-c" && i < args.Length - 1)
{
category = args[i + 1];
}
//if (args[i] == "-r")
//{
// replace = true;
//}
if (args[i] == "-packagesize" && i < args.Length - 1)
{
packageSize = int.Parse(args[i + 1]);
}
#region Proxy
if (args[i] == "-proxy")
{
proxyUrl = args[i + 1];
}
if (args[i] == "-proxy-user")
{
proxyUser = args[i + 1];
}
if (args[i] == "-proxy-pwd")
{
proxyPassword = args[i + 1];
}
#endregion
#region Basic Authentication
if (args[i] == "-basic-auth-user")
{
basicAuthUser = args[i + 1];
}
if (args[i] == "-basic-auth-pwd")
{
basicAuthPassword = args[i + 1];
}
#endregion
}
if (args.Length == 0)
{
Console.WriteLine("Usage: gView.Cmd.ElasticSearch fill|remove-catetory [Options]");
return 1;
}
//gView.Framework.system.SystemVariables.CustomApplicationDirectory =
// System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Console.WriteLine("Environment");
Console.WriteLine("Working Directory: " + gView.Framework.system.SystemVariables.StartupDirectory);
Console.WriteLine("64Bit=" + gView.Framework.system.Wow.Is64BitProcess);
if (cmd == "fill")
{
#region Fill Index (with Json File)
var importConfig = JsonConvert.DeserializeObject<ImportConfig>(File.ReadAllText(jsonFile));
if (importConfig?.Connection == null)
{
throw new Exception("Invalid config. No connection defined");
}
var httpClientHandler = new HttpClientHandler();
if (!String.IsNullOrEmpty(proxyUrl))
{
httpClientHandler.Proxy = new WebProxy
{
Address = new Uri(proxyUrl),
BypassProxyOnLocal = false,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(proxyUser, proxyPassword)
};
}
var httpClient = new HttpClient(handler: httpClientHandler, disposeHandler: true);
if (!String.IsNullOrEmpty(basicAuthUser))
{
var byteArray = Encoding.ASCII.GetBytes($"{basicAuthUser}:{basicAuthPassword}");
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
using (var luceneServerClient = new LuceneServerClient(
importConfig.Connection.Url,
importConfig.Connection.DefaultIndex,
httpClient: httpClient))
{
if (importConfig.Connection.DeleteIndex)
{
await luceneServerClient.RemoveIndexAsync();
}
if (!await luceneServerClient.CreateIndexAsync())
{
throw new Exception($"Can't create elasticsearch index {importConfig.Connection.DefaultIndex}");
}
if (!await luceneServerClient.MapAsync(new SearchIndexMapping(importConfig.Connection.PhoneticAlgorithm,
importConfig.Connection.EncodeCharacters)))
{
throw new Exception($"Can't map item in elasticsearch index {importConfig.Connection.DefaultIndex}");
}
ISpatialReference sRefTarget = SpatialReference.FromID("epsg:4326");
Console.WriteLine("Target Spatial Reference: " + sRefTarget.Name + " " + String.Join(" ", sRefTarget.Parameters));
foreach (var datasetConfig in importConfig.Datasets)
{
if (datasetConfig.FeatureClasses == null)
{
continue;
}
IDataset dataset = new PlugInManager().CreateInstance(datasetConfig.DatasetGuid) as IDataset;
if (dataset == null)
{
throw new ArgumentException("Can't load dataset with guid " + datasetConfig.DatasetGuid.ToString());
}
await dataset.SetConnectionString(datasetConfig.ConnectionString);
await dataset.Open();
foreach (var featureClassConfig in datasetConfig.FeatureClasses)
{
var itemProto = featureClassConfig.IndexItemProto;
if (itemProto == null)
{
continue;
}
string metaId = Guid.NewGuid().ToString("N").ToLower();
category = featureClassConfig.Category;
if (!String.IsNullOrWhiteSpace(category))
{
var meta = new Meta()
{
Id = metaId,
Category = category,
Descrption = featureClassConfig.Meta?.Descrption,
Sample = featureClassConfig?.Meta.Sample,
Service = featureClassConfig?.Meta.Service,
Query = featureClassConfig?.Meta.Query
};
if (!await luceneServerClient.AddCustomMetadataAsync(metaId, JsonConvert.SerializeObject(meta)))
{
throw new Exception($"Can't index meta item in elasticsearch index {importConfig.Connection.MetaIndex}");
}
}
bool useGeometry = featureClassConfig.UserGeometry;
IDatasetElement dsElement = await dataset.Element(featureClassConfig.Name);
if (dsElement == null)
{
throw new ArgumentException("Unknown dataset element " + featureClassConfig.Name);
}
IFeatureClass fc = dsElement.Class as IFeatureClass;
if (fc == null)
{
throw new ArgumentException("Dataobject is not a featureclass " + featureClassConfig.Name);
}
Console.WriteLine("Index " + fc.Name);
Console.WriteLine("=====================================================================");
QueryFilter filter = new QueryFilter();
filter.SubFields = "*";
if (!String.IsNullOrWhiteSpace(featureClassConfig.Filter))
{
filter.WhereClause = featureClassConfig.Filter;
Console.WriteLine("Filter: " + featureClassConfig.Filter);
}
List<Dictionary<string, object>> items = new List<Dictionary<string, object>>();
int count = 0;
ISpatialReference sRef = fc.SpatialReference ?? SpatialReference.FromID("epsg:" + featureClassConfig.SRefId);
Console.WriteLine("Source Spatial Reference: " + sRef.Name + " " + String.Join(" ", sRef.Parameters));
Console.WriteLine("IDField: " + fc.IDFieldName);
using (var transformer = GeometricTransformerFactory.Create())
{
if (useGeometry)
{
transformer.SetSpatialReferences(sRef, sRefTarget);
}
IFeatureCursor cursor = await fc.GetFeatures(filter);
IFeature feature;
while ((feature = await cursor.NextFeature()) != null)
{
var indexItem = ParseFeature(metaId, category, feature, itemProto, useGeometry, transformer, featureClassConfig);
items.Add(indexItem);
count++;
if (items.Count >= packageSize)
{
if (!await luceneServerClient.IndexDocumentsAsync(items.ToArray()))
{
throw new Exception($"Error on indexing {items.Count} items on elasticsearch index {importConfig.Connection.DefaultIndex}");
}
items.Clear();
Console.Write(count + "...");
}
}
if (items.Count > 0)
{
if (!await luceneServerClient.IndexDocumentsAsync(items.ToArray()))
{
throw new Exception($"Error on indexing {items.Count} items on elasticsearch index {importConfig.Connection.DefaultIndex}");
}
Console.WriteLine(count + "...finish");
}
}
}
}
}
#endregion
}
else if (cmd == "remove-category")
{
#region Remove Category
//RemoveCategory(indexUrl, indexName, replace ? Replace(category) : category,
// proxyUrl, proxyUser, proxyPassword,
// basicAuthUser, basicAuthPassword);
#endregion
}
return 0;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
return 1;
}
}
static private Dictionary<string, object> ParseFeature(string metaId, string category, IFeature feature, Item proto, bool useGeometry, IGeometricTransformer transformer, ImportConfig.FeatureClassDefinition featureClassDef)
{
var replace = featureClassDef.Replacements;
var result = new Dictionary<string, object>();
string oid = feature.OID.ToString();
if (feature.OID <= 0 && !String.IsNullOrWhiteSpace(featureClassDef.ObjectOidField))
{
var idFieldValue = feature.FindField(featureClassDef.ObjectOidField);
if (idFieldValue != null)
{
oid = idFieldValue.Value?.ToString();
}
}
result["id"] = metaId + "." + oid;
result["suggested_text"] = ParseFeatureField(feature, proto.SuggestedText);
result["subtext"] = ParseFeatureField(feature, proto.SubText);
result["thumbnail_url"] = ParseFeatureField(feature, proto.ThumbnailUrl);
result["category"] = category;
if (replace != null)
{
foreach (var r in replace)
{
result["suggested_text"] = result["suggested_text"]?.ToString().Replace(r.From, r.To);
result["subtext"] = result["subtext"]?.ToString().Replace(r.From, r.To);
}
}
if (useGeometry == true && feature.Shape != null)
{
IGeometry shape = feature.Shape;
if (shape is IPoint)
{
IPoint point = (IPoint)transformer.Transform2D(feature.Shape);
//result["longitude"] = point.X;
//result["latitude"] = point.Y;
result["geo"] = new LuceneServerNET.Core.Models.Spatial.GeoPoint()
{
Longidute = point.X,
Latitude = point.Y
};
}
else if (shape is IPolyline)
{
IEnvelope env = shape.Envelope;
if (env != null)
{
IPoint point = Algorithm.PolylinePoint((IPolyline)shape, ((IPolyline)shape).Length / 2.0);
if (point != null)
{
point = (IPoint)transformer.Transform2D(point);
//result["longitude"] = point.X;
//result["latitude"] = point.Y;
result["geo"] = new LuceneServerNET.Core.Models.Spatial.GeoPoint()
{
Longidute = point.X,
Latitude = point.Y
};
}
result["bbox"] = GetBBox(env, transformer);
}
}
else if (shape is IPolygon)
{
IEnvelope env = shape.Envelope;
if (env != null)
{
var points = Algorithm.OrderPoints(Algorithm.PolygonLabelPoints((IPolygon)shape), env.Center);
if (points != null && points.PointCount > 0)
{
IPoint point = (IPoint)transformer.Transform2D(points[0]);
//result["longitude"] = point.X;
//result["latitude"] = point.Y;
result["geo"] = new LuceneServerNET.Core.Models.Spatial.GeoPoint()
{
Longidute = point.X,
Latitude = point.Y
};
}
result["bbox"] = GetBBox(env, transformer);
}
}
}
return result;
}
static private string ParseFeatureField(IFeature feature, string pattern)
{
if (pattern == null || !pattern.Contains("{"))
{
return pattern;
}
string[] parameters = GetKeyParameters(pattern);
foreach (string parameter in parameters)
{
var fieldValue = feature.FindField(parameter);
if (fieldValue == null)
{
continue;
}
string val = fieldValue.Value != null ? fieldValue.Value.ToString() : String.Empty;
pattern = pattern.Replace("{" + parameter + "}", val);
}
return pattern;
}
static private string[] GetKeyParameters(string pattern)
{
int pos1 = 0, pos2;
pos1 = pattern.IndexOf("{");
string parameters = "";
while (pos1 != -1)
{
pos2 = pattern.IndexOf("}", pos1);
if (pos2 == -1)
{
break;
}
if (parameters != "")
{
parameters += ";";
}
parameters += pattern.Substring(pos1 + 1, pos2 - pos1 - 1);
pos1 = pattern.IndexOf("{", pos2);
}
if (parameters != "")
{
return parameters.Split(';');
}
else
{
return new string[0];
}
}
static private string GetBBox(IEnvelope env, IGeometricTransformer transformer)
{
try
{
env = ((IGeometry)transformer.Transform2D(env)).Envelope;
return Math.Round(env.minx, 7).ToString(_nhi) + "," +
Math.Round(env.miny, 7).ToString(_nhi) + "," +
Math.Round(env.maxx, 7).ToString(_nhi) + "," +
Math.Round(env.maxy, 7).ToString(_nhi);
}
catch { return String.Empty; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace API.Entities
{
public class Product
{
//properties
//to get from database
//these entities should relate to the database
public int Id { get; set; }
public string Name { get; set; }
}
}
|
using System;
namespace IRO.ImageOrganizer.Logic
{
public class OrganizeImageArgs
{
/// <summary>
/// The source directory
/// </summary>
public String SourceDirectory { get; set; }
/// <summary>
/// The destination directory
/// </summary>
public String DestinationDirectory { get; set; }
/// <summary>
/// The failures directory
/// </summary>
public String FailuresDirectory { get; set; }
/// <summary>
/// The destination directory mask
/// </summary>
public String DestinationDirectoryMask { get; set; }
/// <summary>
/// The include subdirectories
/// </summary>
public Boolean IncludeSubdirectories { get; set; }
/// <summary>
/// The do not move source files
/// </summary>
public Boolean DeleteSourceImages { get; set; }
/// <summary>
/// The rename files according to date
/// </summary>
public Boolean RenameFilesAccordingToDate { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [move failed files].
/// </summary>
/// <value>
/// <c>true</c> if [move failed files]; otherwise, <c>false</c>.
/// </value>
public Boolean MoveFailedFiles { get; set; }
}
}
|
using System;
using Phenix.Business;
using Phenix.Core;
namespace Phenix.Test.使用指南._12._6._2._1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("本程序为{0}位,请确认所连数据库客户端引擎是否与之匹配?(如不匹配可调整本程序的'平台目标'生成类型)", Environment.Is64BitProcess ? "64" : "32");
Console.WriteLine("请通过检索“//*”了解代码中的特殊处理");
Console.WriteLine("本案例中表结构未设置中文友好名,可通过数据库字典相关的Comments内容来自动设置上");
Console.WriteLine("测试过程中的日志保存在:" + Phenix.Core.AppConfig.TempDirectory);
Console.WriteLine("因需要初始化本地配置数据,第一次运行会比正常情况下稍慢,请耐心等待");
Console.WriteLine();
Console.WriteLine("设为调试状态");
Phenix.Core.AppConfig.Debugging = true;
Console.WriteLine();
Console.WriteLine("模拟登陆");
Phenix.Business.Security.UserPrincipal.User = Phenix.Business.Security.UserPrincipal.CreateTester();
Phenix.Services.Client.Library.Registration.RegisterEmbeddedWorker(false);
Console.WriteLine();
Console.WriteLine("**** 测试将完整的业务数据提交到服务端功能 ****");
Console.WriteLine("Fetch全景User集合对象");
UserList users = UserList.Fetch();
Console.WriteLine("User集合对象的EnsembleOnSaving属性为:" + ((IBusiness)users[0]).EnsembleOnSaving + ' ' + (((IBusiness)users[0]).EnsembleOnSaving ? "ok" : "error"));
Console.WriteLine("User集合对象中含有业务对象数:" + users.Count);
if (users.Count >= 2)
{
users[users.Count - 1].Name = users[users.Count - 1].Name + "_test";
Console.WriteLine("修改最后一个User业务对象的Name属性:" + users[users.Count - 1].GetOldValue(User.NameProperty) + " 为 " + users[users.Count - 1].Name);
}
Console.WriteLine("提交User集合对象...");
try
{
users.Save();
}
catch (Exception ex)
{
Console.WriteLine(AppUtilities.GetErrorMessage(ex)); //见UserList的OnSavingSelf(DbTransaction transaction)函数
}
Console.WriteLine();
Console.WriteLine("结束, 与数据库交互细节见日志");
Console.ReadLine();
}
}
}
|
using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Media.Imaging;
namespace SlideShow
{
public partial class PhotoInfo
{
ExifReader r;
string shortName;
public PhotoInfo(string fileName)
{
this.InitializeComponent();
shortName = System.IO.Path.GetFileName(fileName);
r = new ExifReader(fileName);
PreviewImage.Source = new BitmapImage(new Uri(fileName));
string[] userPositions = Properties.Settings.Default.InfoDialogPosition.Split(';');
if (userPositions.Length == 2)
{
Left = double.Parse(userPositions[0]);
Top = double.Parse(userPositions[1]);
}
else
{
Left = (SystemParameters.PrimaryScreenWidth - (double)GetValue(WidthProperty)) / 2;
Top = (SystemParameters.PrimaryScreenHeight - (double)GetValue(HeightProperty)) / 2;
}
this.Closing += new System.ComponentModel.CancelEventHandler(PhotoInfo_Closing);
this.Loaded += new RoutedEventHandler(PhotoInfo_Loaded);
}
void PhotoInfo_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string userPos = this.Left.ToString() + ";" + this.Top.ToString();
Properties.Settings.Default.InfoDialogPosition = userPos;
Properties.Settings.Default.Save();
}
void PhotoInfo_Loaded(object sender, RoutedEventArgs e)
{
InfoText.Text = "File : " + shortName + "\n";
InfoText.Text += "Size : " + r.GetImage().Width.ToString() + " x " + r.GetImage().Height.ToString() + "\n";
InfoText.Text += "Camera make : " + r.GetMake() + "\n";
InfoText.Text += "Camera model : " + r.GetModel() + "\n\n";
InfoText.Text += "Date taken : " + r.GetDateTimeOriginal() + "\n";
InfoText.Text += "Focal length : " + r.GetFocalLength() + "\n";
InfoText.Text += "Shutter : " + r.GetExposureTime() + "\n";
InfoText.Text += "Aperture : " + r.GetFNumber() + "\n";
InfoText.Text += "ISO : " + r.GetISO() + "\n";
InfoText.Text += "Exposure : " + r.GetExposureBiasValue() + "\n";
InfoText.Text += "White balance : " + r.GetWhiteBalance() + "\n";
InfoText.Text += "Mode : " + r.GetMeteringMode() + "\n";
InfoText.Text += "Exp mode : " + r.GetExposureMode() + "\n";
InfoText.Text += "Program : " + r.GetExposureProgram() + "\n";
InfoText.Text += "Flash : " + r.GetFlash() + "\n\n";
}
}
} |
using Alabo.Datas.Stores;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities;
using Alabo.Domains.Enums;
using Alabo.Domains.Services.Update;
using Alabo.Linq;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Alabo.Domains.Services.Time {
public class TimeBase<TEntity, TKey> : UpdateBaseAsync<TEntity, TKey>, ITime<TEntity, TKey>
where TEntity : class, IAggregateRoot<TEntity, TKey> {
public TimeBase(IUnitOfWork unitOfWork, IStore<TEntity, TKey> store) : base(unitOfWork, store) {
}
public IEnumerable<TEntity> GetLastList(TimeType timeType, Expression<Func<TEntity, bool>> predicate) {
return GetLastList(timeType, DateTime.Now, predicate);
}
public IEnumerable<TEntity> GetLastList(TimeType timeType, DateTime dateTime,
Expression<Func<TEntity, bool>> predicate) {
predicate = timeType.GetPredicate<TEntity, TKey>(dateTime, predicate);
return GetList(predicate);
}
public TEntity GetLastSingle(TimeType timeType, DateTime dateTime, Expression<Func<TEntity, bool>> predicate) {
predicate = timeType.GetPredicate<TEntity, TKey>(dateTime, predicate);
return GetSingle(predicate);
}
public TEntity GetLastSingle(TimeType timeType, Expression<Func<TEntity, bool>> predicate) {
return GetLastSingle(timeType, DateTime.Now, predicate);
}
}
} |
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TomKlonowski.Api.Model.Request;
using TomKlonowski.Api.Model.Response;
namespace TomKlonowski.Api.Service
{
public class HelloService : IService
{
public object Any(HelloRequest request)
{
var name = request.Name ?? "John Doe";
return new HelloResponse { Result = "Hello, " + name };
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Profiling2.Domain.Contracts.Queries;
using Profiling2.Domain.Contracts.Tasks;
using Profiling2.Domain.Contracts.Tasks.Screenings;
using Profiling2.Domain.Prf;
using Profiling2.Domain.Prf.Careers;
using Profiling2.Domain.Prf.Persons;
using Profiling2.Domain.Prf.Units;
using Profiling2.Domain.Scr;
using Profiling2.Domain.Scr.Person;
using Profiling2.Domain.Scr.Proposed;
using SharpArch.NHibernate.Contracts.Repositories;
namespace Profiling2.Tasks.Screenings
{
public class RequestPersonTasks : IRequestPersonTasks
{
private readonly INHibernateRepository<RequestPerson> requestPersonRepository;
private readonly INHibernateRepository<RequestPersonStatus> requestPersonStatusRepository;
private readonly INHibernateRepository<RequestPersonHistory> requestPersonHistoryRepository;
private readonly INHibernateRepository<RequestProposedPerson> proposedRepo;
private readonly INHibernateRepository<RequestProposedPersonStatus> proposedStatusRepo;
private readonly INHibernateRepository<RequestProposedPersonHistory> proposedHistoryRepo;
private readonly INHibernateRepository<RequestUnit> requestUnitRepository;
private readonly IRequestPersonsQuery requestPersonsQuery;
private readonly IAuditTasks auditTasks;
public RequestPersonTasks(INHibernateRepository<RequestPerson> requestPersonRepository,
INHibernateRepository<RequestPersonStatus> requestPersonStatusRepository,
INHibernateRepository<RequestPersonHistory> requestPersonHistoryRepository,
INHibernateRepository<RequestProposedPerson> proposedRepo,
INHibernateRepository<RequestProposedPersonStatus> proposedStatusRepo,
INHibernateRepository<RequestProposedPersonHistory> proposedHistoryRepo,
INHibernateRepository<RequestUnit> requestUnitRepository,
IRequestPersonsQuery requestPersonsQuery,
IAuditTasks auditTasks)
{
this.requestPersonRepository = requestPersonRepository;
this.requestPersonStatusRepository = requestPersonStatusRepository;
this.requestPersonHistoryRepository = requestPersonHistoryRepository;
this.proposedRepo = proposedRepo;
this.proposedStatusRepo = proposedStatusRepo;
this.proposedHistoryRepo = proposedHistoryRepo;
this.requestUnitRepository = requestUnitRepository;
this.requestPersonsQuery = requestPersonsQuery;
this.auditTasks = auditTasks;
}
public RequestPerson GetRequestPerson(int id)
{
return this.requestPersonRepository.Get(id);
}
public RequestPerson SaveRequestPerson(RequestPerson rp)
{
return this.requestPersonRepository.SaveOrUpdate(rp);
}
public RequestPerson SaveRequestPerson(Request request, Person person)
{
if (request != null && person != null)
{
RequestPerson rp = request.AddPerson(person);
return this.requestPersonRepository.SaveOrUpdate(rp);
}
return null;
}
public RequestPerson ArchiveRequestPerson(Request request, Person person)
{
if (request != null && person != null)
{
RequestPerson rp = request.GetPerson(person);
if (rp != null)
{
rp.Archive = true;
return this.requestPersonRepository.SaveOrUpdate(rp);
}
}
return null;
}
public RequestPersonStatus GetRequestPersonStatus(string name)
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("RequestPersonStatusName", name);
return this.requestPersonStatusRepository.FindOne(criteria);
}
public RequestPersonHistory SaveRequestPersonHistory(RequestPerson rp, string status, AdminUser user)
{
if (rp != null && !string.IsNullOrEmpty(status) && user != null)
{
RequestPersonHistory h = new RequestPersonHistory();
h.RequestPerson = rp;
h.RequestPersonStatus = this.GetRequestPersonStatus(status);
h.AdminUser = user;
h.DateStatusReached = DateTime.Now;
rp.AddRequestPersonHistory(h);
return this.requestPersonHistoryRepository.SaveOrUpdate(h);
}
return null;
}
public bool NominateRequestPerson(RequestPerson rp, AdminUser user)
{
RequestPersonHistory rph = this.SaveRequestPersonHistory(rp, RequestPersonStatus.NAME_NOMINATED, user);
return rph != null;
}
public bool WithdrawRequestPersonNomination(RequestPerson rp, AdminUser user)
{
RequestPersonHistory rph = this.SaveRequestPersonHistory(rp, RequestPersonStatus.NAME_NOMINATION_WITHDRAWN, user);
return rph != null;
}
public RequestProposedPerson GetRequestProposedPerson(int requestProposedPersonId)
{
return this.proposedRepo.Get(requestProposedPersonId);
}
public RequestProposedPerson SaveRequestProposedPerson(RequestProposedPerson rpp)
{
if (rpp != null && rpp.Request != null)
{
rpp.Request.AddProposedPerson(rpp);
rpp = this.proposedRepo.SaveOrUpdate(rpp);
}
return rpp;
}
public RequestProposedPersonStatus GetRequestProposedPersonStatus(string name)
{
IDictionary<string, object> criteria = new Dictionary<string, object>();
criteria.Add("RequestProposedPersonStatusName", name);
return this.proposedStatusRepo.FindOne(criteria);
}
public RequestProposedPersonHistory SaveRequestProposedPersonHistory(RequestProposedPerson rpp, string status, AdminUser user)
{
if (rpp != null && !string.IsNullOrEmpty(status) && user != null)
{
RequestProposedPersonHistory h = new RequestProposedPersonHistory();
h.RequestProposedPerson = rpp;
h.RequestProposedPersonStatus = this.GetRequestProposedPersonStatus(status);
h.AdminUser = user;
h.DateStatusReached = DateTime.Now;
rpp.AddRequestProposedPersonHistory(h);
return this.proposedHistoryRepo.SaveOrUpdate(h);
}
return null;
}
public IList<RequestPerson> GetNominatedRequestPersons()
{
return this.requestPersonsQuery.GetNominatedRequestPersons()
// only RequestPersons whose current status is nominated
.Where(x => x.MostRecentHistory.RequestPersonStatus.RequestPersonStatusName == RequestPersonStatus.NAME_NOMINATED
// only in requests that are currently being screened
&& new string[] { RequestStatus.NAME_SENT_FOR_SCREENING, RequestStatus.NAME_SCREENING_IN_PROGRESS, RequestStatus.NAME_SENT_FOR_CONSOLIDATION }
.Contains(x.Request.CurrentStatus.RequestStatusName))
.ToList();
}
public IList<Career> GetHistoricalCurrentCareers(RequestPerson rp, bool useAuditTrail)
{
if (rp != null && rp.Request != null)
{
// get historical date
DateTime? date = rp.Request.GetLatestScreeningDate();
if (date.HasValue)
{
IList<Career> list = new List<Career>();
// all valid (date-wise) careers; need to figure out the person's correct function/s at given date
IList<Career> candidates = rp.Person.GetCareersAtTimeOf(date.Value);
if (candidates != null && candidates.Any())
{
// if any date-valid careers are marked current, select those
list.Concat(candidates.Where(x => x.IsCurrentCareer));
// if this is an old request and there are no date-valid careers marked current, then select the most recent
// TODO as requests age and their subject profiles advance in career, their careers will no longer be marked current.
// this is a problem for those with multiple functions, as the logic below will only ensure the most recent is returned.
if (list.Count == 0)
{
list.Add(candidates.First());
candidates.RemoveAt(0);
}
if (useAuditTrail)
{
// select the remaining date-valid careers
candidates = candidates.Where(x => !x.IsCurrentCareer).ToList();
// of the remaining candidates, include only if that career was flagged 'current' at time of screening.
// for this we need to check audit trail.
// IMPORTANT: this assumes the that the 'current' careers in the audit trail were correct - not always the case!
IList<int> oldCareerIds = this.auditTasks.GetHistoricalCurrentCareers(rp.Person, date.Value).Select(x => x.Id).ToList();
foreach (Career c in candidates)
if (oldCareerIds.Contains(c.Id)
|| c.IsCurrentCareer) // if our given date is recent, we can rely on the IsCurrentCareer flag
list.Add(c);
}
}
return list;
}
}
return null;
}
public IList<RequestPerson> GetCompletedRequestPersons()
{
return this.requestPersonRepository.GetAll()
.Where(x => !x.Archive
&& !x.Request.Archive
&& x.Request.CurrentStatus != null
&& string.Equals(x.Request.CurrentStatus.RequestStatusName, RequestStatus.NAME_COMPLETED)
&& x.GetScreeningRequestPersonFinalDecision() != null)
.ToList();
}
public RequestUnit SaveRequestUnit(Request request, Unit unit)
{
if (request != null && unit != null)
{
RequestUnit ru = request.AddUnit(unit);
return this.requestUnitRepository.SaveOrUpdate(ru);
}
return null;
}
public RequestUnit ArchiveRequestUnit(Request request, Unit unit)
{
if (request != null && unit != null)
{
RequestUnit ru = request.GetUnit(unit);
if (ru != null)
{
ru.Archive = true;
return this.requestUnitRepository.SaveOrUpdate(ru);
}
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
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 MattCallawayFinalProject
{
/// <summary>
/// Interaction logic for TunerWindow.xaml
/// </summary>
public partial class TunerWindow : Window
{
public TunerWindow()
{
InitializeComponent();
BitmapImage theBitmap = new BitmapImage();
theBitmap.BeginInit();
// y
String basePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"assets\");
String path = System.IO.Path.Combine(basePath, @"images\wood.jpg");
theBitmap.UriSource = new Uri(path, UriKind.Absolute);
theBitmap.EndInit();
//sheetImage = new Image();
woodImage.Source = theBitmap;
}
private void lowEButtonClick(object sender, RoutedEventArgs e)
{
SoundPlayer sound = new SoundPlayer();
Tuner tune = new Tuner();
sound = tune.getLowE();
sound.Play();
}
private void aButtonClick(object sender, RoutedEventArgs e)
{
SoundPlayer sound = new SoundPlayer();
Tuner tune = new Tuner();
sound = tune.getAString();
sound.Play();
}
private void dButtonClick(object sender, RoutedEventArgs e)
{
SoundPlayer sound = new SoundPlayer();
Tuner tune = new Tuner();
sound = tune.getDString();
sound.Play();
}
private void gButtonClick(object sender, RoutedEventArgs e)
{
SoundPlayer sound = new SoundPlayer();
Tuner tune = new Tuner();
sound = tune.getGString();
sound.Play();
}
private void bButtonClick(object sender, RoutedEventArgs e)
{
SoundPlayer sound = new SoundPlayer();
Tuner tune = new Tuner();
sound = tune.getBString();
sound.Play();
}
private void highEButtonClick(object sender, RoutedEventArgs e)
{
SoundPlayer sound = new SoundPlayer();
Tuner tune = new Tuner();
sound = tune.getHighE();
sound.Play();
}
private void closeTuner(object sender, RoutedEventArgs e)
{
Close();
}
}
}
|
using UnityEngine;
using System.Collections;
public class Intake : MonoBehaviour
{
public float speed;
public Rigidbody holding;
public HoldObject payload;
public Transform holdPosition;
public IntakeArm intakeArm;
Quaternion holdRotation = Quaternion.identity;
public void Drop()
{
payload.Drop(holding);
holding = null;
}
public void setSpeed(float s) {
speed = s;
}
public void Grab()
{
holding = payload.Get();
if (holding)
holdRotation = Quaternion.Inverse(payload.transform.rotation) * holding.transform.rotation;
}
public void KickOut()
{
if (holding)
holding.transform.position = payload.transform.position;
holding = null;
}
void Update()
{
//Debug.Log(intakeArm.Angle);
if (payload.Get() != null && speed > 0 && holding == null && intakeArm.Angle > -5) {
Grab();
}
if (holding)
{
holding.transform.position = holdPosition.transform.position;
holding.transform.rotation = holdPosition.transform.rotation * holdRotation;
}
}
}
|
namespace _1.RefactorVariableNaming
{
using System;
using System.Linq;
class Size
{
//fields
private double width;
private double height;
//I use another width and height because I need them in the override ToString() method
private double widthAfterRotation;
private double heightAfterRotation;
//constructors
public Size(double inputWidth, double inputHeight)
{
this.width = inputWidth;
this.height = inputHeight;
}
//properties
public double HeightAfterRotation
{
get
{
return this.heightAfterRotation;
}
set
{
this.heightAfterRotation = value;
}
}
public double WidthAfterRotation
{
get
{
return this.widthAfterRotation;
}
set
{
this.widthAfterRotation = value;
}
}
public double Height
{
get
{
return this.height;
}
set
{
this.height = value;
}
}
public double Width
{
get
{
return this.width;
}
set
{
this.width = value;
}
}
//methods
public Size GetRotatedSize(Size figureSize, double rotatedFigureAngle)
{
WidthAfterRotation =
Math.Abs(Math.Cos(rotatedFigureAngle)) * figureSize.Width +
Math.Abs(Math.Sin(rotatedFigureAngle)) * figureSize.Height;
HeightAfterRotation =
Math.Abs(Math.Sin(rotatedFigureAngle)) * figureSize.Width +
Math.Abs(Math.Cos(rotatedFigureAngle)) * figureSize.Height;
figureSize = new Size(WidthAfterRotation, HeightAfterRotation);
return figureSize;
}
public override string ToString()
{
return string.Format("The size of the figure after rotation by the given angle is width: {0} and height: {1}",
this.WidthAfterRotation, this.HeightAfterRotation);
}
}
}
|
using System;
namespace Admin.ViewModels
{
public class JoinChatModel
{
public int ChatId {get;set;}
}
} |
using UnityEngine;
using System.Collections;
public class DragAndDrop
{
public float time;
public Vector3 oldPos;
public bool Dragged(GameObject target)
{
if (Camera.main.ScreenToWorldPoint(Input.mousePosition).x < target.transform.position.x + 0.5 &&
Camera.main.ScreenToWorldPoint(Input.mousePosition).x > target.transform.position.x - 0.5 &&
Camera.main.ScreenToWorldPoint(Input.mousePosition).y < target.transform.position.y + 2 &&
Camera.main.ScreenToWorldPoint(Input.mousePosition).y > target.transform.position.y &&
Input.GetMouseButtonDown(0))
{
time = Time.time;
oldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
if (Camera.main.ScreenToWorldPoint(Input.mousePosition).x < target.transform.position.x + 0.5 &&
Camera.main.ScreenToWorldPoint(Input.mousePosition).x > target.transform.position.x - 0.5 &&
Camera.main.ScreenToWorldPoint(Input.mousePosition).y < target.transform.position.y + 2 &&
Camera.main.ScreenToWorldPoint(Input.mousePosition).y > target.transform.position.y &&
oldPos == Camera.main.ScreenToWorldPoint(Input.mousePosition) && Input.GetMouseButton(0))
{
if (Time.time - time > 0.01)
{
return true;
}
}
return false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using TinhLuongDAL;
using TinhLuongINFO;
namespace TinhLuongBLL
{
public class BaoCaoChungBLL
{
BaoCaoChungDAL dal = new BaoCaoChungDAL();
public List<DM_DonVi> Get_ListTenDonVi(String donviId)
{
return dal.Get_ListTenDonVi(donviId);
}
public List<DM_DonVi> Get_ListTenTram(string donviId)
{
return dal.Get_ListTenTram(donviId);
}
public List<NhanVien> Get_ListTenNhanVien(string donviId)
{
return dal.Get_ListTenNhanVien(donviId);
}
public DataTable RequestTableNhanVien(decimal nam, decimal thang, string nhanSuID, string DonViID_Session,string type)
{
return dal.RequestTableNhanVien(nam, thang, nhanSuID,DonViID_Session,type);
}
public DataTable GetSourceRptDSChiTiet_CSHT(string donviId, decimal nam, decimal thang)
{
return dal.GetSourceRptDSChiTiet_CSHT(donviId, nam, thang);
}
public DataTable GetSourceRptDSChiTietKKLD_CSHT(string donviId, decimal nam, decimal thang)
{
return dal.GetSourceRptDSChiTietKKLD_CSHT(donviId, nam,thang);
}
public DataTable GetRptKy1_AgriBank(decimal nam, decimal thang)
{
return dal.GetRptKy1_AgriBank(nam, thang);
}
public DataTable GetRptKy1_VietComBank(decimal nam, decimal thang)
{
return dal.GetRptKy1_VietComBank(nam, thang);
}
public DataTable GetRptKy1_ViettinBank(decimal nam, decimal thang)
{
return dal.GetRptKy1_ViettinBank(nam, thang);
}
public DataTable GetRpt_AgriBank(decimal nam, decimal thang)
{
return dal.GetRpt_AgriBank(nam, thang);
}
public DataTable GetRpt_VietComBank(decimal nam, decimal thang)
{
return dal.GetRpt_VietComBank(nam, thang);
}
public DataTable GetRpt_ViettinBank(decimal nam, decimal thang)
{
return dal.GetRpt_ViettinBank(nam, thang);
}
public List<DM_LoaiBoSung> GetLoaiBoSung(int Nam)
{
return dal.GetLoaiBoSung(Nam);
}
public DataTable GetSourceRptDSBS(string donviId, decimal nam, int loai)
{
return dal.GetSourceRptDSBS(donviId, nam, loai);
}
public DataTable GetRptAgriBankBoSung(int nam, int loai)
{
return dal.GetRptAgriBankBoSung(nam, loai);
}
public DataTable GetRptVietComBankBoSung(int nam, int loai)
{
return dal.GetRptVietComBankBoSung(nam, loai);
}
public DataTable GetRptViettinBankBoSung(int nam, int loai)
{
return dal.GetRptViettinBankBoSung(nam, loai);
}
public DataTable GetRptNhanTienMatBoSung(int nam, int loai)
{
return dal.GetRptNhanTienMatBoSung(nam, loai);
}
public bool ActiveLuong(int Nam, int Thang, int loai)
{
return dal.ActiveLuong(Nam, Thang, loai);
}
}
}
|
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace Inventory.Data.Services
{
partial class DataServiceBase
{
public async Task<OrderStatusHistory> GetOrderStatusHistoryAsync(int orderId, int orderLine)
{
return await _dataSource.OrderStatusHistories
.Where(r => r.OrderId == orderId && r.OrderLine == orderLine)
.FirstOrDefaultAsync();
}
public async Task<IList<OrderStatusHistory>> GetOrderStatusHistorysAsync(int skip, int take, DataRequest<OrderStatusHistory> request)
{
IQueryable<OrderStatusHistory> items = GetOrderStatusHistorys(request);
// Execute
var records = await items.Skip(skip).Take(take)
.AsNoTracking().ToListAsync();
return records;
}
public async Task<IList<OrderStatusHistory>> GetOrderStatusHistorysKeysAsync(int skip, int take, DataRequest<OrderStatusHistory> request)
{
IQueryable<OrderStatusHistory> items = GetOrderStatusHistorys(request);
// Execute
var records = await items.Skip(skip).Take(take)
.Select(r => new OrderStatusHistory
{
OrderId = r.OrderId,
OrderLine = r.OrderLine
})
.AsNoTracking()
.ToListAsync();
return records;
}
private IQueryable<OrderStatusHistory> GetOrderStatusHistorys(DataRequest<OrderStatusHistory> request)
{
IQueryable<OrderStatusHistory> items = _dataSource.OrderStatusHistories;
// Query
// TODO: Not supported
//if (!String.IsNullOrEmpty(request.Query))
//{
// items = items.Where(r => r.SearchTerms.Contains(request.Query.ToLower()));
//}
// Where
if (request.Where != null)
{
items = items.Where(request.Where);
}
// Order By
if (request.OrderBy != null)
{
items = items.OrderBy(request.OrderBy);
}
if (request.OrderByDesc != null)
{
items = items.OrderByDescending(request.OrderByDesc);
}
return items;
}
public async Task<int> GetOrderStatusHistoryCountAsync(DataRequest<OrderStatusHistory> request)
{
IQueryable<OrderStatusHistory> items = _dataSource.OrderStatusHistories;
// Query
// TODO: Not supported
//if (!String.IsNullOrEmpty(request.Query))
//{
// items = items.Where(r => r.SearchTerms.Contains(request.Query.ToLower()));
//}
// Where
if (request.Where != null)
{
items = items.Where(request.Where);
}
return await items.CountAsync();
}
public async Task<int> UpdateOrderStatusHistoryAsync(OrderStatusHistory orderStatusHistory)
{
if (orderStatusHistory.OrderLine > 0)
{
_dataSource.Entry(orderStatusHistory).State = EntityState.Modified;
}
else
{
orderStatusHistory.OrderLine = _dataSource.OrderStatusHistories
.Where(r => r.OrderId == orderStatusHistory.OrderId)
.Select(r => r.OrderLine)
.DefaultIfEmpty(0)
.Max() + 1;
// TODO:
//OrderStatusHistory.CreateOn = DateTime.UtcNow;
_dataSource.Entry(orderStatusHistory).State = EntityState.Added;
}
// TODO:
//OrderStatusHistory.LastModifiedOn = DateTime.UtcNow;
//OrderStatusHistory.SearchTerms = OrderStatusHistory.BuildSearchTerms();
return await _dataSource.SaveChangesAsync();
}
public async Task<int> DeleteOrderStatusHistoryAsync(params OrderStatusHistory[] OrderStatusHistory)
{
_dataSource.OrderStatusHistories.RemoveRange(OrderStatusHistory);
return await _dataSource.SaveChangesAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace CommonQ
{
class RandomString
{
public static Random Rgen = new Random(System.Environment.TickCount);
static Dictionary<string, string> Built = new Dictionary<string, string>();
static public string Next(int lenth, string charset)
{
if (charset == null)
{
charset = ".";
}
if (charset == "")
{
return "";
}
else
{
string Loopup = GetLookUp(charset);
StringBuilder sb = new StringBuilder(lenth);
for (int i = 0; i < lenth; ++i)
{
sb.Insert(i, Loopup[Rgen.Next(0, Loopup.Length)]);
}
return sb.ToString();
}
}
static private string GetLookUp(string charset)
{
try
{
if (!Built.ContainsKey(charset))
{
StringBuilder sb = new StringBuilder(256);
for (int Loop = 1; Loop <= 255; ++Loop)
{
sb.Insert(Loop - 1, (char)Loop);
}
string s = Regex.Replace(sb.ToString(), "[^" + charset + "]", "");
Built.Add(charset, s);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
return Built[charset];
}
}
}
|
namespace carto.Models
{
public class CmdbItemCategory
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public CmdbItemCategory(long id, string name)
{
Id = id;
Name = name;
}
}
} |
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using momo.Infrastructure.Watcher;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace momo.Middleware
{
public class PerformanceLogMiddleware
{
private readonly ILogger _logger;
private readonly RequestDelegate _request;
public PerformanceLogMiddleware(ILogger<PerformanceLogMiddleware> logger,RequestDelegate requestDelegate)
{
_logger = logger;
_request = requestDelegate;
}
/// <summary>
/// 注入中间件到HttpContext中
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task InvokeAsync(HttpContext context)
{
var profiler = new StopwatchProfiler();
profiler.Start();
await _request(context);
profiler.Stop();
_logger.LogInformation("TraceId:{TraceId}, RequestMethod:{RequestMethod}, RequestPath:{RequestPath}, ElapsedMilliseconds:{ElapsedMilliseconds}, Response StatusCode: {StatusCode}",
context.TraceIdentifier, context.Request.Method, context.Request.Path, profiler.ElapsedMilliseconds, context.Response.StatusCode);
}
}
}
|
using Pe.Stracon.Politicas.Infraestructura.CommandModel.General;
using Pe.Stracon.Politicas.Infraestructura.Core.CommandContract.General;
using Pe.Stracon.Politicas.Infraestructura.Repository.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.Politicas.Infraestructura.Repository.Command.General
{
/// <summary>
/// Implementación del Repositorio de Plantilla Notificacion
/// </summary>
/// <remarks>
/// Creación : GMD 20150617 <br />
/// </remarks>
public class PlantillaNotificacionEntityRepository : ComandRepository<PlantillaNotificacionEntity>, IPlantillaNotificacionEntityRepository
{
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Linq;
namespace PersonalNotes
{
public partial class Form2 : Form
{
public string f1 { get; set; }
public string f4 { get; set; }
public string f5 { get; set; }
string pathX;
public Form2(Form1 f1, string s1, Form4 f4, string s4, Form5 f5, string s5)
{
InitializeComponent();
this.f1 = s1;
this.f4 = s4;
this.f5 = s5;
label2.Text = s1;
textBox1.Text = s4;
textBox2.Text = s5;
pathX = "";
}
private void label2_Click(object sender, EventArgs e)
{
}
private void калькуляторToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 f3 = new Form3();
f3.Show();
}
private void категориюToolStripMenuItem_Click(object sender, EventArgs e)
{
Form4 f4 = new Form4();
f4.Show();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void категориюToolStripMenuItem2_Click(object sender, EventArgs e)
{
Form4 f4 = new Form4();
f4.Show();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void темуЗаметкиToolStripMenuItem_Click(object sender, EventArgs e)
{
Form5 f5 = new Form5();
f5.Show();
}
private void темуToolStripMenuItem_Click(object sender, EventArgs e)
{
Form5 f5 = new Form5();
f5.Show();
}
private void назадToolStripMenuItem_Click(object sender, EventArgs e)
{
if (richTextBox1.CanUndo == true)
{
richTextBox1.Undo();
richTextBox1.ClearUndo();
}
}
private void вырезатьToolStripMenuItem_Click(object sender, EventArgs e)
{
if (richTextBox1.SelectionLength > 0)
{
richTextBox1.Cut();
}
}
private void копироватьToolStripMenuItem_Click(object sender, EventArgs e)
{
if (richTextBox1.SelectionLength > 0)
{
richTextBox1.Copy();
}
}
private void вставитьToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{
richTextBox1.Paste();
}
}
private void найтиToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void заменитьToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void выбратьВсёToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.SelectAll();
}
private void сохранитьToolStripMenuItem_Click(object sender, EventArgs e)
{
if (pathX != "")
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Apache Open Office (*.rtf)|*.rtf|Notepad (*.txt)|*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
pathX = sfd.FileName;
richTextBox1.SaveFile(pathX);
}
else
{
richTextBox1.SaveFile(pathX);
MessageBox.Show("Saved.");
}
}
}
private void сохранитьКакToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Apache Open Office (*.rtf)|*.rtf|Notepad (*.txt)|*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
pathX = sfd.FileName;
richTextBox1.SaveFile(pathX);
}
}
private void закрытьПриложениеToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
|
using AutoMapper;
using XH.Commands.Projects;
using XH.Domain.Projects;
using XH.Infrastructure.Mapper;
namespace XH.Command.Handlers.Configs
{
public class ProjectsMapperRegistrar: IAutoMapperRegistrar
{
public void Register(IMapperConfigurationExpression cfg)
{
cfg.CreateMap<CreateProjectCommand, Project>();
cfg.CreateMap<UpdateProjectCommand, Project>();
//cfg.CreateMap<CreateProjectUserCommand, ProjectUser>();
//cfg.CreateMap<UpdateProjectUserCommand, ProjectUser>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Value convertingValue;
Value convertedValue;
Converter converter = new Converter();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
saveButton.Enabled = false;
}
private void lengthInitgroupBox_Enter(object sender, EventArgs e)
{
lengthResGroupBox.Enabled = true;
massResGroupBox.Enabled = false;
timeResGroupBox.Enabled = false;
var massRadioButtons = massInitGroupBox.Controls.OfType<RadioButton>();
foreach (RadioButton rb in massRadioButtons)
{
rb.Checked = false;
}
var timeRadioButtons = timeInitGroupBox.Controls.OfType<RadioButton>();
foreach (RadioButton rb in timeRadioButtons)
{
rb.Checked = false;
}
}
private void inputTextBox_TextChanged(object sender, EventArgs e)
{
if (inputTextBox.Text.StartsWith(".") || inputTextBox.Text.StartsWith(","))
{
inputTextBox.Text = new string(inputTextBox.Text.SkipWhile(c => c == '.' || c == ',').ToArray());
}
}
private void convertButton_Click(object sender, EventArgs e)
{
errorLabel.Text = "";
String convertFromRadioButton = GetConvertingFromRadioButton();
String convertToRadioButton = GetConvertingToRadioButton();
if (convertFromRadioButton == null || convertToRadioButton == null)
{
errorLabel.Text = "Ошибка!!! Нужно указать единицы измерения";
saveButton.Enabled = false;
return;
}
try {
Double initialValue = Convert.ToDouble(inputTextBox.Text.Replace('.', ','));
convertingValue = new Value(initialValue, getConvetingFromUnitType(convertFromRadioButton));
convertedValue = converter.Convert(convertingValue, getConvetingToUnitType(convertToRadioButton));
resultTextBox.Text = convertedValue.GetVal().ToString();
saveButton.Enabled = true;
} catch (FormatException) {
errorLabel.Text = "Ошибка!!!";
saveButton.Enabled = false;
}
}
private void clearButton_Click(object sender, EventArgs e)
{
inputTextBox.Text = "";
resultTextBox.Text = "";
saveButton.Enabled = false;
}
private void massInitGroupBox_Enter(object sender, EventArgs e)
{
massResGroupBox.Enabled = true;
lengthResGroupBox.Enabled = false;
timeResGroupBox.Enabled = false;
var lengthRadioButtons = lengthInitGroupBox.Controls.OfType<RadioButton>();
foreach (RadioButton rb in lengthRadioButtons)
{
rb.Checked = false;
}
var timeRadioButtons = timeInitGroupBox.Controls.OfType<RadioButton>();
foreach (RadioButton rb in timeRadioButtons)
{
rb.Checked = false;
}
}
private void timeInitGroupBox_Enter(object sender, EventArgs e)
{
timeResGroupBox.Enabled = true;
massResGroupBox.Enabled = false;
lengthResGroupBox.Enabled = false;
var massRadioButtons = massInitGroupBox.Controls.OfType<RadioButton>();
foreach (RadioButton rb in massRadioButtons)
{
rb.Checked = false;
}
var lengthRadioButtons = lengthInitGroupBox.Controls.OfType<RadioButton>();
foreach (RadioButton rb in lengthRadioButtons)
{
rb.Checked = false;
}
}
private void inputTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.') && (e.KeyChar != ','))
{
e.Handled = true;
}
// only allow one decimal point
if ((e.KeyChar == '.' || e.KeyChar == ',') &&
((sender as TextBox).Text.IndexOf('.') > -1 || (sender as TextBox).Text.IndexOf(',') > -1))
{
e.Handled = true;
}
}
private String GetConvertingFromRadioButton()
{
var lengthRadioButtons = lengthInitGroupBox.Controls.OfType<RadioButton>();
foreach (RadioButton rb in lengthRadioButtons)
{
if (rb.Checked)
{
return rb.Name;
}
}
var massRadioButtons = massInitGroupBox.Controls.OfType<RadioButton>();
foreach (RadioButton rb in massRadioButtons)
{
if (rb.Checked)
{
return rb.Name;
}
}
var timeRadioButtons = timeInitGroupBox.Controls.OfType<RadioButton>();
foreach (RadioButton rb in timeRadioButtons)
{
if (rb.Checked)
{
return rb.Name;
}
}
return null;
}
private UnitTypes getConvetingFromUnitType(String checkedRadioButtinName)
{
switch (checkedRadioButtinName)
{
case "mmInitRadioButton":
return UnitTypes.Millimeter;
case "cmInitRadioButton":
return UnitTypes.Centimeter;
case "dmInitRadioButton":
return UnitTypes.Decimeter;
case "mInitRadioButton":
return UnitTypes.Meter;
case "kmInitRadioButton":
return UnitTypes.Kilometer;
case "gInitRadioButton":
return UnitTypes.Gramm;
case "kgInitRadioButton":
return UnitTypes.Kilogramm;
case "centnerInitRadioButton":
return UnitTypes.Centner;
case "tInitRadioButton":
return UnitTypes.Ton;
case "secInitRadioButton":
return UnitTypes.Second;
case "minInitRadioButton":
return UnitTypes.Minute;
case "hourInitRadioButton":
return UnitTypes.Hour;
default: return UnitTypes.Nothing;
}
}
private String GetConvertingToRadioButton()
{
if (lengthResGroupBox.Enabled == true)
{
var lengthRadioButtons = lengthResGroupBox.Controls.OfType<RadioButton>();
foreach (RadioButton rb in lengthRadioButtons)
{
if (rb.Checked)
{
return rb.Name;
}
}
}
if (massResGroupBox.Enabled == true)
{
var massRadioButtons = massResGroupBox.Controls.OfType<RadioButton>();
foreach (RadioButton rb in massRadioButtons)
{
if (rb.Checked)
{
return rb.Name;
}
}
}
if (timeResGroupBox.Enabled == true)
{
var timeRadioButtons = timeResGroupBox.Controls.OfType<RadioButton>();
foreach (RadioButton rb in timeRadioButtons)
{
if (rb.Checked)
{
return rb.Name;
}
}
}
return null;
}
private UnitTypes getConvetingToUnitType(String checkedRadioButtinName)
{
switch (checkedRadioButtinName)
{
case "mmResRadioButton":
return UnitTypes.Millimeter;
case "cmResRadioButton":
return UnitTypes.Centimeter;
case "dmResRadioButton":
return UnitTypes.Decimeter;
case "mResRadioButton":
return UnitTypes.Meter;
case "kmResRadioButton":
return UnitTypes.Kilometer;
case "gResRadioButton":
return UnitTypes.Gramm;
case "kgResRadioButton":
return UnitTypes.Kilogramm;
case "centnerResRadioButton":
return UnitTypes.Centner;
case "tResRadioButton":
return UnitTypes.Ton;
case "secResRadioButton":
return UnitTypes.Second;
case "minResRadioButton":
return UnitTypes.Minute;
case "hourResRadioButton":
return UnitTypes.Hour;
default: return UnitTypes.Nothing;
}
}
private void saveButton_Click(object sender, EventArgs e)
{
Stream myStream;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
StreamWriter myWritet = new StreamWriter(myStream);
try
{
myWritet.Write(inputTextBox.Text + " " + resultTextBox.Text + " \r\n");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
myWritet.Close();
}
myWritet.Close();
}
}
}
private void resultTextBox_TextChanged(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IoTSharp.Cicada.Models
{
public class EnumKeyValue
{
public string EnumName { get; set; }
public object EnumValue { get; set; }
}
public static class EnumExts
{
public static void BindingEnum<T>(this System.Windows.Forms.BindingSource source) where T:Enum
{
var t = typeof(T);
List<EnumKeyValue> values = new List<EnumKeyValue>();
Enum.GetNames(t).ToList().ForEach(s => values.Add(new EnumKeyValue() { EnumName = s, EnumValue = Enum.Parse(t, s) }));
source.DataSource = values;
}
}
}
|
using JustOffer.MenuDatabase;
using JustOffer.OrderManagement;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
namespace JustOffer.Offer
{
public class EligibilityRuleProcessor
{
protected List<BasketItem> Items { get; set; }
public EligibilityRule Rule { get; set; }
public Basket Basket { get; set; }
public EligibilityRuleProcessor(EligibilityRule rule, Basket basket)
{
Rule = rule;
Items = new List<BasketItem>();
Basket = basket;
}
public virtual List<BasketItem> GetItems()
{
return Items;
}
public bool ProcessItems()
{
var itemCount = Items.Count;
ProcessItemEligibilityRules();
// return true if items have been added
return Items.Count > itemCount;
}
public void ProcessItemEligibilityRules()
{
List<BasketItem> eligibleItems = new List<BasketItem>();
foreach (var criteria in Rule.ItemCriteria)
{
//process category
foreach (var category in criteria.Category)
{
var matchingItems = GetItemsInCategory(category);
for (var i = 0; i < matchingItems.Count; i++)
{
if (!eligibleItems.Where(e => e.BasketId == matchingItems[i].BasketId).Any())
{
eligibleItems.Add(matchingItems[i]);
}
}
}
//process base products
foreach (var baseProduct in criteria.BaseProducts)
{
var matchingItems = GetItemsInBaseProduct(baseProduct);
for (var i = 0; i < matchingItems.Count; i++)
{
if (!eligibleItems.Where(e => e.BasketId == matchingItems[i].BasketId).Any())
{
eligibleItems.Add(matchingItems[i]);
}
}
}
AddEligibleItemsWithinRuleRange(criteria, eligibleItems);
}
}
public void AddEligibleItemsWithinRuleRange(ItemCriteria criteria, List<BasketItem> eligibleItems)
{
var newItems =
eligibleItems.Where(e => !Items
.Select(i => i.BasketId)
.ToList()
.Contains(e.BasketId))
.ToList();
if (newItems.Count < criteria.MinAmount)
return;
int remainder = newItems.Count % criteria.MinAmount;
for (int amountAdded = 0; amountAdded < criteria.MaxAmount; amountAdded++)
{
if ((newItems.Count - amountAdded) < remainder)
break;
Items.Add(newItems[amountAdded]);
}
}
public List<BasketItem> GetItemsInCategory(string category)
{
var matchingItems = Basket.GetItems()
.Where(i => i.Item.Categories
.Select(c => c.CategoryName)
.ToList()
.Contains(category))
.ToList();
return matchingItems;
}
public List<BasketItem> GetItemsInBaseProduct(string baseProduct)
{
var matchingItems = Basket.GetItems()
.Where(i => i.Item.BaseProducts
.Select(b => b.ProductName)
.ToList()
.Contains(baseProduct))
.ToList();
return matchingItems;
}
}
public static class CloningExtensionMethod
{
/// <summary>
/// Perform a deep Copy of the object, using Json as a serialisation method.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T CloneJson<T>(this T source)
{
// Don't serialize a null object, simply return the default for that object
if (object.ReferenceEquals(source, null))
{
return default(T);
}
// initialize inner objects individually
// for example in default constructor some list property initialized with some values,
// but in 'source' these items are cleaned -
// without ObjectCreationHandling.Replace default constructor values will be added to result
var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings);
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
//TODO: Add other using statements here
namespace com.Sconit.Entity.ISS
{
public partial class IssueAddress
{
#region Non O/R Mapping Properties
//TODO: Add Non O/R Mapping Properties here.
private string _parentIssueAddressCode;
[Display(Name = "ParentIssueAddress", ResourceType = typeof(Resources.ISS.IssueAddress))]
public string ParentIssueAddressCode
{
get
{
if (string.IsNullOrEmpty(_parentIssueAddressCode) && this.ParentIssueAddress != null)
{
_parentIssueAddressCode = this.ParentIssueAddress.Code;
}
return _parentIssueAddressCode;
}
set
{
_parentIssueAddressCode = value;
}
}
private string _parentIssueAddressDescription;
[Display(Name = "ParentIssueAddressDescription", ResourceType = typeof(Resources.ISS.IssueAddress))]
public string ParentIssueAddressDescription
{
get
{
if (string.IsNullOrEmpty(_parentIssueAddressDescription) && this.ParentIssueAddress != null)
{
_parentIssueAddressDescription = this.ParentIssueAddress.Description;
}
return _parentIssueAddressDescription;
}
set
{
_parentIssueAddressDescription = value;
}
}
public string CodeDescription
{
get
{
if (string.IsNullOrWhiteSpace(this.Code) && string.IsNullOrWhiteSpace(this.Description))
{
return string.Empty;
}
else if (string.IsNullOrWhiteSpace(this.Code))
{
return this.Description;
}
else if (string.IsNullOrWhiteSpace(this.Description))
{
return this.Code;
}
return this.Code + "[" + this.Description + "]";
}
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace wsb_agent_win
{
public enum SnackType { Chips, Peanuts, Breadsticks };
public enum DrinkType { Soda, Still, StillWater, SodaWater };
public enum VendingMachineType { Type1, Type2, Type3 };
}
|
using System.Collections.Generic;
using TechEval.DataContext;
namespace TechEval.Commands.Results
{
public class FileUploadCommandResult
{
public bool IsOk { get; set; }
public List<ImportLog> FailedRecords;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace bdd
{
public class BoringCalculator
{
public double Add(double a, double b)
{
return a + b;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Proyecto_AppMoviles_
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PaginaInicioFlyout : ContentPage
{
public ListView ListView;
public PaginaInicioFlyout()
{
InitializeComponent();
BindingContext = new PaginaInicioFlyoutViewModel();
lblUsuario.Text = "";
ListView = MenuItemsListView;
}
class PaginaInicioFlyoutViewModel : INotifyPropertyChanged
{
public ObservableCollection<PaginaInicioFlyoutMenuItem> MenuItems { get; set; }
public PaginaInicioFlyoutViewModel()
{
MenuItems = new ObservableCollection<PaginaInicioFlyoutMenuItem>(new[]
{
new PaginaInicioFlyoutMenuItem {Id=0, Title="Inicio"},
new PaginaInicioFlyoutMenuItem { Id = 1, Title = "Perfil" },
new PaginaInicioFlyoutMenuItem { Id = 2, Title = "Citas" },
//new PaginaInicioFlyoutMenuItem { Id = 2, Title = "Pagos" },
new PaginaInicioFlyoutMenuItem { Id = 3, Title = "Contacto" },
new PaginaInicioFlyoutMenuItem { Id = 4, Title = "Cerrar sesión" }
});
}
#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged == null)
return;
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
} |
namespace SignalRandUnityDI.Models
{
public class IndexViewModel : IIndexViewModel
{
private int _clickTotal;
public int ClickTotal => _clickTotal;
public void AddToTotal()
{
// Just so it's thread safe
lock(this)
{
_clickTotal++;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProgrammingContest.Library
{
class Graph
{
public const long InfCost = (long)1e18;
public struct Edge : IComparable<Edge>
{
public int To { get; }
public long Cost { get; }
public Edge(int to, long cost)
{
this.To = to;
this.Cost = cost;
}
public int CompareTo(Edge other)
=> Math.Sign(this.Cost - other.Cost);
}
public List<Edge>[] ListGraph { get; }
public Graph(int N)
{
this.ListGraph = Enumerable.Range(0, N)
.Select(e => new List<Edge>())
.ToArray();
}
public void AddEdge(int from, int to, long cost)
=> this.ListGraph[from].Add(new Edge(to, cost));
public long[,] MatrixGraph()
{
int N = this.ListGraph.Length;
var ret = new long[N, N];
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
ret[i, j] = InfCost;
}
ret[i, i] = 0;
}
for (int from = 0; from < N; from++)
{
foreach (var e in this.ListGraph[from])
{
ret[from, e.To] = e.Cost;
}
}
return ret;
}
public long[,] WarshallFloyd()
{
int N = this.ListGraph.Length;
var mat = this.MatrixGraph();
for (int k = 0; k < N; k++)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
mat[i, j] = Math.Min(mat[i, j], mat[i, k] + mat[k, j]);
}
}
}
return mat;
}
public long[] DijkstraByMatrix(int st)
{
int N = this.ListGraph.Length;
var mat = this.MatrixGraph();
var ret = new long[N];
for (int i = 0; i < N; i++)
{
ret[i] = InfCost;
}
var vis = new bool[N];
ret[st] = 0;
while (true)
{
int idx = -1;
for (int i = 0; i < N; i++)
{
if (vis[i])
{
continue;
}
if (idx == -1)
{
idx = i;
}
if (ret[i] < ret[idx])
{
idx = i;
}
}
if (idx == -1)
{
break;
}
vis[idx] = true;
for (int i = 0; i < N; i++)
{
ret[i] = Math.Min(ret[i], ret[idx] + mat[idx, i]);
}
}
return ret;
}
public int[] TopologicalSort()
{
int N = this.ListGraph.Length;
var tsort = new List<int>();
var inCnt = new int[N];
for (int from = 0; from < N; from++)
{
foreach (var e in this.ListGraph[from])
{
inCnt[e.To]++;
}
}
var q = new Queue<int>();
for (int i = 0; i < N; i++)
{
if (inCnt[i] == 0)
{
q.Enqueue(i);
}
}
while (q.Count > 0)
{
int now = q.Dequeue();
tsort.Add(now);
foreach (var e in this.ListGraph[now])
{
inCnt[e.To]--;
if (inCnt[e.To] == 0)
{
q.Enqueue(e.To);
}
}
}
return tsort.Count == N ? tsort.ToArray()
: null;
}
}
}
|
using System;
using System.Security;
using Microsoft.AspNetCore.Http;
using Zesty.Core.Entities.Settings;
namespace Zesty.Core.Business
{
public static class Authorization
{
private static NLog.Logger logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
private static IStorage storage = StorageManager.Storage;
private static string setDomainResource = Settings.Get("SetDomainResourceName", "/system.domain.api");
private static string setDomainResourceController = Settings.Get("SetDomainResourceController", "/api/System/Domain");
private static string setDomainListResourceController = Settings.Get("SetDomainListResourceController", "/api/System/Domains");
public static void Logout(HttpContext context)
{
Context.Current.Reset();
context.Session.Clear();
context.Response.Headers.Clear();
context.Request.Headers.Clear();
}
internal static bool CanAccess(string path, Entities.User user, string method = null)
{
//TODO add cache
bool isPublic = StorageManager.Storage.IsPublicResource(path, method);
if (isPublic)
{
logger.Info($"The resource {path} is public");
return true;
}
if (user == null)
{
logger.Warn($"Access denied for resource {path} for null user");
throw new SecurityException(Messages.AccessDenied);
}
if (user.Domain == null && path != setDomainResource && path != setDomainResourceController && path != setDomainListResourceController)
{
logger.Warn($"Access denied for resource {path} for null user.Domain");
throw new SecurityException(Messages.AccessDenied);
}
//TODO add cache
return storage.CanAccess(path, user, method);
}
internal static string GetToken(string sessionId, bool reusable)
{
string tokenValue = (Guid.NewGuid().ToString() + Guid.NewGuid().ToString()).Replace("-", "");
storage.SaveToken(Context.Current.User, sessionId, tokenValue, reusable);
return tokenValue;
}
internal static bool RequireToken(string path, string method = null)
{
//TODO add cache
return storage.RequireToken(path, method);
}
internal static bool IsValid(Guid userId, string sessionId, string tokenValue)
{
return storage.IsValid(userId, sessionId, tokenValue);
}
}
}
|
using EPI.Arrays;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EPI.UnitTests.Arrays
{
[TestClass]
public class Rotate2DArrayUnitTest
{
[TestMethod]
public void Rotate2DMatrixTest()
{
int[,] matrix1 = new int[1, 1] { { 1 } };
Rotate2DArray.Rotate(matrix1);
matrix1.Should().Equal(new int[1, 1] { { 1 } });
int[,] matrix2 = new int[2, 2]
{
{ 1, 2 },
{ 3, 4 }
};
Rotate2DArray.Rotate(matrix2);
matrix2.Should().Equal(new int[2, 2] { { 3, 1 }, { 4, 2 } });
int[,] matrix3 = new int[3, 3]
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
Rotate2DArray.Rotate(matrix3);
matrix3.Should().Equal(new int[3, 3] { { 7, 4, 1 }, { 8, 5, 2 }, { 9, 6, 3 } });
int[,] matrix4 = new int[4, 4]
{
{ 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10, 11, 12 },
{ 13, 14, 15, 16 }
};
Rotate2DArray.Rotate(matrix4);
matrix4.Should().Equal(new int[4, 4] { { 13, 9, 5, 1 }, { 14, 10, 6, 2 }, { 15, 11, 7, 3 }, { 16, 12, 8, 4 } });
int[,] matrix5 = new int[5, 5]
{
{ 1 , 2 , 3 , 4 , 5 },
{ 6 , 7 , 8 , 9 , 10 },
{ 11, 12, 13, 14, 15 },
{ 16, 17, 18, 19, 20 },
{ 21, 22, 23, 24, 25 }
};
Rotate2DArray.Rotate(matrix5);
matrix5.Should().Equal(new int[5, 5] {
{ 21, 16, 11, 6 , 1 },
{ 22, 17, 12, 7 , 2 },
{ 23, 18, 13, 8 , 3 },
{ 24, 19, 14, 9 , 4 },
{ 25, 20, 15, 10, 5 }
});
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Patient : MonoBehaviour
{
public string p_name;
public int age;
public string gender;
public string diagnosis;
private bool isCured = false;
private int treatedSymptoms;
public Symptom[] symptoms;
public float health = 100;
public GameObject curedEffect;
public Animator animator;
private void Start()
{
treatedSymptoms = symptoms.Length;
}
public void TreatSymptom(string[] usedFor, float[] dosages)
{
float damage = CheckDosageAge(dosages);
foreach(Symptom sym in symptoms)
{
foreach(string usage in usedFor)
{
if(sym.s_name == usage)
{
sym.Treat(damage);
}
}
if(sym.IsTreated())
{
//Debug.Log(sym.name + " is treated!");
treatedSymptoms--;
}
}
}
private float CheckDosageAge(float[] dosages)
{
if (age < 13)
{
// Children
return dosages[0];
}
else if (age >= 13 && age < 20)
{
// Teens
return dosages[1];
}
else if (age >= 20 && age < 50)
{
// Adults
return dosages[2];
}
else if (age >= 50)
{
// Elderly
return dosages[3];
}
else
{
return dosages[0];
}
}
public bool CheckIsCured()
{
foreach (Symptom sym in symptoms)
{
if(sym.IsTreated())
{
isCured = true;
// animator.SetBool("isCured", isCured);
}
else
{
isCured = false;
break;
}
}
return isCured;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassicCraft
{
class MightyRageBuff : Effect
{
public static int LENGTH = 20;
public MightyRageBuff(Player p, double baseLength = 20)
: base(p, p, true, baseLength, 1)
{
}
public override void StartBuff()
{
base.StartBuff();
Player.Ressource += Player.Sim.random.Next(45, 347);
Player.BonusAttributes.SetValue(Attribute.Strength, Player.BonusAttributes.GetValue(Attribute.Strength) + 60);
Player.BonusAttributes.SetValue(Attribute.AP, Player.BonusAttributes.GetValue(Attribute.AP) + 120);
}
public override void EndBuff()
{
base.EndBuff();
Player.BonusAttributes.SetValue(Attribute.Strength, Player.BonusAttributes.GetValue(Attribute.Strength) - 60);
Player.BonusAttributes.SetValue(Attribute.AP, Player.BonusAttributes.GetValue(Attribute.AP) - 120);
}
public override string ToString()
{
return "Mighty Rage Buff";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BELCORP.GestorDocumental.BE.DDP
{
public class TareaDDPBE
{
public int ID { get; set; }
public string Titulo { get; set; }
public string TipoContenido { get; set; }
public double PorcentajeCompletado { get; set; }
public string ComentarioObservacion { get; set; }
public string Descripcion { get; set; }
public string EstadoTarea { get; set; }
public DateTime FechaInicio { get; set; }
public DateTime FechaVencimiento { get; set; }
public int AsignadoID { set; get; }
public string AsignadoMail { set; get; }
public string Asignado { get; set; }
public string CodigoDocumento { get; set; }
public string EstadoDocumento { get; set; }
public DateTime FechaAsignacion { get; set; }
public string ResultadoTarea { get; set; }
public int RevisorDocumentoID { get; set; }
public string RevisorDocumento { get; set; }
public TipoDocumentalBE TipoDocumental { get; set; }
public DocumentoDDPBE DocumentoRelacionado { get; set; }
public string ModificadoPor { get; set; }
public string SistemaCalidad { get; set; }
public string URLEditForm { get; set; }
/// <summary>
/// Contructor por defecto
/// </summary>
public TareaDDPBE()
{
this.TipoDocumental = new TipoDocumentalBE();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;
using UnityEditor;
[Serializable]
[CreateAssetMenu(fileName = "StageTable", menuName = "CreateStageTable")]
public class StageTable : ResettableScriptableObject {
const int deadTimesMax = 99;
[SerializeField]
private String stageName;
[SerializeField]
private Sprite star1;
[SerializeField]
private Sprite star2;
[SerializeField]
private Sprite star3;
[SerializeField]
private Sprite stageDigit1;
[SerializeField]
private Sprite stageDigit2;
[SerializeField]
private bool hasClear;
[SerializeField]
private int deadTimes;
[SerializeField]
private Texture ita;
private int ghost1;
private int ghost2;
private Sprite ghost1Sprite;
private Sprite ghost2Sprite;
public String GetStageName()
{
return stageName;
}
public Sprite GetStar1()
{
return star1;
}
public Sprite GetStar2()
{
return star2;
}
public Sprite GetStar3()
{
return star3;
}
public Sprite GetStageDigit1()
{
return stageDigit1;
}
public Sprite GetStageDigit2()
{
return stageDigit2;
}
public Sprite GetGhost1Sprite()
{
return ghost1Sprite;
}
public Sprite GetGhost2Sprite()
{
return ghost2Sprite;
}
public Texture GetIta()
{
return ita;
}
public bool GetHasClear()
{
return hasClear;
}
public int GetDeadTimes()
{
return deadTimes;
}
public void SetDeadTimes(int value)
{
if (value > deadTimesMax)
value = deadTimesMax;
deadTimes = value;
SetDigits();
ghost1Sprite = SetSpriteDigits(ghost1);
ghost2Sprite = SetSpriteDigits(ghost2);
}
private void SetDigits()
{
ghost1 = deadTimes / 10;
ghost2 = deadTimes % 10;
}
private Sprite SetSpriteDigits(int deadNum)
{
return AssetDatabase.LoadAssetAtPath<Sprite>("Assets/UI/StageSelect/" + deadNum.ToString() + ".png");
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI;
namespace MultiplayerEmotes.Framework.Constants {
internal static class Sprites {
public static class Emotes {
public static string AssetName => "TileSheets/emotes";
public static Texture2D Texture => ModEntry.ModHelper.Content.Load<Texture2D>(AssetName, ContentSource.GameContent);
public static int Size = 16;
public static int AnimationFrames = 4;
}
public static class MenuButton {
public static string AssetName => "LooseSprites/Cursors";
public static Texture2D Texture => ModEntry.ModHelper.Content.Load<Texture2D>(AssetName, ContentSource.GameContent);
public static Rectangle SourceRectangle = new Rectangle(301, 288, 15, 15);
}
public static class MenuBox {
public static string AssetName => "assets/emoteBox.png";
public static Texture2D Texture => ModEntry.ModHelper.Content.Load<Texture2D>(AssetName, ContentSource.ModFolder);
public static Rectangle SourceRectangle = new Rectangle(0, 0, 228, 300);
public static int Width = 300;
public static int Height = 250;
//TODO make enum of top, down, left, right arrows
public static class TopArrow {
public static Rectangle SourceRectangle = new Rectangle(228, 0, 28, 28 - 8);
}
public static class DownArrow {
public static Rectangle SourceRectangle = new Rectangle(228, 28 + 8, 28, 28 - 8);
}
public static class LeftArrow {
public static Rectangle SourceRectangle = new Rectangle(228, 56, 28 - 8, 28);
}
public static class RightArrow {
public static Rectangle SourceRectangle = new Rectangle(228 + 8, 84, 28 - 8, 28);
}
}
public static class MenuArrow {
public static string AssetName => "LooseSprites/chatBox";
public static Texture2D Texture => ModEntry.ModHelper.Content.Load<Texture2D>(AssetName, ContentSource.GameContent);
//TODO make enum of top, down, left, right arrows
public static Rectangle UpSourceRectangle = new Rectangle(156, 300, 32, 20); //new Rectangle(256, 20, 32, 20);
public static Rectangle DownSourceRectangle = new Rectangle(192, 304, 32, 20);//new Rectangle(256, 200, 32, 20);
}
}
}
|
// <author>Edson L. dela Torre</author>
// <email>edsondt@yahoo.com</email>
using System.Net;
namespace IpswichWeather.Web
{
/// <summary>
/// This class is a builder class for WebRequest. Right now, this is only implemented with
/// GET, but can easily be modified to support POST (by implementing the message body).
/// </summary>
class WebRequestBuilder
{
private string url;
public WebRequestBuilder(string url)
{
this.url = url;
}
private WebMethod method = WebMethod.GET;
public WebRequestBuilder Method(WebMethod method)
{
this.method = method;
return this;
}
private string contentType = "text/plain;charset=us-ascii";
public WebRequestBuilder ContentType(string contentType)
{
this.contentType = contentType;
return this;
}
public WebRequest Build()
{
WebRequest request = WebRequest.Create(url);
request.Method = method.ToString();
request.ContentType = contentType;
// TODO: Implement logic for adding message body for POST.
return request;
}
}
}
|
using Business.Abstract;
using Business.ValidationRules.FluentValidation;
using Core.Aspects.Autofac.Validation;
using Core.Business;
using Core.Entities.Concrete;
using Core.Utilities.Results;
using DataAccess.Abstract;
using Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Text;
namespace Business.Concrete
{
public class UserManager : IUserService
{
IUserDal _dal;
public UserManager(IUserDal entityDal)
{
_dal = entityDal;
}
[ValidationAspect(typeof(UserValidator))]
public IResult Add(User entity)
{
_dal.Add(entity);
return new SuccessResult("Kayıt Eklendi");
}
private bool CheckEmailIsUsed(string email)
{
var users = _dal.GetAll(x => x.Email == email);
if (users.Count != 0)
{
return true;
}
else
{
return false;
}
}
public IDataResult<User> GetByMail(string email)
{
return new SuccessDataResult<User>(_dal.Get(u => u.Email == email));
}
public IDataResult<List<OperationClaim>> GetClaims(User user)
{
return new SuccessDataResult<List<OperationClaim>>( _dal.GetClaims(user));
}
public IDataResult<List<User>> GetAll()
{
return new SuccessDataResult<List<User>>(_dal.GetAll());
}
public IDataResult<User> GetById(int entityId)
{
throw new NotImplementedException();
}
public IResult Update(User entity)
{
throw new NotImplementedException();
}
public IResult Delete(User entity)
{
throw new NotImplementedException();
}
public IResult DeleteRange(List<User> entities)
{
throw new NotImplementedException();
}
}
} |
using Application.Base;
using Domain.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace Application.Requests
{
public class CreditoRequest : IRequest<Credito>
{
public string CedulaEmpleado { get; set; }
public int Plazo { get; set; }
public double TasaDeInteres { get; set; }
public double Valor { get; set; }
public CreditoRequest()
{
TasaDeInteres = 0.005;
}
public Credito ToEntity()
{
return new Credito
{
Plazo = Plazo,
TasaDeInteres = TasaDeInteres,
Valor = Valor
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Media.Imaging;
namespace CTUMobile
{
class Campus
{
public int Id { get; set; }
public string CampusName { get; set; }
public Uri CampusLocation { get; set; }
public BitmapImage CampusImage { get; set; }
public string CampusContact { get; set; }
public string CampusDescription { get; set; }
public Dictionary<String, String> CampusCourses { get; set; }
public string CampusActivities { get; set; }
public System.Uri CampusVideos { get; set; }
public double MapLong { get; set; }
public double MapLat { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
namespace My_News.DAL
{
class SourceDAL
{
public bool InsertSource(Source sou)
{
try
{
SqlCommand cmd = new SqlCommand("INSERT INTO Source VALUES( @sou_name, @sou_home, @sou_logo)", DbHelper.connection);
cmd.Parameters.AddWithValue("sou_id", sou.Id);
cmd.Parameters.AddWithValue("sou_name", sou.Name);
cmd.Parameters.AddWithValue("sou_home", sou.Homepage);
cmd.Parameters.AddWithValue("sou_logo", sou.Logo);
DbHelper.Open();
int result = cmd.ExecuteNonQuery();
DbHelper.Close();
return result > 0;
}
catch (Exception e)
{
Logger.Instance.Log("SourceDAL CreateSource", e.ToString());
DbHelper.Close();
return false;
}
}
public bool UpdateSource(Source sou)
{
try
{
SqlCommand cmd = new SqlCommand("UPDATE Source SET SourceName = @sou_name, SourceHomepage = @sou_home, SourceLogo = @sou_logo WHERE SourceId = @sou_id", DbHelper.connection);
cmd.Parameters.AddWithValue("sou_id", sou.Id);
cmd.Parameters.AddWithValue("sou_name", sou.Name);
cmd.Parameters.AddWithValue("sou_home", sou.Homepage);
cmd.Parameters.AddWithValue("sou_logo", sou.Logo);
DbHelper.Open();
int result = cmd.ExecuteNonQuery();
DbHelper.Close();
return result > 0;
}
catch (Exception e)
{
Logger.Instance.Log("SourceDAL UpdateSource", e.ToString());
DbHelper.Close();
return false;
}
}
public bool DeleteSource(int sou_id)
{
try
{
bool rs = (new RsslinkDAL()).DeleteRsslinkBySourceId(sou_id);
if (rs)
{
SqlCommand cmd = new SqlCommand("DELETE FROM Source WHERE SourceId = @sou_id", DbHelper.connection);
cmd.Parameters.AddWithValue("sou_id", sou_id);
DbHelper.Open();
int result = cmd.ExecuteNonQuery();
DbHelper.Close();
return result > 0;
}
else
{
Logger.Instance.Log("RsslinkDAL DeleteRsslinkBySourceId", rs.ToString());
DbHelper.Close();
return false;
}
}
catch (Exception e)
{
Logger.Instance.Log("SourceDAL UpdateSource", e.ToString());
return false;
}
}
public List<Source> GetAllSource()
{
List<Source> list = new List<Source>();
try
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Source", DbHelper.connection);
DbHelper.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
while (sdr.Read())
{
Source sou = new Source();
sou.Id = Convert.ToInt32(sdr[0]);
sou.Name = Convert.ToString(sdr[1]);
sou.Homepage = Convert.ToString(sdr[2]);
sou.Logo = Convert.ToString(sdr[3]);
list.Add(sou);
}
}
DbHelper.Close();
return list;
}
catch (Exception e)
{
Logger.Instance.Log("SourceDAL GetAllSource", e.ToString());
DbHelper.Close();
return null;
}
}
public Source GetSourceById(int sou_id)
{
try
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Source WHERE SourceId = @sou_id", DbHelper.connection);
cmd.Parameters.AddWithValue("sou_id", sou_id);
DbHelper.Open();
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
Source sou = new Source();
sou.Id = Convert.ToInt32(sdr[0]);
sou.Name = Convert.ToString(sdr[1]);
sou.Homepage = Convert.ToString(sdr[2]);
sou.Logo = Convert.ToString(sdr[3]);
DbHelper.Close();
return sou;
}
catch (Exception e)
{
Logger.Instance.Log("SourceDAL GetSourceById", e.ToString());
DbHelper.Close();
return null;
}
}
public Source GetSourceByName(string name)
{
try
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Source WHERE SourceName = @name", DbHelper.connection);
cmd.Parameters.AddWithValue("name", name);
DbHelper.Open();
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
Source sou = new Source();
sou.Id = Convert.ToInt32(sdr[0]);
sou.Name = Convert.ToString(sdr[1]);
sou.Homepage = Convert.ToString(sdr[2]);
sou.Logo = Convert.ToString(sdr[3]);
DbHelper.Close();
return sou;
}
catch (Exception e)
{
Logger.Instance.Log("SourceDAL GetSourceByName", e.ToString());
DbHelper.Close();
return null;
}
}
public bool DeleteAllSource()
{
try
{
SqlCommand cmd = new SqlCommand("DELETE FROM Source", DbHelper.connection);
DbHelper.Open();
cmd.ExecuteNonQuery();
DbHelper.Close();
return true;
}
catch (Exception e)
{
Logger.Instance.Log("DeleteAllSource", e.ToString());
DbHelper.Close();
return false;
}
}
public bool ImportSource(List<Source> listSou)
{
try
{
SqlCommand cmd = new SqlCommand("SET IDENTITY_INSERT [Source] ON", DbHelper.connection);
DbHelper.Open();
cmd.ExecuteNonQuery();
foreach (var sou in listSou)
{
cmd = new SqlCommand("INSERT INTO Source([SourceId], [SourceName], [SourceHomepage], [SourceLogo]) VALUES(@sou_id, @sou_name, @sou_home, @sou_logo)", DbHelper.connection);
cmd.Parameters.AddWithValue("sou_id", sou.Id);
cmd.Parameters.AddWithValue("sou_name", sou.Name);
cmd.Parameters.AddWithValue("sou_home", sou.Homepage);
cmd.Parameters.AddWithValue("sou_logo", sou.Logo);
try
{
cmd.ExecuteNonQuery();
}
catch { }
}
cmd = new SqlCommand("SET IDENTITY_INSERT [Source] OFF", DbHelper.connection);
cmd.ExecuteNonQuery();
DbHelper.Close();
return true;
}
catch (Exception e)
{
Logger.Instance.Log("SourceDAL ImportSource", e.ToString());
DbHelper.Close();
return false;
}
}
}
}
|
using System;
using System.IO;
using System.Web.Configuration;
using Boxofon.Web.Helpers;
using Boxofon.Web.Mailgun;
using Boxofon.Web.Services;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
namespace Boxofon.Web.Infrastructure
{
public class EmaillVerificationService : IEmailVerificationService, IRequireInitialization
{
private static readonly Random Random = new Random();
private readonly CloudStorageAccount _storageAccount;
private readonly IMailgunClient _mailgunClient;
public EmaillVerificationService(IMailgunClient mailgunClient)
{
if (mailgunClient == null)
{
throw new ArgumentNullException("mailgunClient");
}
_mailgunClient = mailgunClient;
_storageAccount = CloudStorageAccount.Parse(WebConfigurationManager.AppSettings["azure:StorageConnectionString"]);
}
public void Initialize()
{
Table().CreateIfNotExists();
}
protected CloudTable Table()
{
return _storageAccount.CreateCloudTableClient().GetTableReference("EmailVerifications");
}
public void BeginVerification(Guid userId, string email)
{
var code = GenerateCode();
var entity = new VerificationEntity(userId, email, code);
var op = TableOperation.InsertOrReplace(entity);
Table().Execute(op);
_mailgunClient.SendNoReplyMessage(email, "Verifiering av e-postadress", string.Format("Din verifieringskod: <strong>{0}</strong>", code));
}
public bool TryCompleteVerification(Guid userId, string email, string code)
{
if (string.IsNullOrEmpty(code) || !email.IsValidEmail())
{
return false;
}
var op = TableOperation.Retrieve<VerificationEntity>(userId.ToString(), email);
var entity = (VerificationEntity)Table().Execute(op).Result;
if (entity != null && entity.Code == code)
{
var deleteOp = TableOperation.Delete(entity);
Table().ExecuteAsync(deleteOp);
return true;
}
return false;
}
private static string GenerateCode()
{
return Random.Next(1, 999999).ToString("000000");
}
public class VerificationEntity : TableEntity
{
public string Code { get; set; }
public VerificationEntity()
{
}
public VerificationEntity(Guid userId, string email, string code)
{
PartitionKey = userId.ToString();
RowKey = email;
Code = code;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Step_117
{
public class Half
{
public int Change(int numOne)
{
int x = numOne;
x = numOne / 2;
return x;
}
public int NumFour(out int ageNow)
{
ageNow = 36;
return ageNow;
}
public string NumFour(out string myName)
{
myName = "Abbey";
return myName;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using Microsoft.AppCenter;
namespace Welic.App.Services.ServiceViews
{
class HttpRequestExceptionEx : HttpRequestException
{
public System.Net.HttpStatusCode HttpCode { get; }
public HttpRequestExceptionEx(System.Net.HttpStatusCode code) : this(code, null, null)
{
}
public HttpRequestExceptionEx(System.Net.HttpStatusCode code, string message) : this(code, message, null)
{
}
public HttpRequestExceptionEx(System.Net.HttpStatusCode code, string message, System.Exception inner)
: base(message,
inner)
{
HttpCode = code;
}
}
}
|
/// <summary>
/// The <c>gView.Framework</c> provides all interfaces to develope
/// with and for gView
/// </summary>
namespace gView.Framework.system
{
/// <summary>
/// In the <c>gView.Framework</c> namespace all interfaces are defined. If you want to develope your own extensions use this interfaces.
/// Extensions can be made with any interfaces that implement <see cref="gView.Framework.IgViewExtension"/>
/// </summary>
internal class NamespaceDoc
{
}
}
|
using System;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.GraphVisualiser.Controllers;
using Microsoft.Extensions.Localization;
using OrchardCore.Navigation;
namespace DFC.ServiceTaxonomy.GraphVisualiser.Services
{
public class AdminMenuService : INavigationProvider
{
private readonly IStringLocalizer S;
public AdminMenuService(IStringLocalizer<AdminMenuService> localizer)
{
S = localizer;
}
public Task BuildNavigationAsync(string name, NavigationBuilder builder)
{
if (!String.Equals(name, "admin", StringComparison.OrdinalIgnoreCase))
{
return Task.CompletedTask;
}
builder
.Add(S["Graph"], "99", graph => graph
.AddClass("graph").Id("graph")
.Add(S["Visualise Ontology"], "1", ontology => ontology
.Action(nameof(VisualiseController.Viewer), "Visualise", new { area = typeof(Startup)!.Namespace })));
return Task.CompletedTask;
}
}
}
|
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-nav")]
public class NavTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string NavClass { get; set; }
public NavTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
TagHelperContent childContentAsync = await output.GetChildContentAsync();
output.Content.AppendHtml(childContentAsync.GetContent());
output.Attributes.SetAttribute("class", (object) ("nav " + this.NavClass));
// ISSUE: reference to a compiler-generated method
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KartObjects;
using System.Threading;
using KartLib;
namespace KartSystem
{
/// <summary>
/// Форма генератора дисконтных карт
/// </summary>
public partial class DiscountCardsGenerator : XBaseDictionaryEditor
{
#region Конструкторы
public DiscountCardsGenerator()
{
InitializeComponent();
InitView();
}
public DiscountCardsGenerator(IList<DiscCardGroup> discCardGroups)
{
InitializeComponent();
DiscCardGroups = discCardGroups;
ListToDeleteCard = new List<DiscountCard>();
ListToDeleteAccount = new List<AxlAccount>();
InitView();
}
#endregion
#region Свойства
public IList<DiscCardGroup> DiscCardGroups
{
get;
set;
}
List<DiscountCard> _generatedDiscCards = new List<DiscountCard>();
public List<DiscountCard> GeneratedDiscCards
{
get
{
return _generatedDiscCards;
}
set
{
_generatedDiscCards = value;
}
}
#endregion
#region Поля
FormWait frmWait;
string prefix,format;
long IdCadtGroup;
int cardCount;
List<DiscountCard> ListToDeleteCard;
List<AxlAccount> ListToDeleteAccount;
#endregion
#region Методы
public override void InitView()
{
base.InitView();
discCardGroupBindingSource.DataSource = DiscCardGroups;
}
private void sbCreateCards_Click(object sender, EventArgs e)
{
foreach (var item in ListToDeleteCard)
{
if (ceCreateAccounts.Checked)
{
AxlAccount axl = new AxlAccount();
axl.Id = (long)item.IdAccount;
Saver.DeleteFromDb<AxlAccount>(axl);
}
Saver.DeleteFromDb<DiscountCard>(item);
}
Saver.DataContext.CommitTransaction();
if (string.IsNullOrWhiteSpace(tePrefix.Text))
{
MessageBox.Show("Не задан префикс ","Ошибка заведения данных");
return;
}
if (seCount.Value <= 0)
{
MessageBox.Show("Не задано кол-во карт ", "Ошибка заведения данных");
return;
}
if (lueCardGroup.EditValue == null)
{
MessageBox.Show("Не выбрана группа карт", "Ошибка заведения данных");
return;
}
frmWait = new FormWait("Генерация карт ...");
prefix = tePrefix.Text.Trim();
IdCadtGroup = (long)lueCardGroup.EditValue;
cardCount = (int)seCount.Value;
format = string.Concat(new int[(int) Math.Truncate( Math.Log10((double)cardCount))+1]);
_generatedDiscCards.Clear();
Saver.DataContext.BeginTransaction();
// Процесс формирования запускаем отдельным потоком
Thread thread = new Thread(GenerateDiscCarts) { IsBackground = true };
thread.Start();
frmWait.ShowDialog();
frmWait.Dispose();
frmWait = null;
discountCardBindingSource.DataSource = _generatedDiscCards;
gcDiscountCards.RefreshDataSource();
}
private void GenerateDiscCarts()
{
DiscountCard newCard;
if (prefix[prefix.Length-1] != '=')
prefix += "=";
int LengthPrefix = prefix.Length + 1;
Int64 MaxCardNumber = Convert.ToInt64(Loader.DataContext.ExecuteScalar("select coalesce(max(cast(substring(c.cardcode from " + LengthPrefix + ") as integer)),0) from discountcards c where c.cardcode like '" + prefix + "%'"));
for (int n = 1; n <= cardCount; n++)
{
AxlAccount axl = new AxlAccount();
if (ceCreateAccounts.Checked)
{
axl.Id = 0;
axl.BeginRest = Convert.ToDecimal(0);
axl.CurrRest = Convert.ToDecimal(0);
axl.CreditAmount = Convert.ToDecimal(0);
Saver.SaveToDb<AxlAccount>(axl);
}
newCard = new DiscountCard();
newCard.CardCode = prefix + (MaxCardNumber + n).ToString(format).PadLeft((int)seLegth.Value, '0');
newCard.IdCardGroup = (long)lueCardGroup.EditValue;
newCard.PercentDiscount = (int)sePercent.Value;
if (axl.Id != 0)
newCard.IdAccount = axl.Id;
else
newCard.IdAccount = null;
Saver.SaveToDb<DiscountCard>(newCard);
_generatedDiscCards.Add(newCard);
ListToDeleteCard.Add(newCard);
ListToDeleteAccount.Add(axl);
}
frmWait.CloseWaitForm();
}
#endregion
private void lueCardGroup_EditValueChanged(object sender, EventArgs e)
{
DiscCardGroup _DiscCardGroup = Loader.DbLoadSingle<DiscCardGroup>("Id = " + lueCardGroup.EditValue);
ceCreateAccounts.Enabled = _DiscCardGroup.CardGroupType != (int)CardGroupType.Discount;
sePercent.Value = (_DiscCardGroup.AXLPercent == null) ? 0 : Convert.ToDecimal(_DiscCardGroup.AXLPercent);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace aoc2016.day08
{
public class Solution
{
public static void Run()
{
string[] input = System.IO.File.ReadAllLines("day08.txt");
LCD<bool> lcd = new LCD<bool>(50, 6);
lcd.Formatter = val => val ? "#" : ".";
lcd.FormatDelimiter = null;
AnimateLCD(lcd, input, TimeSpan.FromMilliseconds(2500));
Console.WriteLine();
Console.WriteLine();
int part1 = lcd.Count(val => val);
Console.WriteLine("==== Part 1 ====");
Console.WriteLine($"Lit pixels: {part1}");
Console.WriteLine();
Console.WriteLine("==== Part 2 ====");
Console.WriteLine("Read from the LCD above");
}
private static void AnimateLCD(LCD<bool> lcd, string[] cmds, TimeSpan totalTime)
{
int cLeft = Console.CursorLeft;
int cTop = Console.CursorTop;
var start = DateTime.UtcNow;
var end = start.Add(totalTime);
int step = (int) ((end - start).TotalMilliseconds / cmds.Length);
for (int i = 0; i < cmds.Length - 1; i++)
{
lcd.RunCommand(cmds[i], true);
Console.SetCursorPosition(cLeft, cTop);
Console.Write(lcd);
Thread.Sleep(Math.Max(0, (int)(start.AddMilliseconds(step * i) - DateTime.UtcNow).TotalMilliseconds));
}
lcd.RunCommand(cmds[cmds.Length - 1], true);
Console.SetCursorPosition(cLeft, cTop);
Console.Write(lcd);
}
private class LCD<T> : IEnumerable<T>
{
public int Width { get; }
public int Height { get; }
private T[,] _lcd;
public Func<T, string> Formatter { get; set; } = val => val.ToString();
public char? FormatDelimiter = ' ';
public LCD(int w, int h)
{
this.Width = w;
this.Height = h;
this._lcd = new T[w, h];
}
public T this[int i, int j]
{
get
{
return _lcd[i, j];
}
set
{
_lcd[i, j] = value;
}
}
public void RunCommand(string cmd, T rectVal)
{
int space = cmd.IndexOf(' ');
string args = cmd.Substring(space + 1);
cmd = cmd.Substring(0, space);
switch(cmd)
{
case "rect":
string[] xy = args.Split('x');
Rect(int.Parse(xy[0]), int.Parse(xy[1]), rectVal);
break;
case "rotate":
string pattern = @"^(column|row) .=(\d+) by (\d+)$";
var matches = Regex.Match(args, pattern);
if (!matches.Success)
throw new ArgumentException("wrongly formatted \"rotate\"");
int rowcol = int.Parse(matches.Groups[2].Value);
int n = int.Parse(matches.Groups[3].Value);
if (matches.Groups[1].Value == "column")
RotateColumn(rowcol, n);
else
RotateRow(rowcol, n);
break;
}
}
public void Rect(int A, int B, T val)
{
for (int i = 0; i < A; i++)
for (int j = 0; j < B; j++)
this[i, j] = val;
}
public void RotateRow(int A, int B)
{
B = B % Width;
T[] vals = new T[B];
for (int i = 0; i < B; i++)
vals[i] = this[i, A];
for (int i = 0; i < Width; i++)
{
T bak = this[(i + B) % Width, A];
this[(i + B) % Width, A] = vals[i % B];
vals[i % B] = bak;
}
}
public void RotateColumn(int A, int B)
{
B = B % Height;
T[] vals = new T[B];
for (int i = 0; i < B; i++)
vals[i] = this[A, i];
for (int i = 0; i < Height; i++)
{
T bak = this[A, (i + B) % Height];
this[A, (i + B) % Height] = vals[i % B];
vals[i % B] = bak;
}
}
public override string ToString()
{
return ToString(Formatter);
}
public string ToString(Func<T, string> formatter)
{
int maxWidth = Enumerable.Cast<T>(_lcd).Max(val => formatter(val).Length);
StringBuilder sb = new StringBuilder();
for (int j = 0; j < Height; j++)
{
for (int i = 0; i < Width - 1; i++)
{
sb.Append(formatter(this[i, j]).PadLeft(maxWidth));
if (FormatDelimiter != null)
sb.Append(FormatDelimiter);
}
sb.Append(formatter(this[Width - 1, j]).PadLeft(maxWidth));
sb.AppendLine();
}
sb.Length -= Environment.NewLine.Length; // Remove last newline
return sb.ToString();
}
public IEnumerator<T> GetEnumerator()
{
foreach (var val in _lcd)
yield return val;
}
IEnumerator IEnumerable.GetEnumerator()
{
return _lcd.GetEnumerator();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
using System.Xml.Serialization;
namespace AxiReports
{
public class RestReportSettings : Entity
{
[XmlIgnore]
public override string FriendlyName
{
get { return "Настройки отчета об остатках"; }
}
public List<Warehouse> SelectedWarehouses;
public List<GoodGroup> SelectedGoodGroups;
public long IdPricetype;
public bool ShowPositive;
public bool ShowZero;
public bool ShowNegative;
public bool ShowOnTheWay;
public bool GoodGroupOnly;
public int SortType;
public int OptionIndex;
public bool OperRest { get; set; }
public bool ShowNegativeRow { get; set; }
}
}
|
using SMG.Common.Algebra;
using SMG.Common.Code;
using SMG.Common.Gates;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SMG.Common
{
public static class GateOperations
{
internal static IGate Simplify(this IGate gate)
{
return Gate.Simplify(gate);
}
public static bool IsCached(this IGate gate)
{
return null != gate.ID;
}
public static bool IsFalse(this IGate gate)
{
return gate is FalseGate;
}
internal static IGate Replace(this IGate gate, Func<IGate, IGate> replacer)
{
IGate result;
if (gate.Type.IsLogical())
{
result = gate.Clone();
if (result is IModifyGate)
{
var logic = (IModifyGate)result;
var inputs = result.GetInputs().ToList();
for (int j = 0; j < inputs.Count; ++j)
{
var input = inputs[j];
var r = input.Replace(replacer);
if (r != input)
{
logic.ReplaceInput(j, r);
}
}
}
else
{
throw new ArgumentException("expected logic gate.");
}
}
else
{
result = gate;
}
result = replacer(result);
return result;
}
public static IEnumerable<IGate> SelectAll(this IGate gate, Predicate<IGate> pred = null)
{
foreach(var c in gate.GetInputs())
{
// c.Enumerate(action);
foreach(var e in c.SelectAll(pred))
{
yield return e;
}
}
if (null == pred || pred(gate))
{
yield return gate;
}
}
public static IEnumerable<IGate> GetInputs(this IGate gate)
{
if(gate is ILogicGate)
{
return ((ILogicGate)gate).Inputs;
}
else
{
return new IGate[0];
}
}
internal static void AddInput(this IGate gate, IGate a)
{
if (gate is IModifyGate)
{
((IModifyGate)gate).AddInput(a);
}
else
{
throw new Exception("cannot add input to gate [" + gate.Type + "].");
}
}
internal static SumOfProducts GetSOP(this IGate garg)
{
var gset = new SumOfProducts();
foreach (var i in garg.GetInputs())
{
if (i is TrueGate)
{
gset.SetFixed(i);
break;
}
else if (i is FalseGate)
{
// ignore
}
else
{
gset.Add(i.GetProduct());
}
}
return gset;
}
public static string GetOriginalID(this IGate gate)
{
if(gate is LabelGate)
{
return ((LabelGate)gate).OriginalGate.ID;
}
else
{
return gate.ID;
}
}
public static IGate GetOriginalGate(this IGate gate)
{
if (gate is LabelGate)
{
return ((LabelGate)gate).OriginalGate;
}
else
{
return gate;
}
}
public static int GetNestingLevel(this IGate gate)
{
if(gate.Type.IsLogical())
{
if (gate.GetInputs().Any())
{
return 1 + gate.GetInputs().Max(g => g.GetNestingLevel());
}
else
{
// possibly too much nesting here.
return 1;
}
}
else
{
return 0;
}
}
public static IEnumerable<IVariableCondition> GetVariableConditions(this IGate gate)
{
return gate
.SelectAll(g => g is IVariableCondition)
.OfType<IVariableCondition>();
}
public static IEnumerable<Variable> GetVariables(this IGate gate)
{
return gate
.GetVariableConditions()
.Select(e => e.Variable)
.OrderBy(v => v.Index)
.Distinct();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using FreezyFood_Profit_Calculator.Models;
namespace FreezyFood_Profit_Calculator.Controllers
{
public class UnitsController : Controller
{
private ProfitDbContext db = new ProfitDbContext();
// GET: Units
public ActionResult Index()
{
var units = db.Units.Include(u => u.Product);
return View(units.ToList());
}
// GET: Units/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Unit unit = db.Units.Find(id);
if (unit == null)
{
return HttpNotFound();
}
return View(unit);
}
// GET: Units/Create
public ActionResult Create()
{
ViewBag.ProductId = new SelectList(db.Products, "Id", "ProductName");
return View();
}
// POST: Units/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,SaleInGrams,ProductId")] Unit unit, string submit)
{
if (ModelState.IsValid)
{
var proizvod = db.Products.Find(unit.ProductId);
decimal nabavnaCenaPoGramu = proizvod.PricePerKGBuy / 1000;
decimal punaNabavnaCena = nabavnaCenaPoGramu * unit.SaleInGrams;
decimal prodajnaCenaPoGramu = proizvod.PricePerKGSell / 1000;
decimal punaProdajnaCena = prodajnaCenaPoGramu * unit.SaleInGrams;
decimal profit = punaProdajnaCena - punaNabavnaCena;
unit.CalculatedProfit = profit;
unit.ProductName = proizvod.ProductName;
db.Units.Add(unit);
db.SaveChanges();
if (submit == "Save")
return RedirectToAction("Index");
if (submit == "Save and stay")
return RedirectToAction("Create");
}
ViewBag.ProductId = new SelectList(db.Products, "Id", "ProductName", unit.ProductId);
return View(unit);
}
// GET: Units/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Unit unit = db.Units.Find(id);
if (unit == null)
{
return HttpNotFound();
}
ViewBag.ProductId = new SelectList(db.Products, "Id", "ProductName", unit.ProductId);
return View(unit);
}
// POST: Units/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,SaleInGrams,ProductId")] Unit unit)
{
if (ModelState.IsValid)
{
db.Entry(unit).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ProductId = new SelectList(db.Products, "Id", "ProductName", unit.ProductId);
return View(unit);
}
// GET: Units/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Unit unit = db.Units.Find(id);
if (unit == null)
{
return HttpNotFound();
}
return View(unit);
}
// POST: Units/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Unit unit = db.Units.Find(id);
db.Units.Remove(unit);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using PowerDemandDataFeed.Model;
using System.Collections.Generic;
namespace PowerDemandDataFeed.Processor.Interfaces
{
public interface IPowerDemandProcessor
{
IEnumerable<Item> GetXMLPowerDemand();
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using FileUpload.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
namespace FileUpload.Controllers
{
public class HomeController : Controller
{
private readonly ApplicationDbContext _db;
private readonly IWebHostEnvironment _webHostEnvironment;
public HomeController(ApplicationDbContext db,IWebHostEnvironment webHostEnvironment)
{
this._db = db;
this._webHostEnvironment = webHostEnvironment;
}
public IActionResult Index()
{
List<Product> products= _db.Products.ToList();
return View(products);
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public async Task<IActionResult> CreateAsync(Product product)
{
if (ModelState.IsValid)
{
var filepath = Path.Combine(_webHostEnvironment.WebRootPath, "images");
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
var fullpath = Path.Combine(filepath,product.Picture.FileName);
using (var fileLocation=new FileStream(fullpath,FileMode.Create))
{
await product.Picture.CopyToAsync(fileLocation);
}
product.PicturePath = product.Picture.FileName;
_db.Products.Add(product);
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
else {
return View(product);
}
}
}
}
|
using libairvidproto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace WinAirvid
{
public class WebClientAdp : IWebClient
{
private WebClient _client = new WebClient();
public void AddHeader(string key, string value)
{
_client.Headers.Add(key, value);
}
public byte[] UploadData(string endPoint, byte[] reqData)
{
return _client.UploadData(endPoint, reqData);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MS539FinalProject.Deliverables
{
/// <summary>
/// Generates a StringBuilder with random numbers.
/// </summary>
class RandomNumbers
{
private StringBuilder numberList = new StringBuilder();
public String NumberList { get {
return GetNumberList();
} }
/// <summary>
/// Count indicates how many numbers should be generated.
/// </summary>
/// <param name="count"></param>
public RandomNumbers(int count)
{
numberList = BuildTheString(GenerateNumbers(count));
}
/// <summary>
/// Returns the randomly generated numbers as a string.
/// </summary>
/// <returns></returns>
private string GetNumberList()
{
return numberList.ToString();
}
/// <summary>
/// Generates the random numbers based on the count.
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
private List<int> GenerateNumbers(int count)
{
Random rand = new Random();
List<int> numbers = new List<int>();
for (int i = 0; i < count; i++)
{
numbers.Add(rand.Next(100));
}
return numbers;
}
/// <summary>
/// Converts the list of integers to a formatted StringBuilder.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
private StringBuilder BuildTheString(List<int> list)
{
StringBuilder theString = new StringBuilder();
theString.AppendLine("Number Count: " + list.Count.ToString());
for (int i = 0; i < list.Count; i++)
{
theString.AppendLine(i + 1 + ". " + list[i].ToString());
}
return theString;
}
}
}
|
namespace Airelax.Application.Account
{
public enum AccountStatus
{
Success = 1,
WrongPassword,
Signup
}
} |
using EAN.GPD.Domain.Entities;
using EAN.GPD.Domain.Models;
using EAN.GPD.Domain.Repositories;
using EAN.GPD.Infrastructure.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Text;
namespace EAN.GPD.Server.Controllers.V1
{
[Route("v1/usuario")]
public class UsuarioController : BaseController<UsuarioModel, UsuarioEntity>
{
public UsuarioController(IHttpContextAccessor accessor,
IUsuarioRepository usuarioRepository) : base(accessor, usuarioRepository) { }
private void CodificarSenhaUsuario(UsuarioModel model)
{
string senha = Encoding.UTF8.GetString(Convert.FromBase64String(model.SenhaLogin));
model.SenhaLogin = Criptografia.Codificar(senha);
}
protected override void BeforePost(UsuarioModel model)
{
CodificarSenhaUsuario(model);
}
protected override void BeforePut(UsuarioModel model)
{
CodificarSenhaUsuario(model);
}
public override UsuarioEntity GetOne(long id)
{
var result = base.GetOne(id);
result.SenhaLogin = Criptografia.Descodificar(result.SenhaLogin);
return result;
}
public override long Post([FromBody] UsuarioModel model)
{
try
{
return base.Post(model);
}
catch (Exception exc)
{
Console.Out.WriteLine(exc);
throw;
}
}
public override void Put([FromBody] UsuarioModel model)
{
try
{
base.Put(model);
}
catch (Exception exc)
{
Console.Out.WriteLine(exc);
throw;
}
}
}
}
|
using iSukces.Code.AutoCode;
namespace iSukces.Code.FeatureImplementers
{
public interface IExpressionWithObjectInstance
{
CsExpression ExpressionTemplate { get; }
string Instance { get; }
}
public struct CompareToExpressionData : IExpressionWithObjectInstance
{
public CompareToExpressionData(string fieldName, CsExpression expressionTemplate, string instance = null)
{
FieldName = fieldName;
ExpressionTemplate = expressionTemplate;
Instance = instance;
}
public string FieldName { get; }
public CsExpression ExpressionTemplate { get; }
public string Instance { get; }
}
public struct ExpressionWithObjectInstance : IExpressionWithObjectInstance
{
public ExpressionWithObjectInstance(CsExpression expressionTemplate, string instance = null)
{
ExpressionTemplate = expressionTemplate;
Instance = instance;
}
public CsExpression ExpressionTemplate { get; }
public string Instance { get; }
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Unity.MLAgents;
[System.Serializable]
public class EnergyCore
{
public GameObject coreGO;
public Rigidbody coreRb;
public EnergyCoreController.CoreShape coreShape;
}
public class AIRobot
{
public GameObject robotGO;
[HideInInspector]
public AIRobotAgent robotScript;
public int arucoMarkerID;
}
class Rewards{
public int blueReward;
public int redReward;
}
public class GameArena : MonoBehaviour
{
#region ======= PUBLIC VARIABLES =======
public Text m_RewardText;
public Text m_StepsLeftText;
public List<GameObject> m_Arenas = new List<GameObject>();
[Space(10)]
public bool m_AssignRobotsManually;
public List<GameObject> m_Agents = new List<GameObject>();
[Space(10)]
public bool m_RotateArenaOnEpisodeBegin;
[Space(10)]
public GameObject m_BlueRobotPrefab;
public GameObject m_RedRobotPrefab;
[Space(10)]
public GameObject m_PositiveEnergyCoreBlockPrefab;
public GameObject m_PositiveEnergyCoreBallPrefab;
public GameObject m_NegativeEnergyCoreBlockPrefab;
public GameObject m_NegativeEnergyCoreBallPrefab;
[Space(10)]
[Header("Training options")]
public bool m_EndEpisodeOnNegRewardIfSingleAgent;
[HideInInspector]
public float m_AgentSpeedRandomFactor = 1.0f;
[HideInInspector]
public float m_RotationSpeedRandomFactor = 1.0f;
#endregion // ======= END PUBLIC VARIABLES =======
#region ======= PRIVATE VARIABLES =======
List<AIRobot> m_BlueAgents = new List<AIRobot>();
List<AIRobot> m_RedAgents = new List<AIRobot>();
List<EnergyCore> m_PosEnergyCores = new List<EnergyCore>();
List<EnergyCore> m_NegEnergyCores = new List<EnergyCore>();
/// <summary>
/// We will be changing the ground material based on success/failue
/// </summary>
Renderer m_GroundRenderer;
Material m_GroundMaterial;
GameObject m_Ground;
EnvironmentParameters m_ResetParams;
AIRobotSettings m_AIRobotSettings;
Bounds m_AreaBounds;
int currentLevel = -1;
int resetCounter = 0;
int goalCounter = 0;
int posECoreHitsOpponentGoalReward;
int posECoreHitsOwnGoalReward;
int negECoreHitsOpponentGoalReward;
int negECoreHitsOwnGoalReward;
#endregion // ======= END PRIVATE VARIABLES =======
#region ======= UNITY LIFECYCLE FUNCTIONS =======
void Awake()
{
if (m_AssignRobotsManually)
{
foreach (var agent in m_Agents)
{
var aiRobot = new AIRobot(){robotGO = agent, robotScript = agent.GetComponent<AIRobotAgent>()};
if (agent.gameObject.CompareTag("red_agent")) m_RedAgents.Add(aiRobot);
else if (agent.gameObject.CompareTag("blue_agent")) m_BlueAgents.Add(aiRobot);
}
}
}
void Start()
{
m_AIRobotSettings = FindObjectOfType<AIRobotSettings>();
m_ResetParams = Academy.Instance.EnvironmentParameters;
OnEpisodeBegin();
}
void Update()
{
if (m_RewardText != null && m_RewardText.IsActive() == true)
{
m_RewardText.text = "Reward: " + String.Format("{0:0.000}", m_BlueAgents[0].robotScript.GetCumulativeReward());
}
if (m_StepsLeftText != null && m_StepsLeftText.IsActive() == true)
{
var stepCount = m_BlueAgents[0].robotScript.StepCount;
m_StepsLeftText.text = "Steps Left: " + (m_BlueAgents[0].robotScript.MaxStep - stepCount);
}
}
#endregion // ======= END UNITY LIFECYCLE FUNCTIONS =======
#region ======= PUBLIC FUNCTIONS =======
public void OnEpisodeBegin()
{
resetCounter++;
// Only reset environment once in the first call of this function. Not on every agent's call to this function.
// If called with forceInit, ignore this and initialize the game.
if (resetCounter == 1)
{
if (m_RotateArenaOnEpisodeBegin)
{
var rotation = UnityEngine.Random.Range(0, 4);
var rotationAngle = rotation * 90f;
transform.Rotate(new Vector3(0f, rotationAngle, 0f));
}
float agentSpeedRandom = m_ResetParams.GetWithDefault(
"random_speed",
m_AIRobotSettings.agentRunSpeedRandom);
m_AgentSpeedRandomFactor = Utils.AddRandomFactor(agentSpeedRandom);
float rotationSpeedRandom = m_ResetParams.GetWithDefault(
"random_direction",
m_AIRobotSettings.agentRotationSpeedRandom);
m_RotationSpeedRandomFactor = Utils.AddRandomFactor(rotationSpeedRandom);
SetArena();
if (!m_AssignRobotsManually) SetAgents();
SetEnergyCores();
}
// Check if all agents have called this function
if (resetCounter == m_BlueAgents.Count + m_RedAgents.Count)
{
resetCounter = 0;
}
}
/// <summary>
/// Use the ground's bounds to pick a random spawn position.
/// </summary>
public Vector3 GetRandomSpawnPosInArena()
{
var m_SpawnAreaMarginMultiplier = m_ResetParams.GetWithDefault(
"spawn_area_margin",
m_AIRobotSettings.spawnAreaMarginMultiplier);
var maxTries = 100;
var tryCount = 0;
var foundNewSpawnLocation = false;
var randomSpawnPos = Vector3.zero;
while (foundNewSpawnLocation == false)
{
var randomPosX = UnityEngine.Random.Range(
-m_AreaBounds.extents.x * m_SpawnAreaMarginMultiplier,
m_AreaBounds.extents.x * m_SpawnAreaMarginMultiplier);
var randomPosZ = UnityEngine.Random.Range(
-m_AreaBounds.extents.z * m_SpawnAreaMarginMultiplier,
m_AreaBounds.extents.z * m_SpawnAreaMarginMultiplier);
randomSpawnPos = m_Ground.transform.position + new Vector3(randomPosX, 0.1f, randomPosZ);
if (Physics.CheckBox(randomSpawnPos, new Vector3(0.075f, 0.065f, 0.075f)) == false)
{
foundNewSpawnLocation = true;
}
tryCount++;
if (tryCount > maxTries) throw new Exception("Could not find new spawn position");
}
return randomSpawnPos;
}
/// <summary>
/// Gives rewards to agents based on which kind of energycore hit which goal.
/// goalHit: Which goal was hit
/// coreType: Which type of energy core hit the goal
/// </summary>
public void GoalTouched(AIRobotAgent.Team goalHit, EnergyCoreController.CoreType coreType)
{
goalCounter++;
var rewards = CalculateRewards(goalHit, coreType);
foreach (var agent in m_BlueAgents)
{
agent.robotScript.AddReward(rewards.blueReward);
}
foreach (var agent in m_RedAgents)
{
agent.robotScript.AddReward(rewards.redReward);
}
var amountOfAgents = m_BlueAgents.Count + m_RedAgents.Count;
float EndEpisodeOnNegReward = m_ResetParams.GetWithDefault(
"end_episode_on_neg_reward_if_single_agent",
m_EndEpisodeOnNegRewardIfSingleAgent == true ? 1.0f : 0.0f);
if (amountOfAgents == 1 && EndEpisodeOnNegReward > 0)
{
if (m_BlueAgents.Count > 0 && rewards.blueReward < 0) EndEpisodeForAgents();
else if (m_RedAgents.Count > 0 && rewards.redReward < 0) EndEpisodeForAgents();
}
// All energy cores have been put in goals. Reset arena.
if (goalCounter >= (m_NegEnergyCores.Count + m_PosEnergyCores.Count))
{
EndEpisodeForAgents();
}
Material groundMat = null;
if (rewards.blueReward > 0) groundMat = m_AIRobotSettings.blueTeamSuccessMat;
else groundMat = m_AIRobotSettings.redTeamSuccessMat;
StartCoroutine(GoalScoredSwapGroundMaterial(groundMat, 0.5f));
}
#endregion // ======= END PUBLIC FUNCTIONS =======
#region ======= PRIVATE FUNCTIONS =======
void EndEpisodeForAgents()
{
foreach (var agent in m_BlueAgents)
{
agent.robotScript.EndEpisode();
}
foreach (var agent in m_RedAgents)
{
agent.robotScript.EndEpisode();
}
goalCounter = 0;
}
Rewards CalculateRewards(AIRobotAgent.Team goalHit, EnergyCoreController.CoreType coreType)
{
int redReward = 0;
int blueReward = 0;
if (goalHit == AIRobotAgent.Team.Blue)
{
// Blue team got positive core.
if (coreType == EnergyCoreController.CoreType.Positive)
{
redReward = posECoreHitsOpponentGoalReward;
blueReward = posECoreHitsOwnGoalReward;
}
// Blue team got negative core.
else
{
redReward = negECoreHitsOpponentGoalReward;
blueReward = negECoreHitsOwnGoalReward;
}
}
else
{
// Red team got positive core.
if (coreType == EnergyCoreController.CoreType.Positive)
{
redReward = posECoreHitsOwnGoalReward;
blueReward = posECoreHitsOpponentGoalReward;
}
// Red team got negative core.
else
{
redReward = negECoreHitsOwnGoalReward;
blueReward = negECoreHitsOpponentGoalReward;
}
}
var rewards = new Rewards(){blueReward = blueReward, redReward = redReward};
return rewards;
}
void SetAgents()
{
var nRedAgents = (int)m_ResetParams.GetWithDefault(
"number_of_red_agents",
m_AIRobotSettings.numberOfRedAgents);
var nBlueAgents = (int)m_ResetParams.GetWithDefault(
"number_of_blue_agents",
m_AIRobotSettings.numberOfBlueAgents);
int amountRedChanged = nRedAgents - m_RedAgents.Count;
int amountBlueChanged = nBlueAgents - m_BlueAgents.Count;
if (amountRedChanged != 0)
{
InitializeAgents(m_RedRobotPrefab, m_RedAgents, amountRedChanged);
}
if (amountBlueChanged != 0)
{
InitializeAgents(m_BlueRobotPrefab, m_BlueAgents, amountBlueChanged);
}
}
void InitializeAgents(GameObject agentPrefab, List<AIRobot> list, int amountChanged)
{
if (amountChanged < 0)
{
Debug.Log("Amount of new agents: " + amountChanged);
throw new Exception("Cannot remove Agents. Not implemented yet");
}
for (int i = 0; i < amountChanged; i++)
{
var randomRotY = UnityEngine.Random.Range(-180f, 180f);
var randomRotQuat = Quaternion.Euler(new Vector3(0, randomRotY, 0));
var agentGO = GameObject.Instantiate(agentPrefab, GetRandomSpawnPosInArena(), randomRotQuat, transform);
var agent = new AIRobot(){robotGO = agentGO, robotScript = agentGO.GetComponent<AIRobotAgent>()};
list.Add(agent);
}
}
/// <summary>
/// Initialize the energy cores in the given list if any change to the amout of cores
/// or shape of cores have occured.
/// Also Give energy cores new random position and random rotation.
/// </summary>
void InitializeEnergyCores(GameObject corePrefab, List<EnergyCore> list, int nbrOfCores, EnergyCoreController.CoreShape shape)
{
bool amountChanged = list.Count != nbrOfCores;
bool shapeChanged = list.Count == 0 || list[0].coreShape != shape;
if (amountChanged || shapeChanged)
{
foreach (var core in list)
{
core.coreRb = null;
Destroy(core.coreGO);
}
list.Clear();
for (int i = 0; i < nbrOfCores; i++)
{
var go = GameObject.Instantiate(corePrefab, transform);
var core = new EnergyCore();
core.coreGO = go;
core.coreRb = go.GetComponent<Rigidbody>();
list.Add(core);
}
}
foreach (var core in list)
{
// Physics by default updates Transform changes only during Fixed Update which makes Physics.CheckBox
// to not work correctly when Transform changes and call to Physics.CheckBox are made at the same frame.
// Physics.SyncTransforms() updates the Transforms to the physics engine and Physics.CheckBox works
core.coreGO.SetActive(true);
Physics.SyncTransforms();
var randomRotY = UnityEngine.Random.Range(-180f, 180f);
core.coreGO.transform.rotation = Quaternion.Euler(new Vector3(0, randomRotY, 0));
core.coreGO.transform.position = GetRandomSpawnPosInArena();
core.coreRb.velocity = Vector3.zero;
core.coreRb.angularVelocity = Vector3.zero;
}
}
/// <summary>
/// Resets the energycores positions and velocities.
/// </summary>
void SetEnergyCores()
{
var ballShape = (EnergyCoreController.CoreShape)m_ResetParams.GetWithDefault(
"ball_shape",
(float)m_AIRobotSettings.energyCoreShape);
var negCorePrefab = ballShape == EnergyCoreController.CoreShape.Block_0
? m_NegativeEnergyCoreBlockPrefab
: m_NegativeEnergyCoreBallPrefab;
var posCorePrefab = ballShape == EnergyCoreController.CoreShape.Block_0
? m_PositiveEnergyCoreBlockPrefab
: m_PositiveEnergyCoreBallPrefab;
var nNegCore = (int)m_ResetParams.GetWithDefault(
"number_of_negative_energy_cores",
m_AIRobotSettings.numberOfNegEnergyCores);
var nPosCore = (int)m_ResetParams.GetWithDefault(
"number_of_positive_energy_cores",
m_AIRobotSettings.numberOfPosEnergyCores);
InitializeEnergyCores(negCorePrefab, m_NegEnergyCores, nNegCore, ballShape);
InitializeEnergyCores(posCorePrefab, m_PosEnergyCores, nPosCore, ballShape);
}
void SetArena()
{
var levelNum = (int)m_ResetParams.GetWithDefault("level", m_AIRobotSettings.level);
if (levelNum == currentLevel) return;
currentLevel = levelNum;
for (var i = 0; i < m_Arenas.Count; i++)
{
if (i == levelNum)
{
m_Arenas[i].SetActive(true);
m_Ground = Utils.FindGameObjectInChildWithTag(m_Arenas[i], "ground");
// Get the ground's bounds
m_AreaBounds = m_Ground.GetComponent<Collider>().bounds;
// Get the ground renderer so we can change the material when a goal is scored
m_GroundRenderer = m_Ground.GetComponent<Renderer>();
// Starting materialv
m_GroundMaterial = m_GroundRenderer.material;
}
else m_Arenas[i].SetActive(false);
}
posECoreHitsOpponentGoalReward = (int)m_ResetParams.GetWithDefault(
"pos_ecore_hits_opponent_goal_reward",
m_AIRobotSettings.posECoreHitsOpponentGoalReward);
posECoreHitsOwnGoalReward = (int)m_ResetParams.GetWithDefault(
"pos_ecore_hits_own_goal_reward",
m_AIRobotSettings.posECoreHitsOwnGoalReward);
negECoreHitsOpponentGoalReward = (int)m_ResetParams.GetWithDefault(
"neg_ecore_hits_opponent_goal_reward",
m_AIRobotSettings.negECoreHitsOpponentGoalReward);
negECoreHitsOwnGoalReward = (int)m_ResetParams.GetWithDefault(
"neg_ecore_hits_own_goal_reward",
m_AIRobotSettings.negECoreHitsOwnGoalReward);
}
/// <summary>
/// Swap ground material, wait time seconds, then swap back to the regular material.
/// </summary>
IEnumerator GoalScoredSwapGroundMaterial(Material mat, float time)
{
m_GroundRenderer.material = mat;
yield return new WaitForSeconds(time);
m_GroundRenderer.material = m_GroundMaterial;
}
#endregion // ======= END PRIVATE FUNCTIONS =======
}
|
#region OneFilePicker
// OneFilePicker
// Abstract (extensible) file picker
// https://github.com/picrap/OneFilePicker
// Released under MIT license http://opensource.org/licenses/mit-license.php
#endregion
namespace OneFilePicker.File.Services
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
public static partial class ShellInfo
{
private static readonly IDictionary<string, ImageSource> Cache = new Dictionary<string, ImageSource>();
private static ImageSource GetImage(string key, bool large, Func<ImageSource> loadImage)
{
lock (Cache)
{
if (large)
key += "+";
else
key += "-";
ImageSource image;
if (!Cache.TryGetValue(key, out image))
Cache[key] = image = loadImage();
return image;
}
}
#region Special Images
internal static ImageSource GetComputerImage(bool large)
{
return GetImage(":computer", large, () => GetImage("shell32.dll", 15, large));
}
internal static ImageSource GetFavoritesImage(bool large)
{
return GetImage(":favorites", large, () => GetImage("shell32.dll", 43, large));
}
internal static ImageSource GetFolderImage(bool large)
{
return GetImage(":folder", large, () => GetImage("shell32.dll", 4, large));
}
internal static ImageSource GetNetworkNeighborhoodImage(bool large)
{
return GetImage(":network", large, () => GetImage("shell32.dll", 17, large));
}
internal static ImageSource GetWarningImage(bool large)
{
return GetImage(":warning", large, () => GetImage("user32.dll", 1, large));
}
internal static ImageSource GetQuestionImage(bool large)
{
return GetImage(":question", large, () => GetImage("user32.dll", 2, large));
}
internal static ImageSource GetErrorImage(bool large)
{
return GetImage(":error", large, () => GetImage("user32.dll", 3, large));
}
internal static ImageSource GetInformationImage(bool large)
{
return GetImage(":information", large, () => GetImage("user32.dll", 4, large));
}
internal static ImageSource GetLibrariesImage(bool large)
{
return GetImage(":libraries", large, () => GetImage("imageres.dll", 202, large));
}
#endregion
private static ImageSource GetImage(string file, int index, bool large)
{
IntPtr hImgLarge = IntPtr.Zero; //the handle to the system image list
IntPtr hImgSmall = IntPtr.Zero; //the handle to the system image list
ImageSource image;
try
{
int count = Win32.ExtractIconEx(file, index, ref hImgLarge, ref hImgSmall, 1);
if (large)
{
image = GetImage(hImgLarge);
}
else
{
image = GetImage(hImgSmall);
}
}
finally
{
Win32.DestroyIcon(hImgLarge);
Win32.DestroyIcon(hImgSmall);
}
return image;
}
/// <summary>
/// Gets the icon.
/// </summary>
/// <param name="fileName">The filename.</param>
/// <param name="large">if set to <c>true</c> [large].</param>
/// <returns></returns>
public static ImageSource GetIcon(string fileName, bool large)
{
IntPtr hImg = IntPtr.Zero;
try
{
var shinfo = new SHFILEINFO();
var iconSize = large ? Win32.SHGFI_LARGEICON : Win32.SHGFI_SMALLICON;
hImg = Win32.SHGetFileInfo(GetFileName(fileName), 0, ref shinfo, (uint)Marshal.SizeOf(typeof(SHFILEINFO)), Win32.SHGFI_ICON | iconSize);
var image = GetImage(shinfo.hIcon);
return image;
}
finally
{
Win32.DestroyIcon(hImg);
}
}
private static ImageSource GetImage(IntPtr hIcon)
{
try
{
//The icon is returned in the hIcon member of the shinfo struct
var icon = System.Drawing.Icon.FromHandle(hIcon);
var image = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
return image;
}
catch
{
return null;
}
}
private static string GetFileName(string fileName)
{
if (!fileName.Contains(@"\"))
return fileName + @"\";
return fileName;
}
/// <summary>
/// Gets the type of the file.
/// </summary>
/// <param name="fileName">The filename.</param>
/// <returns></returns>
public static string GetFileType(string fileName)
{
var shinfo = new SHFILEINFO();
Win32.SHGetFileInfo(GetFileName(fileName), 0, ref shinfo, (uint)Marshal.SizeOf(typeof(SHFILEINFO)), Win32.SHGFI_TYPENAME);
return shinfo.szTypeName;
}
/// <summary>
/// Gets the display name.
/// </summary>
/// <param name="fileName">The filename.</param>
/// <returns></returns>
public static string GetDisplayName(string fileName)
{
var shinfo = new SHFILEINFO();
Win32.SHGetFileInfo(GetFileName(fileName), 0, ref shinfo, (uint)Marshal.SizeOf(typeof(SHFILEINFO)), Win32.SHGFI_DISPLAYNAME);
return shinfo.szDisplayName;
}
public static string GetComputerDisplayName()
{
var ppidl = IntPtr.Zero;
//SHGetKnownFolderIDList(ref iconGuid, 0, IntPtr.Zero, ref ppidl);
Win32.SHGetFolderLocation(IntPtr.Zero, Win32.CSIDL_DRIVES, IntPtr.Zero, 0, ref ppidl);
var shinfo = new SHFILEINFO();
Win32.SHGetFileInfo(ppidl, 0, ref shinfo, (uint)Marshal.SizeOf(typeof(SHFILEINFO)), Win32.SHGFI_DISPLAYNAME | Win32.SHGFI_PIDL);
var displayName = shinfo.szDisplayName;
Win32.ILFree(ppidl);
return displayName;
}
}
}
|
namespace Cogito.IIS.Configuration
{
public enum AppHostApplicationPoolManagedPipelineMode
{
Integrated = 0,
Classic = 1,
}
} |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace _01.Furniture
{
class Program
{
static void Main()
{
double totalSpendMoney = 0;
var pattern = @">>(?<item>\w+)<<(?<price>\d+[.]?\d*)!(?<quantity>\d+)";
var boughtFurniture = new List<string>();
while (true)
{
var input = Console.ReadLine();
if (input == "Purchase")
{
break;
}
var matchFurniture = Regex.Match(input, pattern);
if (matchFurniture.Success)
{
var furniture = matchFurniture.Groups["item"].Value;
var price = double.Parse(matchFurniture.Groups["price"].Value);
var quantity = int.Parse(matchFurniture.Groups["quantity"].Value);
boughtFurniture.Add(furniture);
totalSpendMoney += price * quantity;
}
}
Console.WriteLine("Bought furniture:");
foreach (var furniture in boughtFurniture)
{
Console.WriteLine(furniture);
}
Console.WriteLine($"Total money spend: {totalSpendMoney:F2}");
}
}
}
|
using System.Reflection;
[assembly: AssemblyTitle("BetterRanching")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("Urbanyeti")]
[assembly: AssemblyVersion("1.7.1")]
[assembly: AssemblyFileVersion("1.7.1")]
|
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.ProviderCommitments.Web.Models.Cohort;
using System.Collections.Generic;
using System.Threading.Tasks;
using SFA.DAS.ProviderCommitments.Interfaces;
namespace SFA.DAS.ProviderCommitments.Web.Mappers.Cohort
{
public class BulkUploadValidateApiResponseToFileUpldValidateViewModel : IMapper<FileUploadValidateErrorRequest, FileUploadValidateViewModel>
{
private ICacheService _cacheService;
public BulkUploadValidateApiResponseToFileUpldValidateViewModel(ICacheService cacheService)
{
_cacheService = cacheService;
}
public async Task<FileUploadValidateViewModel> Map(FileUploadValidateErrorRequest source )
{
List<Infrastructure.OuterApi.ErrorHandling.BulkUploadValidationError> errors =
new List<Infrastructure.OuterApi.ErrorHandling.BulkUploadValidationError>();
if (!string.IsNullOrWhiteSpace(source.CachedErrorGuid))
{
errors = await _cacheService.GetFromCache<List<Infrastructure.OuterApi.ErrorHandling.BulkUploadValidationError>>(source.CachedErrorGuid) ??
new List<Infrastructure.OuterApi.ErrorHandling.BulkUploadValidationError>();
await _cacheService.ClearCache(source.CachedErrorGuid, nameof(BulkUploadValidateApiResponseToFileUpldValidateViewModel));
}
var viewModel = new FileUploadValidateViewModel();
viewModel.ProviderId = source.ProviderId;
foreach (var sourceError in errors)
{
var validationError = new BulkUploadValidationError();
validationError.EmployerName = sourceError.EmployerName;
validationError.ApprenticeName = sourceError.ApprenticeName;
validationError.RowNumber = sourceError.RowNumber;
validationError.Uln = sourceError.Uln;
foreach (var sError in sourceError.Errors)
{
if (sError.Property == "DeclaredStandards") viewModel.HasNoDeclaredStandards = true;
var dError = new PropertyError()
{
ErrorText = sError.ErrorText,
Property = sError.Property
};
validationError.PropertyErrors.Add(dError);
}
viewModel.BulkUploadValidationErrors.Add(validationError);
}
return viewModel;
}
}
}
|
using System;
/*
Write a program that prompts the user to enter
the number of students and each student’s name and score, and finally displays the
student with the highest score and the student with the second-highest score.
*/
namespace StudentsTwoHighestScores
{
class Program
{
static void Main(string[] args)
{
int scoreBest = -1, scoreSecondBest = -2;
string nameBest = "",nameSecondBset="";
int finishedEntry = 0;
do
{
Console.Write("Enter student name: ");
string studentName = Console.ReadLine();
Console.Write("Enter student score: ");
int score = int.Parse(Console.ReadLine());
if (score>scoreSecondBest)
{
if (score>scoreBest)
{
int tempScore = scoreBest;
string tempName = nameBest;
scoreBest = score;
nameBest = studentName;
scoreSecondBest = tempScore;
nameSecondBset = tempName;
}
else
{
scoreSecondBest = score;
nameSecondBset = studentName;
}
}
Console.Write("if you are finished with entries, type 0 for exit, else type 1 to continue");
finishedEntry = int.Parse(Console.ReadLine());
} while (finishedEntry!=0);
Console.WriteLine("Best student is {0} with score of {1}\n Second best student is {2} with a score of {3} ", nameBest, scoreBest, nameSecondBset, scoreSecondBest);
}
}
}
|
namespace BattleEngine.Output
{
public class UnitRemoveEvent : OutputEvent
{
public int objectId;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BikeDistributor.Data.Common;
namespace BikeDistributor.Data.Entities
{
public class Location: BaseEntity<int>
{
public virtual int BusinessEntityId { get; set; }
public virtual string Type { get; set; }
public virtual string AddressLine1 { get; set; }
public virtual string AddressLine2 { get; set; }
public virtual string Zip { get; set; }
public virtual string City { get; set; }
public virtual string State { get; set; }
public virtual string Country { get; set; }
public virtual double TaxRate { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Security.Claims;
namespace EIM.Core
{
/// <summary>
/// 用户
/// </summary>
public class IUser
{
/// <summary>
/// 用户Id
/// </summary>
string Id { get; }
/// <summary>
/// 用户名称
/// </summary>
string Name { get; }
/// <summary>
/// 用户声明
/// </summary>
IEnumerable<Claim> Claims { get; }
}
}
|
using Backend.Model.Manager;
using System;
using System.Collections.Generic;
namespace Backend.Repository.RenovationRepository
{
public interface IRenovationRepository
{
BaseRenovation GetRenovationById(int id);
List<BaseRenovation> GetAllRenovations();
List<BaseRenovation> GetAllRenovationsForTheRoom(int roomId);
void DeleteRenovation(int id);
BaseRenovation AddRenovation(BaseRenovation basicRenovation);
List<BaseRenovation> GetAllRenovationsByRoomAndDate(int roomId, DateTime date);
ICollection<BaseRenovation> GetFollowingRenovationsByRoom(int roomId);
ICollection<MergeRenovation> GetFollowingRenovationsBySecondRoom(int roomId);
ICollection<BaseRenovation> GetRenovationForPeriodByRoomNumber(DateTime start, DateTime end, int roomNumber);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class InputManager : MonoBehaviour
{
static InputManager instance = null;
Scene activeScene;
string aSceneName;
public GameObject backPanel;
IInput input;
public static InputManager Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<InputManager>();
}
return instance;
}
}
// Use this for initialization
void Awake()
{
activeScene = SceneManager.GetActiveScene();
aSceneName = activeScene.name;
if (aSceneName == "Main Menu")
{
backPanel = GameObject.FindGameObjectWithTag("BackPanel");
backPanel.SetActive(false);
}
instance = this;
if (PlayerPrefs.GetInt("AudioOnOff") == 0)
AudioListener.volume = 0;
else
AudioListener.volume = 1;
#if UNITY_ANDROID || UNITY_IOS
input = new InputMobile();
#else
input = new InputPC();
#endif
}
void Update()
{
if (aSceneName == "Main Menu")
{
if (Input.GetKeyDown(KeyCode.Escape) && backPanel.activeSelf)
backPanel.SetActive(false);
else if (Input.GetKeyDown(KeyCode.Escape) && !backPanel.activeSelf)
backPanel.SetActive(true);
}
else if (aSceneName == "LevelSelect")
{
if (Input.GetKeyDown(KeyCode.Escape))
SceneManager.LoadScene("Main Menu");
}
else if (aSceneName != "Settings") //Si la escena activa es algun nivel, abrir menu pausa ------
{
if (Input.GetKeyDown(KeyCode.Escape))
GameObject.FindGameObjectWithTag("UI").transform.Find("PauseButton").GetComponent<PauseButton>().OpenPausePanel();
}
}
public float GetHorizontalAxis()
{
return input.GetHorizontalAxis();
}
public bool GetJumpButton()
{
return input.GetJumpButton();
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using OnlineShopping.Models;
namespace OnlineShopping.Controllers
{
public class MyOrderController : ApiController
{
DbonlineshoppingEntities db = new DbonlineshoppingEntities();
[HttpPost]
public IHttpActionResult PlaceOrder(MyOrderModel myOrderModel)
{
if (myOrderModel.OrderID == 0)
{
MyOrder objcl = new MyOrder();
objcl.OrderID = myOrderModel.OrderID;
objcl.UserID = myOrderModel.UserID;
objcl.OrderTotal = myOrderModel.OrderTotal;
objcl.OrderDate = DateTime.Now;
db.MyOrders.Add(objcl);
db.SaveChanges();
int id = objcl.OrderID;
foreach (var item in myOrderModel.CartModel)
{
OrderDetail orderDetail = new OrderDetail();
orderDetail.OrderDate = DateTime.Now;
orderDetail.TotalPrice = (int)item.TotalPrice;
orderDetail.Quantity = item.Quantity;
orderDetail.OrderID = id;
orderDetail.ProductID = item.ProductID;
db.OrderDetails.Add(orderDetail);
db.SaveChanges();
try
{
var productData = db.Products.Where(p => p.ProductID == item.ProductID).FirstOrDefault();
{
// Product product = new Product();
productData.Quantity = productData.Quantity - item.Quantity;
if (productData.Quantity == 0)
{
productData.InStock = false;
}
else
{
productData.InStock = true;
}
productData.ModifiedDate = DateTime.Now;
db.Entry(productData).State = EntityState.Modified;
db.SaveChanges();
}
}
catch (Exception exp)
{
return Ok(exp);
}
var cart = db.Carts.Where(w => w.CartID == item.CartID).FirstOrDefault();
if (cart != null)
{
db.Carts.Remove(cart);
db.SaveChanges();
}
}
}
return Ok("Success");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kingdee.CAPP.Model;
using Kingdee.CAPP.DAL;
using System.Data;
using Kingdee.CAPP.Common.ModuleHelper;
using Kingdee.CAPP.Common.Serialize;
/*******************************
* Created By franco
* Description: process card business layer
*******************************/
namespace Kingdee.CAPP.BLL
{
public class ProcessCardBLL
{
/// <summary>
/// 方法说明:根据ID获取卡片数据
/// 作 者:jason.tang
/// 完成时间:2013-03-11
/// </summary>
/// <param name="Id">卡片ID</param>
/// <returns></returns>
public ProcessCard GetProcessCard(Guid Id)
{
//LazyProcessCard
List<LazyProcessCard> lazyProcessCardModuleList = new List<LazyProcessCard>();
LazyProcessCard card = new LazyProcessCard();
try
{
DataSet ds = ProcessCardDAL.GetProcessCardDataset(Id);
ModleHandler<LazyProcessCard> processCardHandler
= new ModleHandler<LazyProcessCard>();
lazyProcessCardModuleList = processCardHandler.GetModelByDataSet(ds);
card = lazyProcessCardModuleList[0];
card.LazyCardXMLLoader = GetCards;
}
catch
{
throw;
}
return card;
}
/// <summary>
/// 方法说明: 根据条件获取卡片列表
/// 作 者:jason.tang
/// 完成时间:2013-06-20
/// </summary>
/// <param name="processCardName">卡片名称</param>
/// <returns></returns>
public static List<ProcessCard> GetProcessCardListByCondition(string processCardName)
{
DataSet ds = ProcessCardDAL.GetProcessCardDatasetByCondition(processCardName);
ModleHandler<ProcessCard> processCardHandler = new ModleHandler<ProcessCard>();
List<ProcessCard> processCardList = new List<ProcessCard>();
try
{
processCardList = processCardHandler.GetModelByDataSet(ds);
}
catch
{
throw;
}
return processCardList;
}
/// <summary>
/// 方法说明:获取卡片
/// 作 者:jason.tang
/// 完成时间:2013-06-20
/// </summary>
/// <returns></returns>
public static List<ProcessCard> GetDefaultProcessCardList()
{
DataSet ds = ProcessCardDAL.GetDefaultProcessCardDataset();
ModleHandler<ProcessCard> processCardHandler = new ModleHandler<ProcessCard>();
List<ProcessCard> processCardList = new List<ProcessCard>();
try
{
processCardList = processCardHandler.GetModelByDataSet(ds);
}
catch
{
throw;
}
return processCardList;
}
/// <summary>
/// 方法说明:获取工艺文件夹
/// 作 者:jason.tang
/// 完成时间:2013-08-23
/// </summary>
/// <param name="parentFolder">父文件夹</param>
/// <returns></returns>
public static List<ProcessFolder> GetProcessFolderList(string parentFolder)
{
DataSet ds = ProcessCardDAL.GetProcessFolderListDataSet(parentFolder);
ModleHandler<ProcessFolder> processFolderHandler = new ModleHandler<ProcessFolder>();
List<ProcessFolder> processFolderList = new List<ProcessFolder>();
try
{
processFolderList = processFolderHandler.GetModelByDataSet(ds);
}
catch
{
throw;
}
return processFolderList;
}
/// <summary>
/// 方法说明:获取对应文件夹下的工艺文件
/// 作 者:jason.tang
/// 完成时间:2013-08-23
/// </summary>
/// <param name="folderId">文件夹Id</param>
/// <returns></returns>
public static List<ProcessVersion> GetProcessCardByFolderId(string folderId, int categoryid)
{
DataSet ds = ProcessCardDAL.GetProcessCardByFolderIdDataSet(folderId, categoryid);
ModleHandler<ProcessVersion> processVersionHandler = new ModleHandler<ProcessVersion>();
List<ProcessVersion> processVersionList = new List<ProcessVersion>();
try
{
processVersionList = processVersionHandler.GetModelByDataSet(ds);
}
catch
{
throw;
}
return processVersionList;
}
/// <summary>
/// get card module XML by id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public CardsXML GetCards(Guid id)
{
string cardxml = string.Empty;
CardsXML card = null;
try
{
cardxml = ProcessCardDAL.GetCardXML(id);
card = SerializeHelper
.DeserializeXMLChar<CardsXML>(cardxml);
}
catch (Exception)
{
throw;
}
return card;
}
/// <summary>
/// 方法说明:卡片新增
/// 作 者:jason.tang
/// 完成时间:2013-03-11
/// </summary>
/// <param name="card">卡片实体</param>
/// <returns>Guid</returns>
public Guid InsertProcessCard(ProcessCard card)
{
Guid result;
try
{
result = ProcessCardDAL.AddProcessCard(card);
}
catch
{
throw;
}
return result;
}
/// <summary>
/// 方法说明:卡片版本新增
/// 作 者:jason.tang
/// 完成时间:2013-08-23
/// </summary>
/// <param name="version">卡片版本实体</param>
/// <returns>True/False</returns>
public static bool InsertProcessVersion(ProcessVersion version, object material)
{
bool result = false;
try
{
result = ProcessCardDAL.AddProcessVersion(version, material);
}
catch
{
throw;
}
return result;
}
/// <summary>
/// 方法说明:卡片版本删除
/// 作 者:jason.tang
/// 完成时间:2013-08-23
/// </summary>
/// <param name="baseid">卡片Id</param>
/// <param name="folderid">文件夹ID</param>
/// <returns>True/False</returns>
public static bool DeleteProcessVersion(string baseid, string folderid)
{
bool result = false;
try
{
result = ProcessCardDAL.DeleteProcessVersion(baseid, folderid);
}
catch
{
throw;
}
return result;
}
/// <summary>
/// 方法说明:卡片修改
/// 作 者:jason.tang
/// 完成时间:2013-03-11
/// </summary>
/// <param name="card">卡片实体</param>
/// <returns></returns>
public bool UpdateProcessCard(ProcessCard card)
{
bool result = false;
try
{
result = ProcessCardDAL.UpdateProcessCard(card);
}
catch
{
throw;
}
return result;
}
/// <summary>
/// 方法说明:根据卡片ID删除卡片
/// 作 者:jason.tang
/// 完成时间:2013-07-30
/// </summary>
/// <param name="cardid">卡片ID</param>
/// <returns></returns>
public static bool DeleteProcessCard(string cardid)
{
bool result = true;
try
{
result = ProcessCardDAL.DeleteProcessCard(cardid);
}
catch
{
throw;
}
return result;
}
/// <summary>
/// 方法说明:获取用户数据
/// 作 者:jason.tang
/// 完成时间:2013-09-10
/// </summary>
/// <returns></returns>
public static DataTable GetUsers()
{
DataTable dt = null;
try
{
DataSet ds = ProcessCardDAL.GetUsersDataset();
if (ds != null && ds.Tables.Count > 0)
dt = ds.Tables[0];
}
catch
{ }
return dt;
}
/// <summary>
/// 方法说明:获取工艺卡片数据
/// 作 者:jason.tang
/// 完成时间:2013-09-10
/// </summary>
/// <param name="condition">条件</param>
/// <returns></returns>
public static List<ProcessCard> GetProcessVersion(string condition)
{
DataSet ds = ProcessCardDAL.GetProcessVersionDataSet(condition);
ModleHandler<ProcessCard> processCardHandler = new ModleHandler<ProcessCard>();
List<ProcessCard> processCardList = new List<ProcessCard>();
try
{
processCardList = processCardHandler.GetModelByDataSet(ds);
}
catch
{
throw;
}
return processCardList;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kadastr.Data.Model
{
class OldNumber
{
public int Id { get; set; }
/// <summary>
/// Тип (кадастровый, условный, инвентарный, иной)
/// </summary>
public string Type { get; set; }
/// <summary>
/// Номер
/// </summary>
public string Number { get; set; }
/// <summary>
/// Дата
/// </summary>
public DateTime? Date { get; set; }
/// <summary>
/// Орган(организация) присвоивший номер
/// </summary>
public string Organ { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace graphred
{
public class Polygon: GraphObject
{
public List<Point> Nodes = new List<Point>();
public Polygon()
{
}
public Polygon(List<Point> N)
{
type = ObjectType.PolyLine;
for (int i = 0; i < N.Count; i++)
Nodes.Add(N[i]);
}
public override void Paint(Graphics gr)
{
Pen P = new Pen(PenColor);
P.Color = Color.FromArgb(Transparancy, P.Color);
SolidBrush B = new SolidBrush(BrushColor);
B.Color = Color.FromArgb(Transparancy, B.Color);
P.Width = PenWidth;
P.Color = Color.FromArgb(Transparancy, P.Color);
Point[] M = new Point[Nodes.Count];
for (int i = 0; i < Nodes.Count; i++)
M[i] = Nodes[i];
gr.FillPolygon(B, M);
gr.DrawPolygon(P, M);
}
public override void Deserialize(string str)
{
String[] substrings = str.Split(',');
PenWidth = (float)Convert.ToSingle(substrings[1]);
Transparancy = (byte)Convert.ToSingle(substrings[2]);
PenColor = Color.FromArgb(Transparancy,
(byte)Convert.ToSingle(substrings[3]),
(byte)Convert.ToSingle(substrings[4]),
(byte)Convert.ToSingle(substrings[5]));
BrushColor = Color.FromArgb(Transparancy,
(byte)Convert.ToSingle(substrings[6]),
(byte)Convert.ToSingle(substrings[7]),
(byte)Convert.ToSingle(substrings[8]));
for (int i = 9; i < substrings.Length - 1; i += 2)
{
Nodes.Add(new Point((int)Convert.ToSingle(substrings[i]), (int)Convert.ToSingle(substrings[i + 1])));
}
}
public override string Serialize()
{
string str = "M," + Convert.ToString(PenWidth) + ","
+ Convert.ToString(Transparancy) + ","
+ Convert.ToString(PenColor.R) + ","
+ Convert.ToString(PenColor.G) + ","
+ Convert.ToString(PenColor.B) + ","
+ Convert.ToString(BrushColor.R) + ","
+ Convert.ToString(BrushColor.G) + ","
+ Convert.ToString(BrushColor.B);
for (int i = 0; i < Nodes.Count; i++)
{
str += "," + Convert.ToString(Nodes[i].X) + ","
+ Convert.ToString(Nodes[i].Y);
}
return str;
}
}
}
|
using RSS_news_feed_bot.bot.KeyBoard;
using RSS_news_feed_bot.data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
namespace RSS_news_feed_bot.bot.actionOnMessage
{
class FunnySticker : IAnswer
{
public string PositiveAnswer => string.Empty;
public Dictionary<string, string> NegativeAnswer => new Dictionary<string, string>();
public string CommandDescription => "Ответ стикерами на смайл";
public List<string> CallCommandList
{
get { return new List<string>() { "👋" }; }
}
public void Process(Message message, AllUsers allUsers)
{
string[] stickers = System.IO.File.ReadAllLines(@"Шаблоны\FunnySticker\Список стикеров.txt");
Random rnd = new Random();
Log.WriteLineUserMessage("Отправлен стикер пользователю:", message.Text, message.Chat.Id);
Bot.Bot_SendSticker(message.Chat.Id, stickers[rnd.Next(0, stickers.Length)], new MainKeyboard().KeyboardMarkup);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace ActivityTracker.Models
{
public class Measurement
{
[Required]
public int Amount { get; set; }
public Activity Activity { get; set; }
public Day Day { get; set; }
}
}
|
using System.Collections.Generic;
namespace Core
{
public class ComponentGroup
{
public int ComponentGroupID { get; }
public string ComponentGroupName { get; }
public List<ComponentSubGroup> SubGroupList { get; }
//конструктор
public ComponentGroup(int id, string name)
{
ComponentGroupID = id;
ComponentGroupName = name;
SubGroupList = null;
}
//конструктор с листом подгрупп (нужен, чтобы построить TreeView на складе)
public ComponentGroup(int id, string name, List<ComponentSubGroup> sub_list)
{
ComponentGroupID = id;
ComponentGroupName = name;
SubGroupList = sub_list;
}
//переопределённый ToString
public override string ToString()
{
return ComponentGroupName;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NetManager : SingletonObject<NetManager>
{
void Awake()
{
CreateInstance(this);
#if UNITY_WEBGL && !UNITY_EDITOR
#else
FxNet.FxNetModule.CreateInstance();
FxNet.FxNetModule.Instance().Init();
FxNet.IoThread.CreateInstance();
FxNet.IoThread.Instance().Init();
FxNet.IoThread.Instance().Start();
#endif
}
// Use this for initialization
void Start ()
{
DontDestroyOnLoad(this);
}
// Update is called once per frame
void Update ()
{
#if UNITY_WEBGL && !UNITY_EDITOR
#else
FxNet.FxNetModule.Instance().Run();
#endif
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using LogFile.Analyzer.Core.LogModel;
namespace LogFile.Analyzer.Core
{
public class LogStringParser
{
private static LogString MakeLogString(string log)
{
var logs = log.Split(' ');
var dateTime = DateTimeOffset.Parse($"{logs[1].Substring(1)} {logs[2]} {logs[3]} {logs[4].Substring(0, 5)}");
var dateTimeZone = logs[4].Substring(0, 5);
var ipAddress = IPAddress.Parse(logs[0]);
var httpMethod = logs[5].Substring(1);
var filePath = logs[6];
var httpProtocol = logs[7].Substring(0, logs[7].Length - 1);
var userAgent = logs[9].Substring(1) + " " + logs[10];
var logString = new LogString
{
Ip = ipAddress,
Date = dateTime.DateTime,
HttpMethod = httpMethod,
DateTimeZone = dateTimeZone,
FilePath = filePath,
HttpProtocol = httpProtocol,
StatusCode = int.Parse(logs[8]),
Size = int.Parse(logs[9]),
UserAgent = userAgent
};
return logString;
}
public List<LogString> LogLinesRead(string fileName)
{
var myLogs = new List<LogString>();
if (fileName == "defaut name") return myLogs;
var file = new StreamReader(fileName);
file.BaseStream.Position = 0;
while (file.EndOfStream == false)
myLogs.Add(MakeLogString(file.ReadLine()));
file.Close();
return myLogs;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using ConvenientChests.StackToNearbyChests;
using Harmony;
using StardewValley;
using StardewValley.Locations;
using StardewValley.Menus;
using StardewValley.Objects;
using Object = StardewValley.Object;
namespace ConvenientChests.CraftFromChests {
public class CraftFromChestsModule : Module {
public HarmonyInstance Harmony { get; set; }
public static List<Chest> NearbyChests { get; set; }
public static List<Item> NearbyItems { get; private set; }
private MenuListener MenuListener;
private static IList<IList<Item>> _nearbyInventories;
public static IList<IList<Item>> NearbyInventories {
get => _nearbyInventories;
set {
_nearbyInventories = value;
NearbyItems = value?.SelectMany(l => l.Where(i => i != null)).ToList();
}
}
public CraftFromChestsModule(ModEntry modEntry) : base(modEntry) {
this.MenuListener = new MenuListener(this.Events);
}
public override void Activate() {
IsActive = true;
// Register Events
this.MenuListener.RegisterEvents();
this.MenuListener.CraftingMenuShown += CraftingMenuShown;
this.MenuListener.CraftingMenuClosed += CraftingMenuClosed;
// Apply method patches
Harmony = HarmonyInstance.Create("aEnigma.convenientchests");
CraftingRecipePatch.Register(Harmony);
FarmerPatch.Register(Harmony);
}
public override void Deactivate() {
IsActive = false;
// Unregister Events
this.MenuListener.CraftingMenuShown -= CraftingMenuShown;
this.MenuListener.CraftingMenuClosed -= CraftingMenuClosed;
this.MenuListener.UnregisterEvents();
// Remove method patches
CraftingRecipePatch.Remove(Harmony);
FarmerPatch.Remove(Harmony);
}
private void CraftingMenuShown(object sender, EventArgs e) {
NearbyChests = GetChests(Game1.activeClickableMenu is CraftingPage).ToList();
NearbyInventories = NearbyChests.Select(c => (IList<Item>) c.items).ToList();
}
private static void CraftingMenuClosed(object sender, EventArgs e) {
foreach (var c in NearbyChests)
foreach (var i in c.items.Where(i => i?.Stack == 0 && i.Category != Object.BigCraftableCategory))
c.items[c.items.IndexOf(i)] = null;
NearbyChests = null;
NearbyInventories = null;
}
private IEnumerable<Chest> GetChests(bool isCookingScreen) {
// nearby chests
var chests = Game1.player.GetNearbyChests(Config.CraftRadius).Where(c => c.items.Any(i => i != null)).ToList();
foreach (var c in chests)
yield return c;
// always add fridge when on cooking screen
if (!isCookingScreen)
yield break;
var house = Game1.player.currentLocation as FarmHouse ?? Utility.getHomeOfFarmer(Game1.player);
if (house == null || house.upgradeLevel == 0)
yield break;
var fridge = house.fridge.Value;
if (!chests.Contains(fridge))
yield return fridge;
}
}
} |
using System;
using UnityEngine;
using UnityEditor;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace IzBone.PhysSpring {
using Common;
[CustomEditor(typeof(RootAuthoring))]
[CanEditMultipleObjects]
sealed class RootAuthoringInspector : Editor
{
void OnSceneGUI() {
Gizmos8.drawMode = Gizmos8.DrawMode.Handle;
var tgt = (RootAuthoring)target;
// 登録されているコライダを表示
if ( Common.Windows.GizmoOptionsWindow.isShowCollider ) {
if (tgt.Collider!=null) foreach (var i in tgt.Collider.Bodies) {
if (i == null) continue;
i.DEBUG_drawGizmos();
}
}
foreach (var bone in tgt._bones)
if (bone.targets != null)
foreach (var boneTgt in bone.targets) {
// 末端のTransformを得る
var trns = boneTgt.topOfBone;
if (trns == null) continue;
for (int i=0; i<bone.depth; ++i) trns = trns.GetChild(0);
// ジョイントごとに描画
var posLst = new float3[bone.depth + 1];
posLst[0] = trns.position;
for (int i=0; i<bone.depth; ++i) {
var next = trns.parent;
// 無効なDepth値が指定されていた場合はエラーを出す
if (next == null) {
Debug.LogError("PhySpring:depth is too higher");
continue;
}
posLst[i+1] = next.position;
var iRate = (float)(bone.depth-1-i) / max(bone.depth-1, 1);
// パーティクル本体を描画
if ( Common.Windows.GizmoOptionsWindow.isShowPtclR ) {
Gizmos8.color = Gizmos8.Colors.JointMovable;
var r = length(trns.position - next.position);
Gizmos8.drawSphere(trns.position, bone.radius.evaluate(iRate) * r);
if (i == bone.depth-1) {
Gizmos8.color = Gizmos8.Colors.JointFixed;
Gizmos8.drawSphere(next.position, 0.15f * r);
}
}
// つながりを描画
if ( Common.Windows.GizmoOptionsWindow.isShowConnections ) {
Gizmos8.color = Gizmos8.Colors.BoneMovable;
Gizmos8.drawLine(next.position, trns.position);
}
// 角度範囲を描画
var l2w = (float4x4)next.localToWorldMatrix;
if (
Common.Windows.GizmoOptionsWindow.isShowLimitAgl
&& bone.rotShiftRate < 0.9999f
) {
var pos = l2w.c3.xyz;
var rot = mul(
Math8.fromToRotation(
mul( next.rotation, float3(0,1,0) ),
trns.position - next.position
),
next.rotation
);
// var scl = HandleUtility.GetHandleSize(l2w.c3.xyz)/2;
var scl = length(trns.position - next.position)/2;
Gizmos8.color = Gizmos8.Colors.AngleMargin;
var agl = bone.angleMax.evaluate(iRate);
Gizmos8.drawAngleCone( pos, rot, scl, agl );
Gizmos8.color = Gizmos8.Colors.AngleLimit;
agl *= 1 - bone.angleMargin.evaluate(iRate);
Gizmos8.drawAngleCone( pos, rot, scl, agl );
}
// 移動可能範囲を描画
if (
Common.Windows.GizmoOptionsWindow.isShowLimitPos
&& 0.00001f < bone.rotShiftRate
) {
var sft = bone.shiftMax.evaluate(iRate);
sft *= length(trns.localPosition)/2;
var scl1 = Unity.Mathematics.float4x4.TRS(
0, Unity.Mathematics.quaternion.identity, sft
);
sft *= 1 - bone.shiftMargin.evaluate(iRate);
var scl0 = Unity.Mathematics.float4x4.TRS(
0, Unity.Mathematics.quaternion.identity, sft
);
Gizmos8.color = Gizmos8.Colors.ShiftMargin;
Gizmos8.drawWireCube( mul(l2w, scl1) );
Gizmos8.color = Gizmos8.Colors.ShiftLimit;
Gizmos8.drawWireCube( mul(l2w, scl0) );
}
trns = next;
}
// 描画
// Gizmos8.drawBones(posLst);
}
}
}
}
|
/*
* PlacementIndicator.cs - This updates the position of the reticle when the
* application is first opened. The user can then
* tap on their screen to place the polymer chain using
* the location of the reticle... after which it will
* be hidden.
*
* Mike Hore (hore@case.edu), Case Western Reserve University
* August 2020
*
*
* Copyright 2020 Michael J. A. Hore
*
* 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.
*
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
public class PlacementIndicator : MonoBehaviour
{
public GameObject baseParticle;
private ARRaycastManager rayManager;
private GameObject visual;
private bool isPlaced = false;
void Start ()
{
// get the components
rayManager = FindObjectOfType<ARRaycastManager>();
visual = GameObject.Find("Reticle");
// hide the placement indicator visual
visual.GetComponent<Renderer>().enabled = false;
}
void Update ()
{
// shoot a raycast from the center of the screen
List<ARRaycastHit> hits = new List<ARRaycastHit>();
rayManager.Raycast(new Vector2(Screen.width / 2, Screen.height / 2), hits, TrackableType.PlaneWithinPolygon);
// if we hit an AR plane surface, update the position and rotation
if (hits.Count > 0)
{
transform.position = hits[0].pose.position;
transform.rotation = hits[0].pose.rotation;
// enable the visual if it's disabled
if (visual.GetComponent<Renderer>().enabled == false && isPlaced == false)
{
visual.GetComponent<Renderer>().enabled = true;
}
}
// Check to see if the user has tapped the screen
// to place the simulation. If they have, start the
// simulation and hide the reticle.
if (Input.touchCount > 0 && isPlaced == false)
{
var touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
if (isPlaced == false)
{
Instantiate(baseParticle, transform.position, transform.rotation);
isPlaced = true;
visual.GetComponent<Renderer>().enabled = false;
}
}
}
}
}
|
using NUnit.Framework;
using SingLife.FacebookShareBonus.Model;
using System;
namespace SingLife.FacebookShareBonus.Test
{
[TestFixture]
internal class FacebookBonusCalculatorTests
{
[Test]
public void Calculate_GivenPremiumAndPercentage_IncentivePointsArePercentageOfPolicyPremium()
{
// Arrange
var input = CreateCalculationInputWithSinglePolicy(premium: 200, percentage: 3);
var facebookBonusCalculator = new FacebookBonusCalculator();
const int expectedIncentivePoint = 6;
// Act
var facebookBonus = facebookBonusCalculator.Calculate(input);
// Assert
int actualBonusPoint = facebookBonus.PolicyBonuses[0].BonusInPoints;
Assert.That(actualBonusPoint, Is.EqualTo(expectedIncentivePoint));
}
[Test]
public void Calculate_GivenIncentivePoints_IncentivePointsAreRoundedDownToTheNearestInteger()
{
// Arrange
var input = CreateCalculationInputWithSinglePolicy(premium: 133, percentage: 3);
var facebookBonusCalculator = new FacebookBonusCalculator();
const int expectedBonusPoint = 3;
// Act
var facebookBonus = facebookBonusCalculator.Calculate(input);
// Assert
var actualBonusPoint = facebookBonus.PolicyBonuses[0].BonusInPoints;
Assert.That(actualBonusPoint, Is.EqualTo(expectedBonusPoint));
}
[Test]
public void Calculate_GivenCustomerPolicies_InctivePointsAreCalculatedForEachPolicy()
{
// Arrange
var input = CreateCalculationInputWith3Policies();
var facebookBonusCalculator = new FacebookBonusCalculator();
const int expectedFirstPolicyBonus = 6;
const int expectedSecondPolicyBonus = 3;
// Act
var facebookBonus = facebookBonusCalculator.Calculate(input);
// Assert
int actualFirstPolicyPoint = facebookBonus.PolicyBonuses[0].BonusInPoints;
int actualSecondPolicyPoint = facebookBonus.PolicyBonuses[1].BonusInPoints;
Assert.That(actualFirstPolicyPoint, Is.EqualTo(expectedFirstPolicyBonus));
Assert.That(actualSecondPolicyPoint, Is.EqualTo(expectedSecondPolicyBonus));
}
[Test]
public void Calculate_DescendingSortByPolicyNumbersIsSpecifiedInSettings_PoliciesAreSortedByDecendingOrderOfPolicyNumbers()
{
// Arrange
var input = CreateCalculationInputWith3Policies();
input.Settings.PolicySorter = new DescendingOrderOfPoliciesNumber();
var facebookBonusCalculator = new FacebookBonusCalculator();
// Act
var facebookBonus = facebookBonusCalculator.Calculate(input);
// Assert
Assert.That(facebookBonus.PolicyBonuses, Is.Ordered.Descending.By(nameof(PolicyBonus.PolicyNumber)));
}
[Test]
public void Calculate_BonusLimitIsSpecifiedInFacebookBonusSettings_TotalPointsShouldNotExceedTheLimit()
{
// Arrange
var input = CreateCalculationInputWith3Policies();
var facebookBonusCalculator = new FacebookBonusCalculator();
const int maxiumBonus = 10;
// Act
var facebookBonus = facebookBonusCalculator.Calculate(input);
// Assert
int totalPoint = facebookBonus.Total;
Assert.That(totalPoint, Is.LessThanOrEqualTo(maxiumBonus));
}
[Test]
public void Calculate_BonusLimitIsSpecifiedInFacebookBonusSettings_BonusPointsAreDistributedCorrectly()
{
// Arrange
var input = CreateCalculationInputWith3Policies();
var facebookBonusCalculator = new FacebookBonusCalculator();
const int expecctedFirstBonusPoints = 6;
const int expecctedSecondBonusPoints = 3;
const int expecctedThirdBonusPoints = 1;
// Act
var facebookBonus = facebookBonusCalculator.Calculate(input);
// Assert
var actualFirstBonusPoints = facebookBonus.PolicyBonuses[0].BonusInPoints;
var actualSecondBonusPoints = facebookBonus.PolicyBonuses[1].BonusInPoints;
var actualThirdBonusPoints = facebookBonus.PolicyBonuses[2].BonusInPoints;
Assert.That(actualFirstBonusPoints, Is.EqualTo(expecctedFirstBonusPoints));
Assert.That(actualSecondBonusPoints, Is.EqualTo(expecctedSecondBonusPoints));
Assert.That(actualThirdBonusPoints, Is.EqualTo(expecctedThirdBonusPoints));
}
private FacebookBonusCalculationInput CreateCalculationInputWithSinglePolicy(decimal premium, float percentage)
{
var policy = new Policy() { PolicyNumber = "P001", Premium = premium, StartDate = new DateTime(2016, 05, 06) };
var settings = new FacebookBonusSettings()
{
BonusPercentage = percentage,
};
return new FacebookBonusCalculationInput()
{
PoliciesOfCustomer = new Policy[] { policy },
Settings = settings
};
}
private FacebookBonusCalculationInput CreateCalculationInputWith3Policies()
{
var firstPolicy = new Policy() { PolicyNumber = "P001", Premium = 200, StartDate = new DateTime(2016, 05, 06) };
var secondPolicy = new Policy() { PolicyNumber = "P002", Premium = 100, StartDate = new DateTime(2017, 08, 11) };
var thirdPolicy = new Policy() { PolicyNumber = "P003", Premium = 100, StartDate = new DateTime(2017, 09, 12) };
var settings = new FacebookBonusSettings()
{
BonusPercentage = 3,
MaximumBonus = 10,
PolicySorter = new FakeSortOrder()
};
return new FacebookBonusCalculationInput()
{
PoliciesOfCustomer = new Policy[] { firstPolicy, secondPolicy, thirdPolicy },
Settings = settings
};
}
}
} |
using Alabo.Datas.Stores;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Dtos;
using Alabo.Domains.Entities;
using Alabo.Domains.Services.Tree;
using Alabo.Extensions;
using Alabo.Validations.Aspects;
using System;
using System.Linq.Expressions;
namespace Alabo.Domains.Services.Update {
public abstract class UpdateBase<TEntity, TKey> : TreeBaseAsync<TEntity, TKey>, IUpdate<TEntity, TKey>
where TEntity : class, IAggregateRoot<TEntity, TKey> {
protected UpdateBase(IUnitOfWork unitOfWork, IStore<TEntity, TKey> store) : base(unitOfWork, store) {
}
public bool Update([Valid] TEntity model) {
var cacheKey = $"{typeof(TEntity).Name}_ReadCache_{model.Id.ToStr().Trim()}";
ObjectCache.Remove(cacheKey);
return Store.UpdateSingle(model);
}
public bool UpdateNoTracking(TEntity model) {
var cacheKey = $"{typeof(TEntity).Name}_ReadCache_{model.Id.ToStr().Trim()}";
ObjectCache.Remove(cacheKey);
return Store.UpdateNoTracking(model);
}
public bool Update(Action<TEntity> updateAction, Expression<Func<TEntity, bool>> predicate = null) {
return Store.Update(updateAction, predicate);
}
public bool Update<TUpdateRequest>([Valid] TUpdateRequest request) where TUpdateRequest : IRequest, new() {
throw new NotImplementedException();
//return Store.Update(request);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using _08.SumTwoArrays;
namespace _11.SumPolinomials
{
class AddingTwoPolynomials
{
//not working properly if 0 is used
static void Main(string[] args)
{
Console.WriteLine("Please enter variable for your equation!");
string var = Console.ReadLine();
Console.WriteLine("Enter the number of the highest math pow of '{0}' for the first polynomial!", var);
int varPow = int.Parse(Console.ReadLine());
int[] array = new int[varPow + 1];
CreateFirstPolynomial(array, var, varPow);
Console.WriteLine();
Console.WriteLine("Enter the number of the highest math pow of '{0}' for the second polynomial!", var);
int varPow2 = int.Parse(Console.ReadLine());
int[] array2 = new int[varPow2 + 1];
CreateSecondPolynomial(array2, var, varPow2);
DoMath.FindFinalSum(array, array2);
}
static string CreateFirstPolynomial(int[] array, string var, int varPow)
{
for (int powSeq = 0; powSeq < array.Length; powSeq++)
{
Console.Write("Enter coefficient for {0}^{1}: ", var, powSeq);
array[powSeq] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Your first polynomial is:");
PrintFirstPolynomial(array, varPow, var);
return var;
}
static string PrintFirstPolynomial(int[] array, int varPow, string var)
{
for (int index = 0; index <= varPow; index++)
{
Console.Write("{0}{1}^{2} + ", array[index], var, index);
};
Console.WriteLine();
return var;
}
static string CreateSecondPolynomial(int[] array2, string var, int varPow2)
{
for (int powSeq = 0; powSeq < array2.Length; powSeq++)
{
Console.Write("Enter coefficient for {0}^{1}: ", var, powSeq);
array2[powSeq] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Your second polynomial is:");
PrintSecondPolynomial(array2, varPow2, var);
return var;
}
static string PrintSecondPolynomial(int[] array2, int varPow2, string var)
{
for (int index = 0; index <= varPow2; index++)
{
Console.Write("{0}{1}^{2} + ", array2[index], var, index);
};
Console.WriteLine();
return var;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmartHome.StatusWriters
{
public interface IStatusWriter
{
//this is an Observer Interface that observers status changes
// there may be many observers as a list
//this is the method that update the change
void DeviceStatusChanged(Device device);
}
}
|
using System;
namespace gView.Framework.IO
{
public class XmlStreamOption : XmlStreamObject
{
private object[] _values;
public XmlStreamOption()
: base()
{
}
public XmlStreamOption(object[] values, object selected)
: base(selected)
{
_values = values;
}
public object[] Options
{
get { return _values; }
internal set { _values = value; }
}
}
public class XmlStreamOption<T> : XmlStreamOption
{
public XmlStreamOption(T[] values, T selected)
: base(Options(values), selected)
{
}
new internal static object[] Options(T[] values)
{
if (values == null)
{
return null;
}
object[] ret = new object[values.Length];
Array.Copy(values, ret, values.Length);
return ret;
}
}
}
|
using kolos1.DTOs.Responses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace kolos1.Services
{
public interface IMedicamentsDbService
{
public List<PrescriptionResponse> GetLek(string id);
public String DeletePatient(string id);
}
}
|
//-----------------------------------------------------------------------
// <copyright file="CustomContext.cs" company="Caspian Pacific Tech">
// Copyright (c) Caspian Pacific Tech. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace SmartLibrary.Services
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Linq;
using Infrastructure;
using SmartLibrary.DataContext;
using SmartLibrary.Models;
/// <summary>
/// CustomContext
/// </summary>
public sealed class CustomContext : ServiceContext
{
/// <summary>
/// Login method
/// </summary>
/// <param name="email">email</param>
/// <param name="password">password</param>
/// <returns> return login response</returns>
public DataSet UserLogin(string email, string password)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "Email", Value = email, DBType = DbType.String });
parameters.Add(new DBParameters() { Name = "Password", Value = password, DBType = DbType.String });
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPUserLogin", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Login method for customer
/// </summary>
/// <param name="email">email</param>
/// <param name="password">password</param>
/// <returns> return login response</returns>
public DataSet CustomerLogin(string email, string password)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "Email", Value = email, DBType = DbType.String });
parameters.Add(new DBParameters() { Name = "Password", Value = password, DBType = DbType.String });
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPCustomerLogin", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Login method for customer
/// </summary>
/// <param name="email">email</param>
/// <returns> return login response</returns>
public DataSet CustomerLoginwithEmail(string email)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "UserEmail", Value = email, DBType = DbType.String });
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPCustomerLoginWithEmail", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Login method for customer
/// </summary>
/// <param name="email">email</param>
/// <returns> return login response</returns>
public DataSet UserLoginwithEmail(string email)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "UserEmail", Value = email, DBType = DbType.String });
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPUserLoginWithEmail", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// GetPageAccessBasedOnUserRole
/// </summary>
/// <param name="roleId">roleId</param>
/// <returns>page access list</returns>
public DataSet GetPageAccessBasedOnUserRole(int? roleId)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "RoleId", Value = roleId, DBType = DbType.Int32 });
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPGetPageAccessBasedOnUserRole", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// ChangeUserPassword
/// </summary>
/// <param name="id">id</param>
/// <param name="password">password</param>
/// <param name="spfor">spfor</param>
/// <returns>bool</returns>
public bool ChangeUserPassword(int id, string password, string spfor)
{
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "Id", Value = id, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "NewPassword", Value = password, DBType = DbType.String });
parameters.Add(new DBParameters() { Name = "SPFor", Value = spfor, DBType = DbType.String });
this.ExecuteProcedure("CUSPChangePassword", ExecuteType.ExecuteDataSet, parameters);
return true;
}
/// <summary>
/// DeletePageAccessBasedOnUserRole
/// </summary>
/// <param name="roleId">roleId</param>
/// <returns>page access list</returns>
public DataSet DeletePageAccessBasedOnUserRole(int? roleId)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "RoleId", Value = roleId, DBType = DbType.Int32 });
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPDeletePageAccessBasedOnRole", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Check the Reference
/// </summary>
/// <param name="tabletype">table type</param>
/// <param name="primarykey">primary key</param>
/// <returns>dataset of reference table with count </returns>
public DataSet CheckReferenceOfPrimaryKey(int tabletype, int primarykey)
{
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "TableType", Value = tabletype, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "PrimaryKey", Value = primarykey, DBType = DbType.Int32 });
return (DataSet)this.ExecuteProcedure("CUSPCheckForForeignKeyConstriant", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Masters the drop-down bind.
/// </summary>
/// <param name="masterDropDownType">Type of the master drop down.</param>
/// <param name="isActive">The is active.</param>
/// <param name="filterId">The filter identifier.</param>
/// <param name="isAddBlank">need this pram for select2 plug-in</param>
/// <param name="filterText">the filter text</param>
/// <param name="filterBool">the filter boolean</param>
/// <returns>List of items</returns>
public IList<MasterDropdown> MasterDropdownBind(int masterDropDownType, bool? isActive = null, int? filterId = null, bool isAddBlank = false, string filterText = "", bool? filterBool = null)
{
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "MasterDropDownType", Value = masterDropDownType, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "Active", Value = isActive, DBType = DbType.Boolean });
parameters.Add(new DBParameters() { Name = "FilterID", Value = filterId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "FilterText", Value = filterText, DBType = DbType.String });
if (filterBool.HasValue)
{
parameters.Add(new DBParameters() { Name = "FilterBool", Value = filterBool, DBType = DbType.Boolean });
}
var result = this.ExecuteProcedure<MasterDropdown>("CUSPMasterDropdownBind", parameters);
if (isAddBlank)
{
result.Insert(0, new MasterDropdown() { ID = string.Empty, Name = string.Empty });
}
return result;
}
/// <summary>
/// Get Book Borrowed Details
/// </summary>
/// <param name="bookId">bookId</param>
/// <param name="statusId">statusId</param>
/// <param name="active">active</param>
/// <param name="startRowIndex">startRowIndex</param>
/// <param name="endRowIndex">endRowIndex</param>
/// <param name="sortExpression">sortExpression</param>
/// <param name="sortDirection">sortDirection</param>
/// <param name="searchText">searchText</param>
/// <returns>Get Books Borrowed Details</returns>
public DataSet GetBookBorrowedDetails(int bookId, int? statusId = null, int? active = 1, int? startRowIndex = null, int? endRowIndex = null, string sortExpression = null, string sortDirection = null, string searchText = null)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "BookId", Value = bookId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "StatusId", Value = statusId, DBType = DbType.Int32 });
if (active != null)
{
parameters.Add(new DBParameters() { Name = "Active", Value = active, DBType = DbType.Int32 });
}
if (startRowIndex != null && endRowIndex != null)
{
parameters.Add(new DBParameters() { Name = "StartRowIndex", Value = startRowIndex, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "EndRowIndex", Value = endRowIndex, DBType = DbType.Int32 });
}
if (!string.IsNullOrEmpty(sortExpression) && !string.IsNullOrEmpty(sortDirection))
{
parameters.Add(new DBParameters() { Name = "SortExpression", Value = sortExpression, DBType = DbType.String });
parameters.Add(new DBParameters() { Name = "SortDirection", Value = sortDirection, DBType = DbType.String });
}
if (!string.IsNullOrEmpty(searchText))
{
parameters.Add(new DBParameters() { Name = "SearchText", Value = searchText, DBType = DbType.String });
}
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPGetBookBorrowedDetails", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Get Book Details Complete
/// </summary>
/// <param name="bookId">bookId</param>
/// <param name="customerId">Customer Id</param>
/// <returns>Get BooksDetails</returns>
public DataSet GetBookDetailsComplete(int bookId, int? customerId = null)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "BookId", Value = bookId, DBType = DbType.Int32 });
if (customerId != null)
{
parameters.Add(new DBParameters() { Name = "CustomerId", Value = customerId, DBType = DbType.Int32 });
}
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPLatestBookBorrower", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Get Book Details of Customer
/// </summary>
/// <param name="customerId">customerId</param>
/// <param name="searchText">searchText</param>
/// <param name="startRowIndex">startRowIndex</param>
/// <param name="endRowIndex">endRowIndex</param>
/// <param name="sortExpression">Sort Expression</param>
/// <param name="sortDirection">Sort Direction</param>
/// <returns>Get BooksDetails</returns>
public DataSet GetBookDetailsOfCustomer(int customerId, string searchText, int? startRowIndex, int? endRowIndex, string sortExpression, string sortDirection)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "CustomerID", Value = customerId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "SearchText", Value = searchText, DBType = DbType.String });
if (startRowIndex != null && endRowIndex != null)
{
parameters.Add(new DBParameters() { Name = "StartRowIndex", Value = startRowIndex, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "EndRowIndex", Value = endRowIndex, DBType = DbType.Int32 });
}
if (!string.IsNullOrEmpty(sortExpression) && !string.IsNullOrEmpty(sortDirection))
{
parameters.Add(new DBParameters() { Name = "SortExpression", Value = sortExpression, DBType = DbType.String });
parameters.Add(new DBParameters() { Name = "SortDirection", Value = sortDirection, DBType = DbType.String });
}
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPBookHistoryOfCustomer", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Get Book Details of Customer
/// </summary>
/// <param name="customerId">customerId</param>
/// <param name="searchText">searchText</param>
/// <param name="startRowIndex">startRowIndex</param>
/// <param name="endRowIndex">endRowIndex</param>
/// <param name="sortExpression">Sort Expression</param>
/// <param name="sortDirection">Sort Direction</param>
/// <returns>Get Space Details</returns>
public DataSet GetSpaceDetailsOfCustomer(int customerId, string searchText, int? startRowIndex, int? endRowIndex, string sortExpression, string sortDirection)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "CustomerID", Value = customerId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "SearchText", Value = searchText, DBType = DbType.String });
if (startRowIndex != null && endRowIndex != null)
{
parameters.Add(new DBParameters() { Name = "StartRowIndex", Value = startRowIndex, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "EndRowIndex", Value = endRowIndex, DBType = DbType.Int32 });
}
if (!string.IsNullOrEmpty(sortExpression) && !string.IsNullOrEmpty(sortDirection))
{
parameters.Add(new DBParameters() { Name = "SortExpression", Value = sortExpression, DBType = DbType.String });
parameters.Add(new DBParameters() { Name = "SortDirection", Value = sortDirection, DBType = DbType.String });
}
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPSpaceHistoryOfCustomer", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Get Current book status
/// </summary>
/// <param name="bookId">bookId</param>
/// <param name="active">active</param>
/// <returns>return book status</returns>
public DataSet GetCurrentBookStatus(int bookId, int? active)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "BookId", Value = bookId, DBType = DbType.Int32 });
if (active != null)
{
parameters.Add(new DBParameters() { Name = "Active", Value = active, DBType = DbType.Int32 });
}
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPGetCurrentBookStatus", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Accept Cancel Book Borrow Request
/// </summary>
/// <param name="bookId">bookId</param>
/// <param name="userId">userId</param>
/// <param name="statusId">statusId</param>
/// <param name="borrowId">borrowId</param>
/// <param name="bookperiod">bookperiod</param>
/// <returns>return status</returns>
public DataSet AcceptCancelBookBorrowRequest(int bookId, int userId, int statusId, int borrowId, int bookperiod)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "BookId", Value = bookId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "UserId", Value = userId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "StatusId", Value = statusId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "BorrowId", Value = borrowId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "ActivityDate", Value = DateTime.Now, DBType = DbType.DateTime });
parameters.Add(new DBParameters() { Name = "BookPeriodValue", Value = bookperiod, DBType = DbType.Int32 });
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPAcceptCancelBookBorrowRequest", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Book Return
/// </summary>
/// <param name="bookId">bookId</param>
/// <param name="userId">userId</param>
/// <param name="borrowId">borrowId</param>
/// <param name="returnNotes">returnNotes</param>
/// <param name="returnDate">returnDate</param>
/// <returns>return status</returns>
public DataSet BookReturn(int bookId, int userId, int borrowId, string returnNotes, DateTime returnDate)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "BookId", Value = bookId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "UserId", Value = userId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "BorrowId", Value = borrowId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "returnNotes", Value = returnNotes, DBType = DbType.String });
parameters.Add(new DBParameters() { Name = "ActivityDate", Value = returnDate, DBType = DbType.DateTime });
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPBookReturn", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Check Book Pending Entry
/// </summary>
/// <param name="bookId">bookId</param>
/// <param name="customerId">customerId</param>
/// <returns>return status</returns>
public DataSet CheckBookPendingEntry(int bookId, int customerId)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "BookId", Value = bookId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "CustomerId", Value = customerId, DBType = DbType.Int32 });
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPCheckBookPendingEntry", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// GetCheckBookBorrowStatus
/// </summary>
/// <param name="bookId">bookId</param>
/// <param name="customerId">customerId</param>
/// <returns>return status</returns>
public DataSet GetCheckBookBorrowStatus(int bookId, int customerId)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "BookId", Value = bookId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "CustomerId", Value = customerId, DBType = DbType.Int32 });
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPCheckBookBorrowStatus", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Get Book Comments
/// </summary>
/// <param name="bookId">bookId</param>
/// <param name="searchText">searchText</param>
/// <param name="startRowIndex">startRowIndex</param>
/// <param name="endRowIndex">endRowIndex</param>
/// <param name="sortExpression">Sort Expression</param>
/// <param name="sortDirection">Sort Direction</param>
/// <returns>Get Book Discussions</returns>
public DataSet GetBookDiscussions(int bookId, string searchText, int? startRowIndex, int? endRowIndex, string sortExpression, string sortDirection)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "BookId", Value = bookId, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "SearchText", Value = searchText, DBType = DbType.String });
if (startRowIndex != null && endRowIndex != null)
{
parameters.Add(new DBParameters() { Name = "StartRowIndex", Value = startRowIndex, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "EndRowIndex", Value = endRowIndex, DBType = DbType.Int32 });
}
if (!string.IsNullOrEmpty(sortExpression) && !string.IsNullOrEmpty(sortDirection))
{
parameters.Add(new DBParameters() { Name = "SortExpression", Value = sortExpression, DBType = DbType.String });
parameters.Add(new DBParameters() { Name = "SortDirection", Value = sortDirection, DBType = DbType.String });
}
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPBookDiscussions", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Get Todays Activities
/// </summary>
/// <param name="requestType">requestType</param>
/// <param name="fromDate">fromDate</param>
/// <param name="toDate">toDate</param>
/// <param name="active">active</param>
/// <param name="customerId">customerId</param>
/// <param name="searchText">searchText</param>
/// <param name="startRowIndex">startRowIndex</param>
/// <param name="endRowIndex">endRowIndex</param>
/// <param name="sortExpression">Sort Expression</param>
/// <param name="sortDirection">Sort Direction</param>
/// <param name="status">status</param>
/// <returns>Return today's activities</returns>
public DataSet GetTodaysActivities(string requestType, DateTime? fromDate, DateTime? toDate, int active = 1, int? customerId = null, string searchText = null, int? startRowIndex = null, int? endRowIndex = null, string sortExpression = "", string sortDirection = "", string status = "")
{
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "Type", Value = requestType, DBType = DbType.String });
parameters.Add(new DBParameters() { Name = "Active", Value = active, DBType = DbType.Int32 });
if (fromDate != null)
{
parameters.Add(new DBParameters() { Name = "FromDate", Value = fromDate, DBType = DbType.DateTime });
}
if (toDate != null)
{
parameters.Add(new DBParameters() { Name = "ToDate", Value = toDate, DBType = DbType.DateTime });
}
if (customerId != null)
{
parameters.Add(new DBParameters() { Name = "CustomerId", Value = customerId, DBType = DbType.Int32 });
}
if (!string.IsNullOrEmpty(status))
{
parameters.Add(new DBParameters() { Name = "status", Value = status, DBType = DbType.String });
}
parameters.Add(new DBParameters() { Name = "SearchText", Value = searchText, DBType = DbType.String });
if (startRowIndex != null && endRowIndex != null)
{
parameters.Add(new DBParameters() { Name = "StartRowIndex", Value = startRowIndex, DBType = DbType.Int32 });
parameters.Add(new DBParameters() { Name = "EndRowIndex", Value = endRowIndex, DBType = DbType.Int32 });
}
if (!string.IsNullOrEmpty(sortExpression) && !string.IsNullOrEmpty(sortDirection))
{
parameters.Add(new DBParameters() { Name = "SortExpression", Value = sortExpression, DBType = DbType.String });
parameters.Add(new DBParameters() { Name = "SortDirection", Value = sortDirection, DBType = DbType.String });
}
return (DataSet)this.ExecuteProcedure("CUSPGetTodaysActivities", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// get records from custom procedure
/// </summary>
/// <typeparam name="TEntity">Entity Type which require to be return as list</typeparam>
/// <param name="procedureName">procedureName </param>
/// <param name="parameter">parameter </param>
/// <returns>list of data</returns>
public IList<TEntity> SearchByProcedure<TEntity>(string procedureName, object parameter)
{
System.Collections.ObjectModel.Collection<DBParameters> parameters = AddParameters(parameter, true);
return this.ExecuteProcedure<TEntity>(procedureName, parameters);
}
/// <summary>
/// Check Book Pending Entry
/// </summary>
/// <param name="reportfor">reportfor</param>
/// <returns>return ReportCount</returns>
public DataSet GetCountForReport()
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
////parameters.Add(new DBParameters() { Name = "ReportFor", Value = reportfor, DBType = DbType.Int32 });
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPReports", ExecuteType.ExecuteDataSet, parameters);
}
/// <summary>
/// Scheduler Run for All Pending Requests
/// </summary>
/// <param name="schedulerDate">schedulerDate</param>
/// <returns>return Status</returns>
public DataSet SchedulerRunforAllPendingRequests(DateTime schedulerDate)
{
/*Add Parameters*/
System.Collections.ObjectModel.Collection<DBParameters> parameters = new System.Collections.ObjectModel.Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "SchedulerDate", Value = schedulerDate, DBType = DbType.DateTime });
/*Convert Dataset to Model List object*/
return (DataSet)this.ExecuteProcedure("CUSPCancelPendingRequestByScheduler", ExecuteType.ExecuteDataSet, parameters);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataAccess.Concrete.EntityFramework.Abstract;
using Entities.Concrete;
namespace DataAccess.Concrete.EntityFramework.Concrete
{
public class EfColorDal:EfEntityRepository<Color,ReCapContext>, IColorDal
{
}
}
|
/*
******************************************************************************
* @file : Program.cs
* @Copyright: ViewTool
* @Revision : ver 1.0
* @Date : 2015/02/09 17:31
* @brief : Program demo
******************************************************************************
* @attention
*
* Copyright 2009-2015, ViewTool
* http://www.viewtool.com/
* All Rights Reserved
*
******************************************************************************
*/
/*
Hardware Connection (This is for your reference only)
BH1750FVI Ginkgo USB-I2C Adapter
1.VCC <--> VCC(Pin2)
2.ADDR <--> GND(Pin19/Pin20)
3.GND <--> GND(Pin19/Pin20)
4.SDA <--> HI2C_SDA0(Pin8)
5.DVI <--> VCC(Pin2)
6.SCL <--> HI2C_SCL0 (Pin6)
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Ginkgo;
namespace ControlI2C_BH1750FVI
{
class Program
{
static void Main(string[] args)
{
int ret;
//Scan connected device
ret = ControlI2C.VII_ScanDevice(1);
if (ret <= 0)
{
Console.WriteLine("No device connect!");
return;
}
//Open device
ret = ControlI2C.VII_OpenDevice(ControlI2C.INIT_CONFIG.VII_USBI2C, 0, 0);
if (ret != ControlI2C.ERROR.SUCCESS)
{
Console.WriteLine("Open device error!");
return;
}
//Initialize device(Hardware control mode)
ControlI2C.I2C_Config.AddrType = ControlI2C.INIT_CONFIG.VII_ADDR_7BIT;
ControlI2C.I2C_Config.ClockSpeed = 100000;
ControlI2C.I2C_Config.ControlMode = ControlI2C.INIT_CONFIG.VII_HCTL_MODE;
ControlI2C.I2C_Config.MasterMode = ControlI2C.INIT_CONFIG.VII_MASTER;
ControlI2C.I2C_Config.SubAddrWidth = ControlI2C.INIT_CONFIG.VII_SUB_ADDR_NONE;
ret = ControlI2C.VII_InitI2C(ControlI2C.INIT_CONFIG.VII_USBI2C, 0, 0, ref ControlI2C.I2C_Config);
if (ret != ControlI2C.ERROR.SUCCESS)
{
Console.WriteLine("Initialize device error!");
return;
}
// Send wait for measuring instructions
Byte[] write_buffer = new Byte[8];
write_buffer[0] = 0x01;
ret = ControlI2C.VII_WriteBytes(ControlI2C.INIT_CONFIG.VII_USBI2C, 0, 0, 0x46, 0x00, write_buffer, 1);
if (ret != ControlI2C.ERROR.SUCCESS)
{
Console.WriteLine("Write data error!");
return;
}
// Start measurement in 11x resolution ratio
write_buffer[0] = 0x10;
ret = ControlI2C.VII_WriteBytes(ControlI2C.INIT_CONFIG.VII_USBI2C, 0, 0, 0x46, 0x00, write_buffer, 1);
if (ret != ControlI2C.ERROR.SUCCESS)
{
Console.WriteLine("Write data error!");
return;
}
// Loop measurement
while (true)
{
// Waiting for measurement complete
System.Threading.Thread.Sleep(1000);
// Get measurement data
Byte[] read_buffer = new Byte[8];
ret = ControlI2C.VII_ReadBytes(ControlI2C.INIT_CONFIG.VII_USBI2C, 0, 0, 0x46, 0x00, read_buffer, 2);
if (ret != ControlI2C.ERROR.SUCCESS)
{
Console.WriteLine("Read data error!");
return;
}
else
{
double illuminance = ((read_buffer[0] << 8) | read_buffer[1]) / 1.2;
Console.Clear();
Console.WriteLine("illuminance:" + illuminance.ToString("0.00") + " lx");
}
}
}
}
}
|
namespace TruckPad.Services.ViewModel
{
public class MotoristaSemCargaDestinoOrigemViewModel
{
public int IdViagem { get; set; }
public string SentidoViagem { get; set; }
public string Carregado { get; set; }
public int IdMotorista { get; set; }
public string Nome { get; set; }
}
}
|
namespace DChild.Gameplay.Player.Items
{
public interface IOnConsumeEffect
{
void EnableEffect(Player player);
void DisableEffect(Player player);
}
} |
namespace Sentry.Tests.Protocol;
public class BaseScopeTests
{
private readonly Scope _sut = new(new SentryOptions());
[Fact]
public void Fingerprint_ByDefault_ReturnsEmptyEnumerable()
{
Assert.Empty(_sut.Fingerprint);
}
[Fact]
public void Tags_ByDefault_ReturnsEmpty()
{
Assert.Empty(_sut.Tags);
}
[Fact]
public void Breadcrumbs_ByDefault_ReturnsEmpty()
{
Assert.Empty(_sut.Breadcrumbs);
}
[Fact]
public void Sdk_ByDefault_ReturnsNotNull()
{
Assert.NotNull(_sut.Sdk);
}
[Fact]
public void User_ByDefault_ReturnsNotNull()
{
Assert.NotNull(_sut.User);
}
[Fact]
public void User_Settable()
{
var expected = new User();
_sut.User = expected;
Assert.Same(expected, _sut.User);
}
[Fact]
public void Contexts_ByDefault_NotNull()
{
Assert.NotNull(_sut.Contexts);
}
[Fact]
public void Contexts_Settable()
{
_sut.Contexts.App.Name = "Foo";
var expected = new Contexts
{
App =
{
Name = "Bar"
}
};
_sut.Contexts = expected;
Assert.Equal(expected, _sut.Contexts);
Assert.NotSame(expected, _sut.Contexts);
}
[Fact]
public void Request_ByDefault_NotNull()
{
Assert.NotNull(_sut.Request);
}
[Fact]
public void Request_Settable()
{
var expected = new Request();
_sut.Request = expected;
Assert.Same(expected, _sut.Request);
}
[Fact]
public void Transaction_Settable()
{
var expected = "Transaction";
_sut.TransactionName = expected;
Assert.Same(expected, _sut.TransactionName);
}
[Fact]
public void Release_Settable()
{
var expected = "Release";
_sut.Release = expected;
Assert.Same(expected, _sut.Release);
}
[Fact]
public void Distribution_Settable()
{
var expected = "Distribution";
_sut.Distribution = expected;
Assert.Same(expected, _sut.Distribution);
}
[Fact]
public void Environment_Settable()
{
var expected = "Environment";
_sut.Environment = expected;
Assert.Same(expected, _sut.Environment);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.Sconit.Entity.MD;
namespace com.Sconit.Service
{
public interface IFinanceCalendarMgr
{
FinanceCalendar GetNowEffectiveFinanceCalendar();
void CloseFinanceCalendar();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CEMAPI.DAL;
using System.Net.Http;
using System.Web.Http;
using CEMAPI.Models;
using log4net;
using CEMAPI.DAL;
using Newtonsoft.Json.Linq;
namespace CEMAPI.BAL
{
public class CreditDebitBAL
{
#region Global Variables
public TETechuvaDBContext context = new TETechuvaDBContext();
CEMEmailControllerBal email = new CEMEmailControllerBal();
CreditDebitDAL CrDbt = new CreditDebitDAL();
GenericDAL genDAL = new GenericDAL();
HttpResponseMessage hrm = new HttpResponseMessage();
SuccessInfo sinfo = new SuccessInfo() { errorcode = 0, errormessage = "Successful", listcount = 0 };
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion
public HttpResponseMessage CreditDebitDetailsListGet(DateTime? Date = null)
{
try
{
var CrdbtList = CrDbt.CreditDebitDetailsListGet();
if (Date != null)
{
DateTime Day = Date.Value.AddDays(1);
CrdbtList = CrdbtList.Where(x => (x.CreatedOn.Value == Date) && x.IsDeleted == false).ToList();
}
sinfo.errorcode = 0;
sinfo.errormessage = "Records Fetched sucessfully";
hrm.Content = new JsonContent(new
{
info = sinfo, Results = CrdbtList
});
}
catch (Exception Ex)
{
sinfo.errorcode = 1;
sinfo.errormessage = "Failed to Fetch the Records";
hrm.Content = new JsonContent(new
{
info = sinfo
});
}
return hrm;
}
public HttpResponseMessage CreditDebit_Cust_DetailsListGet(String Cust_ID)
{
try
{
var CrdbtList = CrDbt.CreditDebitCustumerDataList(Cust_ID);
sinfo.errorcode = 0;
sinfo.errormessage = "Records Fetched sucessfully";
hrm.Content = new JsonContent(new
{
info = sinfo,
Results = CrdbtList
});
}
catch (Exception Ex)
{
sinfo.errorcode = 1;
sinfo.errormessage = "Failed to Fetch the Records";
hrm.Content = new JsonContent(new
{
info = sinfo
});
}
return hrm;
}
public HttpResponseMessage CreditDebitGLMapping(String PaymentType)
{
SuccessInfo sinfo = new SuccessInfo();
HttpResponseMessage hrm = new HttpResponseMessage();
IEnumerable<CreditDebitTypeModel> Crdbt = CrDbt.CreditDebitGLMapping(PaymentType);
hrm.Content = new JsonContent(new
{
Results = Crdbt,
info = sinfo
});
return hrm;
}
public HttpResponseMessage SaveCreditDebitNote(TECreditDebitDetail creditDebitDetail, int logInUserId)
{
SuccessInfo sinfo = new SuccessInfo();
HttpResponseMessage hrm = new HttpResponseMessage();
try
{
int creditDebitId = 0;
creditDebitId = CrDbt.SaveCreditDebitNote(creditDebitDetail, logInUserId);
if (creditDebitId > 0)
{
sinfo.errorcode = 0;
sinfo.errormessage = "Record Saved Successfully";
hrm.Content = new JsonContent(new
{
info = sinfo, CreditDebitId = creditDebitId
});
}
else
{
sinfo.errorcode = 0;
sinfo.errormessage = "Record Failed Save";
hrm.Content = new JsonContent(new
{
info = sinfo
});
}
}
catch (Exception ex)
{
genDAL.RecordUnHandledException(ex);
sinfo.errorcode = 1;
sinfo.errormessage = "Failed to Save";
hrm.Content = new JsonContent(new
{
info = sinfo
});
}
return hrm;
}
public HttpResponseMessage UpdateCreditDebitNote(TECreditDebitDetail creditDebitDetail, int logInUserId)
{
SuccessInfo sinfo = new SuccessInfo();
HttpResponseMessage hrm = new HttpResponseMessage();
try
{
if (creditDebitDetail.Uniqueid > 0)
{
bool creditDebitId = CrDbt.UpdateCreditDebitNote(creditDebitDetail, logInUserId);
if (creditDebitId)
{
sinfo.errorcode = 0;
sinfo.errormessage = "Record Updated Successfully";
hrm.Content = new JsonContent(new
{
info = sinfo,
});
}
else
{
sinfo.errorcode = 1;
sinfo.errormessage = "Record Failed Updating";
hrm.Content = new JsonContent(new
{
info = sinfo,
});
}
}
else
{
sinfo.errorcode = 0;
sinfo.errormessage = "Record Failed Updating";
hrm.Content = new JsonContent(new
{
info = sinfo
});
}
}
catch (Exception ex)
{
genDAL.RecordUnHandledException(ex);
sinfo.errorcode = 1;
sinfo.errormessage = "Record Failed Updating";
hrm.Content = new JsonContent(new
{
info = sinfo
});
}
return hrm;
}
#region Approval Section
public HttpResponseMessage CreditandDebitApprovalBAL(JObject json, int lastModifiedby)
{
try
{
if (json == null)
{
sinfo.errorcode = 1;
sinfo.errormessage = "Mandatory field is missing";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = string.Empty }) };
}
if (json["CreditDebitId"] == null)
{
sinfo.errorcode = 1;
sinfo.errormessage = "Offer Id is missing";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = string.Empty }) };
}
int creditDebitId = json["CreditDebitId"].ToObject<int>();
hrm = CrDbt.CreditandDebitApprovalDAL(creditDebitId, lastModifiedby);
}
catch (Exception ex)
{
genDAL.RecordUnHandledException(ex);
sinfo.errorcode = 1;
sinfo.errormessage = "Failed To Submit";
hrm.Content = new JsonContent(new
{ info = sinfo });
}
return hrm;
}
public HttpResponseMessage CreditandDebitApprovalProcessingBAL(JObject json, int lastModifiedby)
{
try
{
if (json == null)
{
sinfo.errorcode = 1;
sinfo.errormessage = "Mandatory field is missing";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = string.Empty }) };
}
if (json["CreditDebitId"] == null)
{
sinfo.errorcode = 1;
sinfo.errormessage = "Credit Debit Note Id is missing";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = string.Empty }) };
}
if (json["Remarks"] == null)
{
sinfo.errorcode = 1;
sinfo.errormessage = "Remark is missing";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = string.Empty }) };
}
int creditDebitId = json["CreditDebitId"].ToObject<int>();
string remarks = json["Remarks"].ToObject<string>();
hrm = CrDbt.CreditandDebitApprovalProcessingDAl(creditDebitId, lastModifiedby, remarks);
}
catch (Exception ex)
{
genDAL.RecordUnHandledException(ex);
sinfo.errorcode = 1;
sinfo.errormessage = "Failed To Submit";
hrm.Content = new JsonContent(new
{ info = sinfo });
}
return hrm;
}
public HttpResponseMessage CreditandDebitRejectProcessingBAL(JObject json, int lastModifiedby)
{
SuccessInfo sinfo = new SuccessInfo() { errorcode = 0, errormessage = "Successful", listcount = 0 };
try
{
if (json == null)
{
sinfo.errorcode = 1;
sinfo.errormessage = "Mandatory field is missing";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = string.Empty }) };
}
if (json["CreditDebitId"] == null)
{
sinfo.errorcode = 1;
sinfo.errormessage = "Credit Debit Note Id is missing";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = string.Empty }) };
}
if (json["Remarks"] == null)
{
sinfo.errorcode = 1;
sinfo.errormessage = "Remark is missing";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = string.Empty }) };
}
int creditDebitId = json["CreditDebitId"].ToObject<int>();
string remarks = json["Remarks"].ToObject<string>();
hrm = CrDbt.CreditandDebitRejectProcessingDAl(creditDebitId, lastModifiedby, remarks);
}
catch (Exception ex)
{
genDAL.RecordUnHandledException(ex);
sinfo.errorcode = 1;
sinfo.errormessage = "Failed To Submit";
hrm.Content = new JsonContent(new
{ info = sinfo });
}
return hrm;
}
public HttpResponseMessage CreditDebitApprovalDataBAL(JObject jData, int lastModiifedby)
{
try
{
if (jData == null)
{
sinfo.errorcode = 1;
sinfo.errormessage = "Mandatory field is missing";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = string.Empty }) };
}
if (jData["CreditDebitId"] == null)
{
sinfo.errorcode = 1;
sinfo.errormessage = "Credit Debit ID is missing";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = string.Empty }) };
}
int cdId = jData["CreditDebitId"].ToObject<int>();
CNDTransferApprovalDetail cndListData = new CNDTransferApprovalDetail();
List<CNDApprovalRemarks> appRemarks = new List<CNDApprovalRemarks>();
cndListData = CrDbt.CreditDebitApprovalDataDAL(cdId, lastModiifedby);
appRemarks = CrDbt.GetCNDApproverRemark(cdId);
if (cndListData != null)
{
sinfo.errorcode = 0;
sinfo.errormessage = "Successfull";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = cndListData, remark = appRemarks }) };
}
else
{
sinfo.errorcode = 1;
sinfo.errormessage = "No Record Found";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = string.Empty }) };
}
}
catch (Exception ex)
{
genDAL.RecordUnHandledException(ex);
sinfo.errorcode = 1;
sinfo.errormessage = "Fail to get data";
return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo, result = string.Empty }) };
}
}
#endregion
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.