text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DSG东莞路测客户端
{
public class GPSInfo
{
public string Time { get; set; }
public double Lng { get; set; }
public double Lat { get; set; }
public int GridID { get; set; }
public LocationInfo Location { get; set; }
public GPSInfo()
{
}
public GPSInfo(double lng, double lat)
{
this.Lng = lng;
this.Lat = lat;
this.Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
public GPSInfo Copy()
{
if (this == null) return null;
return (GPSInfo)this.MemberwiseClone();
}
}
public class GridInfo
{
public int ID { get; set; }
public double StartLon { get; set; }
public double StopLon { get; set; }
public double StartLat { get; set; }
public double StopLat { get; set; }
public int? CM { get; set; }
public int? CU { get; set; }
public int? CT { get; set; }
}
public class LocationInfo
{
public string Province { get; set; }
public string City { get; set; }
public string District { get; set; }
public string DetailAddress { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomString
{
class Program
{
// Create a custom string structure:
// Create an ICustomString interface with the following custom functions:
// string ToString()
// void Insert(string stringToInsert)
// void Remove(int startIndex, int numCharsToRemove)
// int Length()
// Inherit from the ICustomString interface to implement the following custom string subclasses:
// SystemString
// Underlying structure: System.string
// Piggyback off System.string's built-in functionality to implement ICustomString's functions
// SystemArrayString
// Underlying structure: System.array
// Each index of the underlying array holds one character
// SystemLinkedListString
// Underlying structure: System.Collections.Generic.LinkedList
// Each node of the underlying C# LinkedList holds one character
// CustomLinkedListString
// Underlying structure: your own custom linked list
// Each node of the underlying custom linked list structure holds one character
static void Main(string[] args)
{
//SystemString systemstring = new SystemString();
//systemstring.Insert("nt", 9);
//systemstring.Length();
//systemstring.Remove(7, 2);
//SystemArrayString arrayString = new SystemArrayString();
//arrayString.Insert("the", 0);
//arrayString.Length();
//arrayString.Remove(2, 3);
SystemLinkedListString systemLinkedList = new SystemLinkedListString();
Node<string> node = new Node<string>("ILoveThe");
systemLinkedList.Insert(node.storage, 0);
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Communicator.Infrastructure.Dto;
namespace Communicator.Infrastructure.IServices
{
public interface IMessageService
{
Task Add(Guid to, Guid from, string title, string body);
Task<IEnumerable<MessageDto>> GetTo(Guid id);
Task Delete(Guid id);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
class ABC123B{
public static void Main(){
var ae = new List<int>();
ae.Add(int.Parse(Console.ReadLine()));
ae.Add(int.Parse(Console.ReadLine()));
ae.Add(int.Parse(Console.ReadLine()));
ae.Add(int.Parse(Console.ReadLine()));
ae.Add(int.Parse(Console.ReadLine()));
var ae2 = new List<int>();
ae.ForEach(x=>ae2.Add(10-x%10));
ae2.RemoveAll(x=>x==10);
if(ae2.Count != 0)ae2.Remove(ae2.Max());
Console.WriteLine(ae.Sum()+ae2.Sum());
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Configuration;
using DevExpress.XtraEditors;
namespace MarcalDataSim
{
public partial class frmSimMain : DevExpress.XtraEditors.XtraForm
{
private IPEndPoint ipep = null;
public frmSimMain()
{
InitializeComponent();
//IPHostEntry hostInfo = Dns.GetHostEntry(@"irap.vicp.net");
IPHostEntry hostInfo = Dns.GetHostEntry(@"localhost");
foreach (IPAddress ip in hostInfo.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
ipep = new IPEndPoint(ip, 30000);
}
}
if (ConfigurationManager.AppSettings["DCSAddress"] != null)
ipep = new IPEndPoint(IPAddress.Parse(ConfigurationManager.AppSettings["DCSAddress"]), 30000);
else
ipep = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 30000);
}
private void btnSend_Click(object sender, EventArgs e)
{
if (ipep == null)
{
WriteLog("初始化 Socket 服务地址失败");
}
try
{
string outBufferStr;
byte[] outBuffer = new byte[1024];
byte[] inBuffer = new byte[1024];
int idxUnitOfMeasure = rgpUnifOfMeasure.SelectedIndex;
outBufferStr =
edtSimData.Text.Trim() +
rgpUnifOfMeasure.Properties.Items[idxUnitOfMeasure].Value.ToString();
WriteLog(outBufferStr);
outBuffer = Encoding.ASCII.GetBytes(outBufferStr);
using (Socket client =
new Socket(
ipep.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp))
{
client.Connect(ipep);
client.Send(outBuffer, outBuffer.Length, SocketFlags.None);
client.Receive(inBuffer, SocketFlags.None);
WriteLog(Encoding.ASCII.GetString(inBuffer).Trim());
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
catch
{
WriteLog("服务未开启!");
}
edtSimData.Focus();
}
private void WriteLog(string message)
{
//if (mmeLogs.Text.Trim() != "")
// mmeLogs.Text += "\r\n";
if (message.Trim() != "")
{
message =
string.Format(
"{0}: {1}",
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),
message).Trim('\0');
mmeLogs.Text =
string.Format(
"{0}\r\n{1}",
message,
mmeLogs.Text);
}
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
private void edtSimData_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
btnSend.PerformClick();
}
}
private void frmSimMain_Activated(object sender, EventArgs e)
{
edtSimData.Focus();
}
}
} |
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Data.SqlClient;
using System.Collections.Generic;
/// <summary>
/// Summary description for DataAccessLayer
/// </summary>
public static class DataAccessLayer
{
//public static string ConnectionString =@"data source=BUGNET-VM1\BUGNET;database=WebAutomation;User id=sa;pwd=test@123;Connect Timeout=120";
public static string ConnectionString = System.Configuration.ConfigurationManager.AppSettings["con"];
public static DataTable GetReturnDataTable(string storeProcName, List<SqlParameter> parameters)
{
SqlConnection con = null;
try
{
string connectionString = ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = storeProcName;
foreach (SqlParameter param in parameters)
{
command.Parameters.AddWithValue(param.ParameterName, param.Value);
}
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
catch (SqlException ex)
{
throw ex;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
con.Dispose();
}
}
}
public static DataSet GetReturnDataSet(string storeProcName, List<SqlParameter> parameters)
{
SqlConnection con = null;
try
{
string connectionString = ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = storeProcName;
foreach (SqlParameter param in parameters)
{
command.Parameters.AddWithValue(param.ParameterName, param.Value);
}
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataSet dt = new DataSet();
adapter.Fill(dt);
return dt;
}
catch (SqlException ex)
{
throw ex;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
con.Dispose();
}
}
}
public static object InsertData(string storeProcName, List<SqlParameter> parameters)
{
object _returnValue = null;
SqlConnection con = null;
SqlTransaction _trans = null;
try
{
string connectionString = ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
_trans = con.BeginTransaction();
SqlCommand command = new SqlCommand();
command.Connection = con;
command.Transaction = _trans;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = storeProcName;
foreach (SqlParameter param in parameters)
{
if (param.Direction == ParameterDirection.Input)
{
command.Parameters.AddWithValue(param.ParameterName, param.Value);
}
else if (param.Direction == ParameterDirection.ReturnValue)
{
command.Parameters.Add(param);
}
else if (param.Direction == ParameterDirection.Output)
{
command.Parameters.Add(param);
}
}
command.ExecuteNonQuery();
_trans.Commit();
foreach (SqlParameter param in parameters)
{
if (param.Direction == ParameterDirection.ReturnValue)
{
_returnValue = param.Value;
}
else if (param.Direction == ParameterDirection.Output)
{
_returnValue = param.Value;
}
}
return _returnValue;
}
catch (SqlException ex)
{
_trans.Rollback();
throw ex;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
con.Dispose();
}
}
}
public static object InsertData(SqlConnection con, SqlTransaction trans, string storeProcName, List<SqlParameter> parameters)
{
object _returnValue = null;
try
{
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = storeProcName;
command.Transaction = trans;
foreach (SqlParameter param in parameters)
{
if (param.Direction == ParameterDirection.Input)
{
command.Parameters.AddWithValue(param.ParameterName, param.Value);
}
else if (param.Direction == ParameterDirection.ReturnValue)
{
command.Parameters.Add(param);
}
}
command.ExecuteNonQuery();
foreach (SqlParameter param in parameters)
{
if (param.Direction == ParameterDirection.ReturnValue)
{
_returnValue = param.Value;
}
}
return _returnValue;
}
catch (SqlException ex)
{
throw ex;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace Algorithms.LeetCode
{
public class PerformanceOfTeam
{
public int MaxPerformance(int n, int[] speed, int[] efficiency, int k)
{
var workers = new List<(int s, int e)>(n);
for (int i = 0; i < n; i++)
{
workers.Add((speed[i], efficiency[i]));
}
workers.Sort((d1, d2) => d1.e != d2.e ? d2.e.CompareTo(d1.e) : d1.s.CompareTo(d2.s));
BigInteger res = 0;
BigInteger sum = 0;
var heap = new MinHeap(new List<int>(k));
foreach (var worker in workers)
{
sum += worker.s;
heap.Push(worker.s);
if (heap._data.Count > k)
sum -= heap.Pop();
BigInteger curRes = (sum * worker.e);
if (curRes > res)
res = curRes;
}
return (int)(res % 1000000007);
}
private class MinHeap
{
public readonly List<int> _data;
public MinHeap(List<int> inputs)
{
_data = inputs;
for (int i = _data.Count / 2; i >= 0; i--)
{
Heapify(i);
}
}
private void Swap(int i, int j)
{
var tmp = _data[i];
_data[i] = _data[j];
_data[j] = tmp;
}
private void Heapify(int i)
{
while (2 * i + 1 < _data.Count)
{
int left = 2 * i + 1;
int right = 2 * i + 2;
int j = left;
if (right < _data.Count && _data[right] < _data[left])
{
j = right;
}
if (_data[i] <= _data[j])
break;
Swap(i, j);
i = j;
}
}
public int Pop()
{
var top = _data[0];
_data[0] = _data.Last();
_data.RemoveAt(_data.Count - 1);
Heapify(0);
return top;
}
public void Push(int value)
{
_data.Add(value);
int i = _data.Count - 1;
while (_data[i] < _data[(i - 1) / 2])
{
Swap(i, (i - 1) / 2);
i = (i - 1) / 2;
}
}
}
}
} |
using ApiSGCOlimpiada.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSGCOlimpiada.Data.ProdutoDAO
{
public interface IProdutoDAO
{
IEnumerable<Produto> GetAll();
Produto Find(long codigoProtheus);
Produto FindByProtheus(long codigoProtheus);
List<Produto> FindBySearch(string search);
bool Add(Produto produto);
bool Update(Produto produto, long id);
bool Remove(long id);
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Tensorflow;
using static Tensorflow.Binding;
namespace TensorFlowNET.Examples.ImageProcessing.YOLO
{
class common
{
public static Tensor convolutional(Tensor input_data, int[] filters_shape, Tensor trainable,
string name, bool downsample = false, bool activate = true,
bool bn = true)
{
return tf_with(tf.variable_scope(name), scope =>
{
int[] strides;
string padding;
if (downsample)
{
(int pad_h, int pad_w) = ((int)Math.Floor((filters_shape[0] - 2) / 2.0f) + 1, (int)Math.Floor((filters_shape[1] - 2) / 2.0f) + 1);
var paddings = tf.constant(new int[,] { { 0, 0 }, { pad_h, pad_h }, { pad_w, pad_w }, { 0, 0 } });
input_data = tf.pad(input_data, paddings, "CONSTANT");
strides = new int[] { 1, 2, 2, 1 };
padding = "VALID";
}
else
{
strides = new int[] { 1, 1, 1, 1 };
padding = "SAME";
}
var weight = tf.compat.v1.get_variable(name: "weight", dtype: tf.float32, trainable: true,
shape: filters_shape, initializer: tf.random_normal_initializer(stddev: 0.01f));
var conv = tf.nn.conv2d(input: input_data, filter: weight, strides: strides, padding: padding);
if (bn)
{
conv = tf.layers.batch_normalization(conv, beta_initializer: tf.zeros_initializer,
gamma_initializer: tf.ones_initializer,
moving_mean_initializer: tf.zeros_initializer,
moving_variance_initializer: tf.ones_initializer, training: trainable);
}
else
{
var bias = tf.compat.v1.get_variable(name: "bias", shape: filters_shape.Last(), trainable: true,
dtype: tf.float32, initializer: tf.constant_initializer(0.0f));
conv = tf.nn.bias_add(conv, bias);
}
if (activate)
conv = tf.nn.leaky_relu(conv, alpha: 0.1f);
return conv;
});
}
public static Tensor upsample(Tensor input_data, string name, string method = "deconv")
{
Debug.Assert(new[] { "resize", "deconv" }.Contains(method));
Tensor output = null;
if (method == "resize")
{
tf_with(tf.variable_scope(name), delegate
{
var input_shape = tf.shape(input_data);
output = tf.image.resize_nearest_neighbor(input_data, new Tensor[] { input_shape[1] * 2, input_shape[2] * 2 });
});
}
else if(method == "deconv")
{
throw new NotImplementedException("upsample.deconv");
}
return output;
}
public static Tensor residual_block(Tensor input_data, int input_channel, int filter_num1,
int filter_num2, Tensor trainable, string name)
{
var short_cut = input_data;
return tf_with(tf.variable_scope(name), scope =>
{
input_data = convolutional(input_data, filters_shape: new int[] { 1, 1, input_channel, filter_num1 },
trainable: trainable, name: "conv1");
input_data = convolutional(input_data, filters_shape: new int[] { 3, 3, filter_num1, filter_num2 },
trainable: trainable, name: "conv2");
var residual_output = input_data + short_cut;
return residual_output;
});
}
}
}
|
using System;
using System.Reflection;
using System.Security.Claims;
using System.Threading.Tasks;
using ApiTemplate.Common.Exceptions;
using ApiTemplate.Common.Markers.DependencyRegistrar;
using ApiTemplate.Core.Entities.Users;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace ApiTemplate.Service.Users
{
public class UserService : IUserService ,IScopedDependency
{
#region Fields
private readonly UserManager<AppUser> _userManager;
private readonly SignInManager<AppUser> _signInManager;
#endregion
#region Constructors
public UserService(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
#endregion
#region Methods
public async Task<AppUser> GetUserByUserName(string userName)
{
if (string.IsNullOrEmpty(userName))
{
throw new NullArgumentException($"فیلد {nameof(userName)} در کلاس {GetType().Name} در متد {MethodBase.GetCurrentMethod().Name} خالی می باشد");
}
return await _userManager.FindByNameAsync(userName);
}
public async Task<SignInResult> CheckPassword(AppUser user, string password)
{
if (user is null)
{
throw new NullArgumentException($"فیلد {nameof(user)} در کلاس {GetType().Name} در متد {MethodBase.GetCurrentMethod().Name} خالی می باشد");
}
if (string.IsNullOrEmpty(password))
{
throw new NullArgumentException($"فیلد {nameof(password)} در کلاس {GetType().Name} در متد {MethodBase.GetCurrentMethod().Name} خالی می باشد");
}
return await _signInManager.CheckPasswordSignInAsync(user, password, true);
}
public async Task<AppUser> GetUserById(long id)
{
return await _userManager.Users.FirstOrDefaultAsync(c => c.Id.Equals(id));
}
public async Task<IdentityResult> AddUser(AppUser appUser, string password)
{
if (appUser is null)
{
throw new NullArgumentException($"فیلد {nameof(appUser)} در کلاس {GetType().Name} در متد {MethodBase.GetCurrentMethod().Name} خالی می باشد");
}
if (string.IsNullOrEmpty(password))
{
throw new NullArgumentException($"فیلد {nameof(password)} در کلاس {GetType().Name} در متد {MethodBase.GetCurrentMethod().Name} خالی می باشد");
}
var result = await _userManager.CreateAsync(appUser, password);
return result;
}
public async Task UpdateLockoutToZero(AppUser user)
{
await _userManager.SetLockoutEndDateAsync(user, new DateTimeOffset(DateTime.UtcNow));
}
public async Task<AppUser> GetUserByHttpContextUser(ClaimsPrincipal httpContextUser)
{
return await _userManager.GetUserAsync(httpContextUser);
}
#endregion
}
} |
using MyShop.Core.Contracts;
using MyShop.Core.Model;
using MyShop.DataAccess.Sql.Migrations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyShop.Core.Model;
using Customer = MyShop.Core.Model.Customer;
namespace MyShop.WebUI.Controllers
{
public class BasketController : Controller
{
IBasketService _basketService;
IOrderService _orderService;
IRepository<Customer> _customerService;
public BasketController(IBasketService basketService, IOrderService orderService,IRepository<Customer> customer)
{
_basketService = basketService;
_orderService = orderService;
_customerService = customer;
}
// GET: Basket
public ActionResult Index()
{
var model = _basketService.GetBasketItems(this.HttpContext);
return View(model);
}
public ActionResult AddToBasket(string id)
{
_basketService.AddToBasket(this.HttpContext, id);
return RedirectToAction("Index");
}
public PartialViewResult BasketSummery()
{
var basketSummery = _basketService.GetBasketSummary(this.HttpContext);
return PartialView(basketSummery);
}
[Authorize]
public ActionResult Checkout()
{
//Search User from the Loged in Email and find the user name from that
//c=>c.Email==User.Identity.Name
Customer customer = _customerService.GetAll().FirstOrDefault(c => c.Email == User.Identity.Name);// found the logged in user
if(customer != null)
{ //create new order for customer
Order order = new Order
{FirstName=customer.FirstName,
LastName=customer.LastName,
Email=customer.Email,
};
return View(order);
}
else { return RedirectToAction("Error");
}
}
[HttpPost]
[Authorize]
public ActionResult Checkout(Order order)
{
var basketItems = _basketService.GetBasketItems(this.HttpContext);
order.OrderStatus = "Order Created";
order.Email = User.Identity.Name;
//process payment
order.OrderStatus = "Payment Processed";
_orderService.CreateOrder(order, basketItems);
_basketService.ClearBasket(this.HttpContext);
return RedirectToAction("Thankyou", new { OrderId = order.Id });
}
public ActionResult ThankYou(string OrderId)
{
ViewBag.OrderId = OrderId;
return View();
}
}
} |
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Function x 2 of type `int`. Inherits from `AtomFunction<int, int>`.
/// </summary>
[EditorIcon("atom-icon-sand")]
public abstract class IntIntFunction : AtomFunction<int, int> { }
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
namespace OnlineStore.Model
{
public class OnlineStore : DbContext
{
public DbSet<ShopingCart> ShopingCarts { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=OnlineStore;Trusted_Connection=True;");
}
}
public class ShopingCart
{
public int ShopingCartID { get; set; }
public int UserID { get; set; }
public User User { get; set; }
public int ProductID { get; set; }
public Product Product { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
}
public class Order
{
public int OrderID { get; set; }
public DateTime OrderDate { get; set; }
public DateTime ShipDate { get; set; }
public string ShipAddress { get; set; }
public int ProductID { get; set; }
public Product Product { get; set; }
public int UserID { get; set; }
public User User { get; set; }
public int StatusID { get; set; }
public Status Status { get; set; }
}
public class Status
{
public int StatusID { get; set; }
public string StatusName { get; set; }
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public string Description { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
}
public class Role
{
public int RoleID { get; set; }
public string RoleName { get; set; }
}
public class User
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MidName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Phone { get; set; }
public bool Lock { get; set; }
public string Location { get; set; }
public int RoleID { get; set; }
public Role Role { get; set; }
}
}
|
using EnvDTE;
using Microsoft.master2.assembly;
using Microsoft.master2.contextmodel;
using Microsoft.master2.graph;
using Microsoft.master2.model;
using Microsoft.Master2.assembly;
using Microsoft.Master2.command;
using Relations;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.master2.rules
{
public class RuleEngine
{
GraphUtils gUt;
public DTE dte;
public StructuralConnection currentStructuralConnection;
public ArrayList xmlModel = null;
public bool hasModel() {
if (xmlModel == null)
{
return false;
}
else { return true; }
}
public void setModel(ArrayList model) {
xmlModel = model;
}
public int positionNumber = 0;
public RuleEngine(GraphUtils gUt, GraphLayout graphLayout)
{
this.gUt = gUt;
}
ArrayList cSharpClassModel = new ArrayList();
ArrayList cSharpEntityModel = new ArrayList();
ArrayList entitiesList = new ArrayList();
public void updateEntity(MyVertexBase entity)
{
gUt.Clear(cSharpEntityModel);
ArrayList cSharpClasses = entity.CSharpClasses;
foreach (CSharpClass sCharpClassFromEntity in cSharpClasses)
{
sCharpClassFromEntity.Threshold = entity.CommonThreshold;
}
CSharpClass.resetModel(cSharpClassModel);
updateGUI();
}
ArrayList entitiesToDisplayModel = new ArrayList();
public void updateEntityWithGrpah(MyVertexBase entity, GraphLayout gL)
{
gUt.Clear(cSharpEntityModel);
ArrayList cSharpClasses = entity.CSharpClasses;
foreach (CSharpClass sCharpClassFromEntity in cSharpClasses)
{
sCharpClassFromEntity.Threshold = entity.CommonThreshold;
}
CSharpClass.resetModel(cSharpClassModel);
positionNumber = 0;
cSharpEntityModel = new ArrayList();
updateEntities(null,false);
//gUt.updateVertexWithGraph(null, cSharpEntityModel, gL, entitiesToDisplayModel);
// gUt.updateEdgesWithGraph(cSharpEntityModel, gL);
// gUt.updateCoordinates(null, gL);
}
private CSharpClass prepareClassMethodsFromName(string fullName)
{
CSharpClass result = null;
string[] elementsNames = fullName.Split('.');
try
{
AssemblyInstance asInst = new AssemblyInstance();
Type[] types = asInst.Assembly.GetTypes();
// Type[] types = asInst.getTypes();
Type t = null;
foreach (Type type in types)
{
if (type.FullName == elementsNames[0] + "." + elementsNames[1])
{
t = type;
break;
}
}
result = new CSharpClass();
result.Name = t.Name;
if (t.DeclaringType != null)
{
result.Parent = t.DeclaringType.Name;
}
else
{
result.Parent = "Object";
}
result.Relevance = 0;
CSharpMethod cSharpMethod = new CSharpMethod();
cSharpMethod.Name = elementsNames[2];
cSharpMethod.Relevance = 0.1;
result.Methods.Add(cSharpMethod);
}
catch (Exception e)
{
}
return result;
}
private void tryToGetSelectedElement(CSharpClass c)
{
try
{
/*EnvDTE.TextSelection doc = (EnvDTE.TextSelection)dte.ActiveDocument.Selection;
EnvDTE.TextPoint textPoint = doc.ActivePoint;
CodeElement el = dte.ActiveDocument.ProjectItem.FileCodeModel.CodeElementFromPoint(textPoint, EnvDTE.vsCMElement.vsCMElementFunction);
string methodTo = el.FullName;
CSharpClass c = prepareClassMethodsFromName(methodTo);*/
currentStructuralConnection.classTo = c;
// currentStructuralConnection.methodTo = methodTo;
if(!structuralConnections.Contains(currentStructuralConnection)){
StructuralConnection sc= new StructuralConnection();
sc.classFrom = currentStructuralConnection.classFrom;
sc.classTo = currentStructuralConnection.classTo;
sc.methodFrom = currentStructuralConnection.methodFrom;
// sc.methodTo = currentStructuralConnection.methodTo;
structuralConnections.Add(sc);
}
}catch(Exception e){
}
}
private CSharpClass lastClassSelected = null;
public void updateRelevanceOfClass(CSharpClass cSharpClass)
{
cSharpClassModel = Heuristics.updateRelevance(cSharpClassModel, cSharpClass, false);
}
public ArrayList classSelectedWithGrpah(CSharpClass cSharpClass, GraphLayout gL, bool mouseEvent)
{
if (gUt.xmlModel == null) {
gUt.xmlModel = xmlModel;
}
ArrayList result = new ArrayList();
if ((mouseEvent) || (lastClassSelected == null) || (cSharpClass.Name != lastClassSelected.Name))
{
lastClassSelected = cSharpClass;
gUt.Clear(cSharpEntityModel);
cSharpClassModel = Heuristics.updateRelevance(cSharpClassModel, cSharpClass, mouseEvent);
cSharpClassModel.Sort();
CSharpClass.resetModel(cSharpClassModel);
positionNumber = 0;
cSharpEntityModel = new ArrayList();
updateEntities(cSharpClass, false);
tryToGetSelectedElement(cSharpClass);
proActiveClassess = new ArrayList();
updateProActiveNavigationWithoutRefresh(cSharpClass);
gL.Graph = new MyGraph();
entitiesToDisplayModel = gUt.updateVertexWithGraph(cSharpClass, cSharpEntityModel, gL, entitiesToDisplayModel);
MyVertexBase selectedEntity = updateEdges(entitiesToDisplayModel);
ArrayList proActiveNavigationEntities = gUt.updateProActiveNavigationWithGraph(cSharpClass, proActiveClassess, gL);
addEdgesToProActiveEntities(gL.Graph, proActiveNavigationEntities, selectedEntity);
result.Add(proActiveNavigationEntities);
gUt.updateEdgesWithGraph(cSharpEntityModel, gL);
}
result.Add(entitiesToDisplayModel);
return result;
}
public ArrayList classSelectedWithGrpahRefreshButton(CSharpClass cSharpClass, GraphLayout gL, bool mouseEvent)
{
ArrayList result = new ArrayList();
if ((mouseEvent) || (lastClassSelected == null) || (cSharpClass.Name != lastClassSelected.Name))
{
lastClassSelected = cSharpClass;
gUt.Clear(cSharpEntityModel);
cSharpClassModel = Heuristics.updateRelevance(cSharpClassModel, cSharpClass, true);
cSharpClassModel.Sort();
gUt.cSharpModel = cSharpClassModel;
CSharpClass.resetModel(cSharpClassModel);
positionNumber = 0;
cSharpEntityModel = new ArrayList();
updateEntities(cSharpClass, true);
tryToGetSelectedElement(cSharpClass);
proActiveClassess = new ArrayList();
ArrayList proActiveEntities = updateProActiveNavigationWithRefresh(cSharpClass);
gL.Graph = new MyGraph();
entitiesToDisplayModel = gUt.updateVertexWithGraph(cSharpClass, cSharpEntityModel, gL, entitiesToDisplayModel);
MyVertexBase selectedEntity = updateEdges(entitiesToDisplayModel);
ArrayList proActiveNavigationEntities = gUt.updateProActiveNavigationWithGraphWithRefresh(cSharpClass, proActiveEntities, gL);
result.Add(proActiveNavigationEntities);
addEdgesToProActiveEntities(gL.Graph, proActiveNavigationEntities, selectedEntity);
gUt.updateEdgesWithGraph(cSharpEntityModel, gL);
}
result.Add(entitiesToDisplayModel);
return result;
}
private void addEdgesToProActiveEntities(MyGraph myGraph, ArrayList proActiveNavigationEntities, MyVertexBase selectedEntity)
{
string[] protocol = new string[proActiveNavigationEntities.ToArray().Length];
int j = 0;
foreach (MyVertexBase entity in proActiveNavigationEntities)
{
//EntityEdge entityEdge = new EntityEdge(selectedEntity.ToString(), entity.ToString());
if((entity.CSharpClasses != null) &&(entity.CSharpClasses.ToArray().Length > 0)){
CSharpClass cl = (CSharpClass)entity.CSharpClasses[0];
if (!Constant.AUTOTEST)
{
myGraph.AddEdge(new MyEdgeBase(selectedEntity, entity, cl.NumerOfEdges.ToString()));
}
}else{
if (!Constant.AUTOTEST)
{
myGraph.AddEdge(new MyEdgeBase(selectedEntity, entity, ""));
}
}
protocol[j] = protocolEntities(entity);
j++;
}
writeProtocolToFile(protocol, 1);
}
private void addEdgesToProActiveEntitiesWithSort(MyGraph myGraph, ArrayList proActiveNavigationEntities, MyVertexBase selectedEntity)
{
string[] protocol = new string[proActiveNavigationEntities.ToArray().Length];
int j = 0;
foreach (MyVertexBase entity in proActiveNavigationEntities)
{
//EntityEdge entityEdge = new EntityEdge(selectedEntity.ToString(), entity.ToString());
myGraph.AddEdge(new MyEdgeBase(selectedEntity, entity, ""));
protocol[j] = protocolEntities(entity);
j++;
}
writeProtocolToFile(protocol, 1);
}
private ArrayList proActiveClassess = new ArrayList();
public void updateProActiveNavigationWithoutRefresh(CSharpClass selectedCSharpClass)
{
ArrayList methods = selectedCSharpClass.Methods;
foreach (CSharpMethod cSharpMethod in methods)
{
foreach (CSharpClass cSharpClass in xmlModel)
{
if (!cSharpClassModel.Contains(cSharpClass))
{ //class is still not added. We can navigate there
ArrayList incomingCalls = cSharpMethod.IncomingCalls;
foreach (IncomingCall incomingCall in incomingCalls)
{
if (incomingCall.ClassName == cSharpClass.Name)
{
//add the class to navigation
if (!proActiveClassess.Contains(cSharpClass))
{
cSharpClass.NumerOfEdges = 1;
proActiveClassess.Add(cSharpClass);
}
else
{
CSharpClass proActiveClass = getClassByName(cSharpClass.Name, proActiveClassess);
proActiveClass.NumerOfEdges = proActiveClass.NumerOfEdges + 1;
}
}
}
ArrayList outgountCalls = cSharpMethod.OutgoingCalls;
foreach (MethodTypeCall outgoingCall in outgountCalls)
{
if (outgoingCall.ClassName == cSharpClass.Name)
{
//add the class to navigation
if (!proActiveClassess.Contains(cSharpClass))
{
cSharpClass.NumerOfEdges = 1;
proActiveClassess.Add(cSharpClass);
}
else
{
CSharpClass proActiveClass = getClassByName(cSharpClass.Name, proActiveClassess);
proActiveClass.NumerOfEdges = proActiveClass.NumerOfEdges + 1;
}
}
}
}
}
}
}
public ArrayList updateProActiveNavigationWithRefresh(CSharpClass selectedCSharpClass)
{
ArrayList listToCheck = new ArrayList();
ArrayList result = new ArrayList();
ArrayList methods = selectedCSharpClass.Methods;
foreach(CSharpMethod cSharpMethod in methods){
if(cSharpMethod.Name == selectedCSharpClass.SelectedMethod){
ArrayList outgoingCalls = cSharpMethod.OutgoingCalls;
foreach (MethodTypeCall outgoingCall in outgoingCalls)
{
CSharpClass classToConnect = getMethodFromClassModel(outgoingCall, xmlModel);
if (classToConnect != null)
{
double relevance = getRelevamceFromClass(classToConnect, outgoingCall.Name);
MyVertexBaseVerySmall myVertexSmall = new MyVertexBaseVerySmall();
myVertexSmall.Name1 = classToConnect.Name;
myVertexSmall.Name2 = outgoingCall.Name;
myVertexSmall.Relevance = relevance;
if (!listToCheck.Contains(myVertexSmall.Name1 + myVertexSmall.Name2))
{
listToCheck.Add(myVertexSmall.Name1 + myVertexSmall.Name2);
result.Add(myVertexSmall);
}
}
}
}
}
return result;
}
private double getRelevamceFromClass(CSharpClass currentCSharpClass, String currentMethodName) {
foreach(CSharpClass cl in cSharpClassModel){
if (cl.Name == currentCSharpClass.Name) {
ArrayList methods = currentCSharpClass.Methods;
foreach(CSharpMethod method in methods){
if(currentMethodName == method.Name){
return cl.Relevance + method.Relevance;
}
}
}
}
return 0;
}
private CSharpClass getMethodFromClassModel(MethodTypeCall outgoingCall, ArrayList model) {
foreach (CSharpClass cSharpClass in model)
{
if(outgoingCall.ClassName == cSharpClass.Name){
ArrayList methods = cSharpClass.Methods;
foreach(CSharpMethod cSharpMethod in methods){
if(outgoingCall.Name == cSharpMethod.Name){
return cSharpClass;
}
}
}
}
return null;
}
/*ArrayList methods = selectedCSharpClass.Methods;
foreach(CSharpMethod cSharpMethod in methods){
foreach (CSharpClass cSharpClass in xmlModel)
{
if(!cSharpClassModel.Contains(cSharpClass)){ //class is still not added. We can navigate there
ArrayList incomingCalls = cSharpMethod.IncomingCalls;
foreach(IncomingCall incomingCall in incomingCalls){
if(incomingCall.ClassName == cSharpClass.Name){
//add the class to navigation
if (!proActiveClassess.Contains(cSharpClass))
{
cSharpClass.NumerOfEdges = 1;
proActiveClassess.Add(cSharpClass);
}
else {
CSharpClass proActiveClass = getClassByName(cSharpClass.Name, proActiveClassess);
proActiveClass.NumerOfEdges = proActiveClass.NumerOfEdges + 1;
}
}
}
ArrayList outgountCalls = cSharpMethod.OutgoingCalls;
foreach (MethodTypeCall outgoingCall in outgountCalls)
{
if(outgoingCall.ClassName == cSharpClass.Name){
//add the class to navigation
if (!proActiveClassess.Contains(cSharpClass))
{
cSharpClass.NumerOfEdges = 1;
proActiveClassess.Add(cSharpClass);
}
else
{
CSharpClass proActiveClass = getClassByName(cSharpClass.Name, proActiveClassess);
proActiveClass.NumerOfEdges = proActiveClass.NumerOfEdges + 1;
}
}
}
}
}
}
}*/
private CSharpClass getClassByName(string className, ArrayList listOfClasses) {
foreach(CSharpClass cSharpClass in listOfClasses){
if (cSharpClass.Name == className) {
return cSharpClass;
}
}
return null;
}
ArrayList structuralConnections = new ArrayList();
public void classSelectedWithGrpahNoUpdate(CSharpClass cSharpClass, GraphLayout gL, StructuralConnection structuralConnection)
{
/* gUt.Clear(cSharpEntityModel);
cSharpClassModel = Heuristics.updateRelevance(cSharpClassModel, cSharpClass);
cSharpClassModel.Sort();
CSharpClass.resetModel(cSharpClassModel);
positionNumber = 0;
cSharpEntityModel = new ArrayList();
updateEntities(cSharpClass);*/
// updateEdges(null);
/* if (!structuralConnections.Contains(structuralConnection)) {
structuralConnections.Add(structuralConnection);
}*/
gUt.Clear(cSharpEntityModel);
cSharpClassModel = Heuristics.updateRelevance(cSharpClassModel, cSharpClass, false);
cSharpClassModel.Sort();
CSharpClass.resetModel(cSharpClassModel);
positionNumber = 0;
cSharpEntityModel = new ArrayList();
updateEntities(cSharpClass, false);
//15.02.13 check this code
// proActiveClassess = new ArrayList();
// updateProActiveNavigation(cSharpClass);
// gL.Graph = new MyGraph();
// entitiesToDisplayModel = gUt.updateVertexWithGraph(cSharpClass, cSharpEntityModel, gL, entitiesToDisplayModel);
// updateEdges(entitiesToDisplayModel);
// gUt.updateProActiveNavigationWithGraph(cSharpClass, proActiveClassess, gL);
// gUt.updateEdgesWithGraph(cSharpEntityModel, gL);
// gUt.updateCoordinates(cSharpClass,gL);
}
public void classSelected(CSharpClass cSharpClass)
{
try
{
gUt.Clear(cSharpEntityModel);
cSharpClassModel = Heuristics.updateRelevance(cSharpClassModel, cSharpClass, false);
cSharpClassModel.Sort();
}
catch (Exception e)
{
int i = 0;
}
try
{
CSharpClass.resetModel(cSharpClassModel);
updateGUI();
}
catch (Exception e)
{
int i = 0;
}
}
private void updateGUI()
{
positionNumber = 0;
cSharpEntityModel = new ArrayList();
updateEntities(null, false);
updateEdges(null);
gUt.updateVertex(cSharpEntityModel);
gUt.updateEdges(cSharpEntityModel);
}
private void manageSecondSelectedClass(CSharpClass currentCSharpClass, CSharpClass selectedClass, bool isRefresh)
{
if(!isRefresh){
if (currentCSharpClass.IsSelected == true)
{
currentCSharpClass.IsSelected = false;
currentCSharpClass.IsSecondSelected = true;
}
else
{
currentCSharpClass.IsSecondSelected = false;
}
}
if (selectedClass != null)
{
if (currentCSharpClass == selectedClass)
{
currentCSharpClass.IsSelected = true;
}
}
}
private ArrayList updateEntities(CSharpClass selectedClass, bool isRefresh)
{
int numberOfEntities = 1; //will be read from UI
foreach (CSharpClass currentCSharpClass in cSharpClassModel)
{
// if (!isRefresh)
// {
manageSecondSelectedClass(currentCSharpClass, selectedClass, isRefresh);
//}
MyVertexBase entity = new MyVertexBaseMiddle();
if (!currentCSharpClass.IsAddedToEntity)
{
currentCSharpClass.IsAddedToEntity = true;
// entity.CSharpClasses.Add(currentCSharpClass);
addClassToEntity(entity, currentCSharpClass);
//calculate threshold of the class dependent on relevance
calculateThresholdDependentOnRelevance(numberOfEntities);
numberOfEntities++;
entity.CommonThreshold = currentCSharpClass.Threshold;
addAllConnectedClasses(entity, currentCSharpClass);
cSharpEntityModel.Add(entity);
}
}
int numberOfEntities2 = 0;
ArrayList result = new ArrayList();
foreach(MyVertexBase entity in cSharpEntityModel){
if (numberOfEntities2 < 7) {
result.Add(entity);
numberOfEntities2++;
}
}
cSharpEntityModel = result;
return cSharpEntityModel;
}
private void calculateThresholdDependentOnRelevance(int number) {
//for now the threshol set to large number in order to have all classes separate
/* double averageRelevance = 0;
foreach (CSharpClass currentCSharpClass in cSharpClassModel)
{
averageRelevance += currentCSharpClass.countRelevance();
}
averageRelevance = averageRelevance / cSharpClassModel.Count;*/
foreach (CSharpClass currentCSharpClass in cSharpClassModel)
{
// if (currentCSharpClass.countRelevance() > averageRelevance)
// {
if (number > 4)
{
currentCSharpClass.Threshold = 1;
}
else
{
currentCSharpClass.Threshold = 100;
}
// }
// else {
// currentCSharpClass.Threshold = 1;
//}
}
}
private void addClassToEntity(MyVertexBase myVertexBase, CSharpClass cSharpClass) {
myVertexBase.CSharpClasses.Add(cSharpClass);
if ((myVertexBase.NumberInThePast == 0)||(myVertexBase.NumberInThePast > cSharpClass.NumberInThePast))
{
myVertexBase.NumberInThePast = cSharpClass.NumberInThePast;
}
}
/* private void addAllConnectedClasses(Entity entity, CSharpClass cSharpClass) {
ArrayList methods = cSharpClass.Methods;
ArrayList edges = entity.Edges;
ArrayList incomingEdges = cSharpClass.IncomingEdges;
foreach(CSharpClassEdge incomingEdge in incomingEdges){
if ((incomingEdge.Weight >= entity.CommonThreshold) &&
(incomingEdge.Weight >= cSharpClass.Threshold)) {
string classToAddName = incomingEdge.Target;
CSharpClass classToAdd = getClassFromModelByName(classToAddName);
if ((classToAdd != null)&&(!classToAdd.IsAddedToEntity)) {
classToAdd.IsAddedToEntity = true;
entity.CSharpClasses.Add(classToAdd);
addAllConnectedClasses(entity, classToAdd);
}
}
}
ArrayList outgoingEdges = cSharpClass.OutgoingEdges;
foreach (CSharpClassEdge outgoingEdge in outgoingEdges)
{
if ((outgoingEdge.Weight >= entity.CommonThreshold)&&
(outgoingEdge.Weight >= cSharpClass.Threshold))
{
string classToAddName = outgoingEdge.Target;
CSharpClass classToAdd = getClassFromModelByName(classToAddName);
if ((classToAdd != null) && (!classToAdd.IsAddedToEntity))
{
classToAdd.IsAddedToEntity = true;
entity.CSharpClasses.Add(classToAdd);
addAllConnectedClasses(entity, classToAdd);
}
}
}
}*/
private void addAllConnectedClasses(MyVertexBase entity, CSharpClass cSharpClass)
{
ArrayList methods = cSharpClass.Methods;
ArrayList edges = entity.Edges;
ArrayList incomingEdges = cSharpClass.IncomingEdges;
foreach (CSharpClassEdge incomingEdge in incomingEdges)
{
string classToAddName = incomingEdge.Target;
CSharpClass classToAdd = getClassFromModelByName(classToAddName);
if (classToAdd != null)
{
if ((incomingEdge.Weight >= entity.CommonThreshold) &&
(incomingEdge.Weight >= classToAdd.Threshold))
{
if ((classToAdd != null) && (!classToAdd.IsAddedToEntity))
{
classToAdd.IsAddedToEntity = true;
// entity.CSharpClasses.Add(classToAdd);
addClassToEntity(entity, classToAdd);
addAllConnectedClasses(entity, classToAdd);
}
}
}
}
ArrayList outgoingEdges = cSharpClass.OutgoingEdges;
foreach (CSharpClassEdge outgoingEdge in outgoingEdges)
{
string classToAddName = outgoingEdge.Target;
CSharpClass classToAdd = getClassFromModelByName(classToAddName);
if (classToAdd != null)
{
if ((outgoingEdge.Weight >= entity.CommonThreshold) &&
(outgoingEdge.Weight >= classToAdd.Threshold))
{
if ((classToAdd != null) && (!classToAdd.IsAddedToEntity))
{
classToAdd.IsAddedToEntity = true;
entity.CSharpClasses.Add(classToAdd);
addAllConnectedClasses(entity, classToAdd);
}
}
}
}
}
private CSharpClass getClassFromModelByName(String className)
{
CSharpClass result = null;
foreach (CSharpClass cSharpClass in cSharpClassModel)
{
if (cSharpClass.Name == className)
{
return cSharpClass;
}
}
return result;
}
public void proActiveNavigation() {
foreach (MyVertexBase entity in cSharpEntityModel)
{
Object[] cSharpClass = entity.CSharpClasses.ToArray();
for (int i = 0; i < cSharpClass.Length; i++)
{
CSharpClass cl = (CSharpClass)cSharpClass[i];
// ArrayList navigationElements = cl.NavigationElements;
createClassNavigationElements(cl, 3);
//checkEdges(cl, cSharpEntityModel, entity);
}
}
}
private void createClassNavigationElements(CSharpClass cl, int deepLevel)
{
ArrayList methods = cl.Methods;
CSharpClass newClass = null;
if (deepLevel > 0) {
deepLevel--;
createClassNavigationElements(newClass, deepLevel);
}
}
int numberOfProtocolStep = 0;
public MyVertexBase updateEdges(ArrayList entityiesToProcess)
{
string[] protocol = new string[entityiesToProcess.ToArray().Length];
int j = 0;
MyVertexBase result = null;
foreach (MyVertexBase entity in entityiesToProcess)
{
if (entity is MyVertexBaseMiddle)
{
result = entity;
}
Object[] cSharpClass = entity.CSharpClasses.ToArray();
for (int i = 0; i < cSharpClass.Length; i++)
{
Type t = cSharpClass[i].GetType();
CSharpClass cl = (CSharpClass)cSharpClass[i];
checkEdges(cl, cSharpEntityModel, entity);
}
protocol[j] = protocolEntities(entity);
j++;
}
writeProtocolToFile(protocol, 0);
return result;
}
private string protocolEntities(MyVertexBase entity)
{
Object[] cSharpClass = entity.CSharpClasses.ToArray();
string result = "";
for (int i = 0; i < cSharpClass.Length; i++)
{
CSharpClass cl = (CSharpClass)cSharpClass[i];
result += cl.Name + " " + cl.NumerOfEdges + ";;" ;
}
return result;
}
private void writeProtocolToFile(string[] protocol, int navigation)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("e:\\rachota\\s14\\protocol" + numberOfProtocolStep + "_"+navigation+".txt");
// for (int i = protocol.Length - 1; i >= 0; i-- )
for (int i = 0; i < protocol.Length; i++)
{
file.Write(protocol[i]);
}
if (navigation == 1)
{
numberOfProtocolStep++;
}
file.Close();
}
private void addToEdgeStructuralConnection(EntityEdge edge, CSharpClass cSharpClass, CSharpClass currentClass) {
foreach(StructuralConnection structuralConnection in structuralConnections){
if ((cSharpClass.Name == structuralConnection.classFrom.Name) &&
(currentClass.Name == structuralConnection.classTo.Name))
{
edge.NameOfTheConnection = prepareMethodToDispaly(structuralConnection.methodFrom);
}
}
}
private string prepareMethodToDispaly(string fullName) {
string[] names = fullName.Split('.');
return names[2];
}
private void checkEdges(CSharpClass cSharpClass, ArrayList entities, MyVertexBase currentEntity)
{
foreach (MyVertexBase entity in entities)
{
if (entity.ToString() == currentEntity.ToString())
{
continue;
}
// ArrayList cSharpClasses = entity.CSharpClasses;
Object[] cSharpClasses = entity.CSharpClasses.ToArray();
for (int i = 0; i < cSharpClasses.Length; i++)
// foreach (CSharpClass currentSharpClass in cSharpClasses)
{
CSharpClass currentSharpClass = (CSharpClass)cSharpClasses[i];
int result = checkCalls(cSharpClass, currentSharpClass);
if (result != 0)
{
EntityEdge entityEdge = new EntityEdge(currentEntity.ToString(), entity.ToString());
addToEdgeStructuralConnection(entityEdge, cSharpClass, currentSharpClass);
entityEdge.Weight = result;
if (!currentEntity.Edges.Contains(entityEdge))
{
currentEntity.Edges.Add(entityEdge);
}
else
{
IEnumerator enumeratorEdges = currentEntity.Edges.GetEnumerator();
while (enumeratorEdges.MoveNext())
{
EntityEdge currentEdge = (EntityEdge)enumeratorEdges.Current;
if (currentEdge.Equals(entityEdge))
{
currentEdge.Weight += result;
break;
}
}
}
}
}
}
}
private int checkCalls(CSharpClass cSharpClass, CSharpClass currentSharpClass)
{
int result = 0;
ArrayList methods = cSharpClass.Methods;
foreach (CSharpMethod cSharpMethod in methods)
{
/*ArrayList incomingCalls = cSharpMethod.IncomingCalls;
foreach (IncomingCall incomingCall in incomingCalls)
{
if (incomingCall.ClassName == currentSharpClass.Name)
{
result++;
}
}*/
ArrayList outgoingCalls = cSharpMethod.OutgoingCalls;
foreach (MethodTypeCall outgoingCall in outgoingCalls)
{
if (outgoingCall.ClassName == currentSharpClass.Name)
{
result++;
}
}
}
return result;
}
public void methodSelected(CSharpMethod cSharpMethod)
{
cSharpMethod.ToString();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
namespace DelftTools.Utils.Binding
{
/// <summary>
/// Class to get a list Key,Value of an enum where the keys is the enum value and the value the description
/// Copied from:
/// http://geekswithblogs.net/sdorman/archive/2007/08/02/Data-Binding-an-Enum-with-Descriptions.aspx
/// </summary>
/// <example>
/// ComboBox combo = new ComboBox();
/// combo.DataSource = EnumBindingHelper.ToList(typeof(SimpleEnum));
/// combo.DisplayMember = "Value";
/// combo.ValueMember = "Key";
/// </example>
public class EnumBindingHelper
{
/// <summary>
/// Gets the <see cref="DescriptionAttribute"/> of an <see cref="Enum"/> type value.
/// </summary>
/// <param name="value">The <see cref="Enum"/> type value.</param>
/// <returns>A string containing the text of the <see cref="DescriptionAttribute"/>.</returns>
private static string GetDescription(Enum value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
string description = value.ToString();
FieldInfo fieldInfo = value.GetType().GetField(description);
var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
description = attributes[0].Description;
}
return description;
}
/// <summary>
/// Converts the <see cref="Enum"/> type to an <see cref="IList{T}"/> compatible object.
/// </summary>
/// <param name="type">The <see cref="Enum"/> type.</param>
/// <returns>An <see cref="IList{T}"/> containing the enumerated type value and description.</returns>
public static IList<KeyValuePair<TEnumType,string>> ToList<TEnumType>() where TEnumType:struct
{
Type type = typeof(TEnumType);
if (!type.IsEnum)
{
throw new InvalidOperationException("Type is not an enum type.");
}
var list = new List<KeyValuePair<TEnumType,string>>();
/*Array enumValues = Enum.GetValues(type);
foreach (Enum value in enumValues)
{
list.Add(new KeyValuePair<TEnumType, string>((TEnumType)value, GetDescription(value)));
}*/
Array enumValArray = Enum.GetValues(type);
//List<T> enumValList = new List<T>(enumValArray.Length);
foreach (Enum val in enumValArray)
{
var description = GetDescription(val);
list.Add(new KeyValuePair<TEnumType, string>((TEnumType)Enum.Parse(type, val.ToString()),description));
}
return list;
}
}
} |
using Models;
namespace OdborkyApp.Model
{
public class UserDetails
{
public int UserId { get; }
public int UnitId { get; }
public int PersonId { get; }
public string UserName { get; }
public bool IsUnitAdmin { get; }
public MembershipCategoryId CategoryId { get; }
public UserDetails(int userId, int unitId, int personId, string userName, bool isUnitAdmin, MembershipCategoryId categoryId)
{
UserId = userId;
UnitId = unitId;
PersonId = personId;
UserName = userName;
IsUnitAdmin = isUnitAdmin;
CategoryId = categoryId;
}
}
} |
namespace PatternsCore.FrameWorkStyleFactory.AbstractFactory
{
public interface ICheese
{
string ToString();
}
public class ReginaCheese:ICheese
{
public override string ToString()
{
return "regiana cheese";
}
}
public class MozerellaCheese : ICheese
{
public override string ToString()
{
return "mozerella cheese";
}
}
} |
namespace DragDotNet.Api
{
public class ScoundrelInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string DateOfBirth { get; set; }
public string IdentifyGuid { get; set; }
public string IdentityUserData { get; set; }
public PhotoInfo Photo { get; set; }
}
public class PhotoInfo
{
public string Content { get; set; }
public string MimeType { get; set; }
public string Id { get; set; }
}
public class ScoundrelDetailedInfo : ScoundrelInfo
{
public IncidentInfo[] Incidents { get; set; }
}
public class IncidentInfo
{
public string Id { get; set; }
public string IncidentDate { get; set; }
public string IncidentStatus { get; set; }
public string IncidentType { get; set; }
public string LocationId { get; set; }
public string ReportDate { get; set; }
public string ReportDescription { get; set; }
public string ReportedBy { get; set; }
public string ReportTitle { get; set; }
}
} |
using System;
namespace AnalogDisplay
{
/// <summary>
/// Threshold Adapter takes an input and outputs a series of thresholded values
/// </summary>
public class ThresholdAdapter : Adapter
{
public ThresholdAdapter()
{
//
// TODO: Add constructor logic here
//
}
public ThresholdAdapter(string aname):this()
{
name = aname;
}
public override int TranslateValue (double input)
{
// simply translate value into a value for the device
if (input > 0)
{
return (device.Max - device.Min) / 2;
}
else
{
return 0;
}
}
}
}
|
using DataLightning.Core;
using DataLightning.Core.Operators;
using DataLightning.Examples.Questions.Model;
using System;
using System.Collections.Generic;
using System.Linq;
namespace DataLightning.Examples.Questions
{
public class Engine
{
private readonly PassThroughUnit<Question> _questions;
private readonly PassThroughUnit<Answer> _answers;
private readonly PassThroughUnit<User> _users;
private readonly Dictionary<int, long> _userVersionGuard = new Dictionary<int, long>();
private readonly Dictionary<int, long> _questionVersionGuard = new Dictionary<int, long>();
private readonly Dictionary<int, long> _answerVersionGuard = new Dictionary<int, long>();
private int _maxQuestionId = 0;
private int _maxAnswerId = 0;
private int _maxUserId = 0;
public Engine(IQaApiPublisher qaApiPublisher)
{
_questions = new PassThroughUnit<Question>();
_answers = new PassThroughUnit<Answer>();
_users = new PassThroughUnit<User>();
_questions.Subscribe(new CallbackSubcriber<Question>(q => _maxQuestionId = Math.Max(_maxQuestionId, q.Id)));
_answers.Subscribe(new CallbackSubcriber<Answer>(a => _maxAnswerId = Math.Max(_maxAnswerId, a.Id)));
_users.Subscribe(new CallbackSubcriber<User>(u => _maxUserId = Math.Max(_maxUserId, u.Id)));
var qaJoin = new Join<Question, Answer>(
_questions, _answers,
q => q.Id, a => a.QuestionId,
q => q.Id, a => a.Id);
new QaApiContentMaker(qaJoin).Subscribe(new CallbackSubcriber<QaApiContent>(qaApiPublisher.Publish));
var userStatistics = new MultiJoin(
new JoinDefinitionAdapter<User>(_users, "User", u => u.Id, u => u.Id),
new JoinDefinitionAdapter<Question>(_questions, "Questions", q => q.UserId, q => q.Id),
new JoinDefinitionAdapter<Answer>(_answers, "Answers", a => a.UserId, a => a.Id));
var statMapper = new Mapper<IDictionary<string, IList<object>>, UserStatistic>(userStatistics, data =>
{
if (!data.ContainsKey("User") || data["User"].Count != 1)
return null;
return new UserStatistic
{
User = (User)data["User"].Single(),
QuestionsCount = data.ContainsKey("Questions") ? data["Questions"].Count : 0,
AnswerCount = data.ContainsKey("Answers") ? data["Answers"].Count : 0
};
});
statMapper.Subscribe(new CallbackSubcriber<UserStatistic>(s => s?.ToString()));
}
public int AddUser(string userName)
{
User user = new User
{
Id = _maxUserId + 1,
UserName = userName
};
_users.Push(user);
return user.Id;
}
public int AddQuestion(int userId, string text)
{
Question question = new Question
{
Id = _maxQuestionId + 1,
UserId = userId,
Text = text
};
_questions.Push(question);
return question.Id;
}
public void UpsertQuestion(int questionId, long version, int userId, string text)
{
if(_questionVersionGuard.ContainsKey(questionId) && _questionVersionGuard[questionId] >= version)
return;
_questionVersionGuard[questionId] = version;
Question question = new Question
{
Id = questionId,
UserId = userId,
Text = text
};
_questions.Push(question);
}
public int AddAnswer(int questionId, int userId, string text)
{
Answer answer = new Answer
{
Id = _maxAnswerId + 1,
UserId = userId,
QuestionId = questionId,
Text = text
};
_answers.Push(answer);
return answer.Id;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exp002_Sb_Saga
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("---Tripping Saga Service---");
var trippingService = new TrippingService();
Console.WriteLine("Starting...");
trippingService.Start();
Console.WriteLine("done...");
Console.ReadLine();
Console.WriteLine("Stopping...");
trippingService.Stop();
Console.WriteLine("done...");
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TaskScheduler;
namespace CarManageSystem.helper
{
public class TaskScheduler
{
/// <summary>
/// delete task
/// </summary>
/// <param name="taskName"></param>
public static void DeleteTask(string taskName)
{
TaskSchedulerClass ts = new TaskSchedulerClass();
ts.Connect(null, null, null, null);
ITaskFolder folder = ts.GetFolder("\\");
folder.DeleteTask(taskName, 0);
}
/// <summary>
/// get all tasks
/// </summary>
public static IRegisteredTaskCollection GetAllTasks()
{
TaskSchedulerClass ts = new TaskSchedulerClass();
ts.Connect(null, null, null, null);
ITaskFolder folder = ts.GetFolder("\\");
IRegisteredTaskCollection tasks_exists = folder.GetTasks(1);
return tasks_exists;
}
/// <summary>
/// check task isexists
/// </summary>
/// <param name="taskName"></param>
/// <returns></returns>
public static bool IsExists(string taskName)
{
var isExists = false;
IRegisteredTaskCollection tasks_exists = GetAllTasks();
for (int i = 1; i <= tasks_exists.Count; i++)
{
IRegisteredTask t = tasks_exists[i];
if (t.Name.Equals(taskName))
{
isExists = true;
break;
}
}
return isExists;
}
/// <summary>
/// create task
/// </summary>
/// <param name="creator"></param>
/// <param name="taskName"></param>
/// <param name="path"></param>
/// <param name="interval"></param>
/// <returns>state</returns>
public static _TASK_STATE CreateTaskScheduler(string creator, string taskName, string path, int trigerType, string startBoundary, string description)
{
try
{
if (IsExists(taskName))
{
DeleteTask(taskName);
}
//new scheduler
TaskSchedulerClass scheduler = new TaskSchedulerClass();
//pc-name/ip,username,domain,password
scheduler.Connect(null, null, null, null);
//get scheduler folder
ITaskFolder folder = scheduler.GetFolder("\\");
//set base attr
ITaskDefinition task = scheduler.NewTask(0);
task.RegistrationInfo.Author = creator;//creator
task.RegistrationInfo.Description = description;//description
//set trigger (IDailyTrigger ITimeTrigger)
//ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
//tt.Repetition.Interval = interval;// format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器
//tt.StartBoundary = startBoundary;//start time
switch (trigerType)
{
case 2: //天
IDailyTrigger dt = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
dt.StartBoundary = startBoundary;
break;
case 3: //周
IWeeklyTrigger wt = (IWeeklyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY);
wt.DaysOfWeek = 1;
wt.StartBoundary = startBoundary;
break;
case 4: //月
IMonthlyTrigger mt = (IMonthlyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_MONTHLY);
mt.DaysOfMonth = 1;
mt.StartBoundary = startBoundary;
break;
default:
break;
}
//set action
IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
action.Path = path;
task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时
task.Settings.DisallowStartIfOnBatteries = false;//只有在交流电源下才执行
task.Settings.RunOnlyIfIdle = false;//仅当计算机空闲下才执行
IRegisteredTask regTask = folder.RegisterTaskDefinition(taskName, task,
(int)_TASK_CREATION.TASK_CREATE, null, //user
null, // password
_TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
"");
IRunningTask runTask = regTask.Run(null);
return runTask.State;
}
catch (Exception ex)
{
throw ex;
}
}
}
} |
using System.Collections.Generic;
using InvertedIndex.FileHandler;
namespace InvertedIndex.Keywords
{
public interface Keyword
{
string GetWord();
HashSet<Doc> Operate(HashSet<Doc> docs, HashSet<Doc> newDocs);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace EventDepartmentManager
{
public class Log
{
public static void logging(string log)
{
using (var l = File.AppendText("../../log.txt"))
{
l.WriteLine(log);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Target : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
{
TextBox txtF= (TextBox)PreviousPage.FindControl("txtFN");
TextBox txtL= (TextBox)PreviousPage.FindControl("txtLN");
Response.Write("your fname is :"+txtF.Text.Trim());
Response.Write("your lname is:"+txtL.Text.Trim());
}
else
{
Response.Redirect("~/Source.aspx");
}
}
} |
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using WitsmlExplorer.Api.Repositories;
namespace WitsmlExplorer.Api.Models
{
public class Server: DbDocument<Guid>
{
public Server() : base(Guid.NewGuid())
{
}
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("url")]
public Uri Url { get; set; }
[JsonPropertyName("description")]
public string Description { get; set; }
public override string ToString()
{
return JsonSerializer.Serialize(this);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ProjetoMVC.Models;
namespace ProjetoMVC.Controllers
{
public class AulaController : Controller
{
[HttpGet]
public IActionResult Matricular()
{
return View();
}
[HttpPost]
public IActionResult Matricular(Matricular matricular)
{
return View();
}
public IActionResult novo()
{
return View();
}
}
} |
namespace EnduroCalculator
{
public interface ITrackCalculation
{
IPrintCalculation CalculateAll();
}
} |
/*
* Exception that is thrown when an illegal request is made to the Board.
* e.g.
* Trying to get information on non-existing room
* Maybe merge this with some other Exception in future?
* Copyright (c) Yulo Leake 2016
*/
using System;
namespace Deadwood.Model.Exceptions
{
class IllegalBoardRequestException: Exception
{
public string msg { get; private set; }
public IllegalBoardRequestException(string msg)
: base(msg)
{
this.msg = msg;
}
}
}
|
using System;
using System.Text;
public class Test
{
public string Start(int[] array, int n)
{
StringBuilder s = new StringBuilder();
Random rd = new Random();
int[] a = new int[array.Length]; //用数组a表示该数有没有被取过,取过为1。
for (int i = 0; i < n; i++)
{
int num = rd.Next(array.Length - 1);
if (a[num] == 0)
{
s.Append(array[num]);
if (i <= n - 2)
{
s.Append(",");
}
a[num] = 1;
}
else
{
i--;
continue;
}
}
return s.ToString();
}
void ASD()
{
string a = "s";
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TransitionController : MonoBehaviour {
private GameController gc;
public Text hintText;
public int timeToGame; // from transition to game time
// Use this for initialization
void Start () {
gc = GameController.gc;
gc.gameTime = timeToGame * 10;
gc.transition ();
hintText.text = gc.nextHint;
}
private IEnumerator animateText() {
for (int i = -Screen.width / 3; i < Screen.width + Screen.width; i+=10) { // zoom towards and then out
hintText.transform.position = new Vector2 (i, hintText.transform.position.y);
yield return new WaitForSeconds(0.01f);
}
}
}
|
using System;
using System.IO;
using System.Net;
namespace Common
{
public static class ExternalWebRequests
{
static ExternalWebRequests()
{
//Allow all client certs. Treat a client cert like anonymous.
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
}
public static string ExternalWebRequest(byte[] content, HttpVerbs verb, string requestUriString, int timeout = 600000)
{
//Not for GETs
if (string.Compare("GET", verb.ToString(), StringComparison.CurrentCultureIgnoreCase) == 0)
throw new ArgumentException("Specified verb not valid for ExternalWebRequest");
var request = HttpWebRequest.Create(requestUriString);
request.Method = verb.ToString();
request.ContentType = "application/json; charset=utf-8";
request.Timeout = timeout;
if (null != content)
{
request.ContentLength = content.Length;
//request.ContentType = "application/x-www-form-urlencoded";
request.GetRequestStream().Write(content, 0, content.Length);
return GetResponse(request);
}
return null;
}
public static string ExternalHttpRequest(string requestUriString, HttpVerbs verb, int timeout = 600000, bool streamResult = true)
{
var request = WebRequest.Create(requestUriString);
request.Method = verb.ToString();
request.Timeout = timeout;
if(verb == HttpVerbs.POST)
request.ContentLength = 0;
return GetResponse(request, streamResult);
}
static string GetResponse(WebRequest request, bool streamResult = true)
{
try
{
var webResponse = request.GetResponse() as HttpWebResponse;
if (webResponse != null)
{
if (!streamResult)
return webResponse.StatusCode.ToString();
if(webResponse.StatusCode == HttpStatusCode.OK && webResponse.ContentLength > 0)
{
using (var sr = new StreamReader(webResponse.GetResponseStream()))
{
var responseString = sr.ReadToEnd();
return responseString;
}
}
}
return String.Empty;
}
catch (WebException e)
{
throw e;
}
}
}
//public static class GenericsExtensions
//{
// public static string AsString<T>(this T source);
//}
public enum HttpVerbs
{
GET,
POST,
PUT,
DELETE
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using RimWorld;
using Verse;
using UnityEngine;
using Harmony;
namespace DontShaveYourHead
{
public class Controller : Mod
{
public Controller(ModContentPack content) : base(content)
{
HarmonyInstance.Create("DontShaveYourHead-Harmony").PatchAll(Assembly.GetExecutingAssembly());
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using SAAS.Framework.Orm.EfCore.UnitWork;
namespace SysBase.Domain.Models
{
public partial class SysIcon: BaseEntity<int>
{
public string Code { get; set; }
public string Size { get; set; }
public string Color { get; set; }
public string Custom { get; set; }
public string Description { get; set; }
public int Status { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Anywhere2Go.Business.Master;
using Anywhere2Go.Business.Utility;
using Anywhere2Go.DataAccess.Object;
using Anywhere2Go.DataAccess.Entity;
using Anywhere2Go.DataAccess;
namespace Claimdi.Web.MY.Controllers
{
public class ReportsController : Controller
{
// GET: Reports
public ActionResult EmployeeReport()
{
MyContext _context = new MyContext();
GenerateID genid = new GenerateID(_context);
ViewBag.Message = genid.GetNewID(7,"AY","QC");
return View();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MainWebApplication;
using MainWebApplication.Models;
namespace MainWebApplication.Data
{
public class MainWebApplicationContext : DbContext
{
public MainWebApplicationContext(DbContextOptions<MainWebApplicationContext> options)
: base(options)
{
}
public DbSet<BleHub> BleHubs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BleHub>();
modelBuilder.Entity<BleServer>()
.HasOne(b => b.BleHub)
.WithMany(h => h.BleServers);
//.HasForeignKey(c => new { c.BleHub.Name, c.BleAdr });
modelBuilder.Entity<BleService>()
.HasOne(b => b.BleServer)
.WithMany(b => b.BleServices);
//.HasForeignKey(c => new { c.BleServer.BleHub.Name, c.BleServer.BleAdr, c.SUUID });
modelBuilder.Entity<DigitalBleCharacteristic>();
modelBuilder.Entity<AnalogBleCharacteristic>();
modelBuilder.Entity<BleCharacteristic>()
.HasOne(c => c.BleService)
.WithMany(b => b.BleCharacteristics);
//.HasForeignKey(c => new { c.BleService.BleServer.BleHub.Name, c.BleService.BleServer.BleAdr, c.BleService.SUUID, c.CUUID });
}
public DbSet<MainWebApplication.Models.BleServer> BleServer { get; set; }
public DbSet<MainWebApplication.Models.BleService> BleService { get; set; }
public DbSet<MainWebApplication.Models.AnalogBleCharacteristic> AnalogBleCharacteristic { get; set; }
public DbSet<MainWebApplication.Models.DigitalBleCharacteristic> DigitalBleCharacteristic { get; set; }
public DbSet<MainWebApplication.Models.AnalogValue> AnalogValue { get; set; }
public DbSet<MainWebApplication.Models.DigitalValue> DigitalValue { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntVenta
{
public class Box
{
public int Id { get; set; }
public string Descripcion { get; set; }
public string Tema { get; set; }
public string SerialPC { get; set; }
public string ImpresoraTicket { get; set; }
public string ImpresoraA4 { get; set; }
public string Tipo { get; set; }
public bool Estado { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Langium.DataLayer.DataAccessObjects;
using Langium.DataLayer.DbModels;
using Langium.Domain;
using Langium.PresentationLayer;
using Langium.PresentationLayer.ViewModels;
using Langium.WebAPI.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace Langium.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly UserDao _dao = new UserDao();
// GET api/users
[HttpGet]
public async Task<ActionResult<IEnumerable<UserModel>>> Get()
{
var result = await _dao.GetAllUsersAsync();
if (result.Data.Count() != 0 && result.Succeded && result.Exception == null && string.IsNullOrEmpty(result.ErrorMessage))
{
return Ok(result);
}
else if (result.Exception == null)
{
return NotFound(result);
}
else
{
return BadRequest(result);
}
}
// GET api/users/{id}
[HttpGet("{id}")]
public async Task<ActionResult<UserModel>> Get(int id)
{
var result = await _dao.GetUserByIdAsync(id);
if (result.Data != null && result.Succeded && result.Exception == null && string.IsNullOrEmpty(result.ErrorMessage))
{
return Ok(result);
}
else if (result.Exception == null)
{
return NotFound(result);
}
else
{
return BadRequest(result);
}
}
// POST api/users/register
[HttpPost("register")]
public async Task<ActionResult<UserModel>> Register(UserAuthDto regData)
{
if(CheckHelper.IsValidEmail(regData.Email))
{
var added = await _dao.AddUserAsync(regData);
if (added.Data != null)
{
return Ok(added);
}
else
{
return BadRequest(added);
}
}
else
{
return BadRequest(new DataResult<UserModel>(null, "INVALID_EMAIL"));
}
}
// POST api/user/auth
[HttpPost("auth")]
public async Task<ActionResult<UserModel>> Auth(UserAuthDto authData)
{
var user = _dao.GetAllUsersAsync().Result.Data.Where(u => u.Email == authData.Email && u.Password == authData.Password).ToList();
if (user.Count() == 1)
{
return Ok(user);
}
else
{
return BadRequest(new DataResult<UserModel>(null, "WRONG_EMAIL_OR_PASSWORD"));
}
}
// PUT api/user/{id}
[HttpPut("{id}/edit")]
public async Task<ActionResult<UserModel>> Put(int id, UserUpdateDto userData)
{
var user = _dao.GetUserByIdAsync(id).Result.Data;
if(user != null)
{
if(user.Password == userData.CurrentPassword)
{
if(CheckHelper.IsValidEmail(userData.Email))
{
if (!string.IsNullOrEmpty(userData.Email))
{
user.Email = userData.Email;
}
if (!string.IsNullOrEmpty(userData.NewPassword))
{
user.Password = userData.NewPassword;
}
var result = await _dao.UpdateUserAsync(user);
return Ok(result);
}
return BadRequest(new DataResult<UserModel>(null, "INVALID_EMAIL"));
}
return BadRequest(new DataResult<UserModel>(null, "WRONG_PASSWORD"));
}
return NotFound(new DataResult<UserModel>(null, "USER_NOT_EXISTS"));
}
// DELETE api/users/{id}/delete
[HttpDelete("{id}/delete")]
public async Task<ActionResult<bool>> Delete(int id)
{
var result = await _dao.RemoveUserAsync(id);
if (result.Succeded)
{
return Ok(result);
}
else
{
return NotFound(result);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.Sconit.Entity.WMS;
using com.Sconit.Entity.INV;
using com.Sconit.Entity.Exception;
using com.Sconit.Entity;
using com.Sconit.Entity.ACC;
using System.Data;
using System.Data.SqlClient;
namespace com.Sconit.Service.Impl
{
public class PickTaskMgrImpl : BaseMgr, IPickTaskMgr
{
public IGenericMgr genericMgr { get; set; }
public void CreatePickTask(IDictionary<int, decimal> shipPlanIdAndQtyDic)
{
User user = SecurityContextHolder.Get();
SqlParameter[] paras = new SqlParameter[3];
DataTable createPickTaskTable = new DataTable();
createPickTaskTable.Columns.Add("Id", typeof(Int32));
createPickTaskTable.Columns.Add("PickQty", typeof(decimal));
foreach (var i in shipPlanIdAndQtyDic)
{
DataRow row = createPickTaskTable.NewRow();
row[0] = i.Key;
row[1] = i.Value;
createPickTaskTable.Rows.Add(row);
}
paras[0] = new SqlParameter("@CreatePickTaskTable", SqlDbType.Structured);
paras[0].Value = createPickTaskTable;
paras[1] = new SqlParameter("@CreateUserId", SqlDbType.Int);
paras[1].Value = user.Id;
paras[2] = new SqlParameter("@CreateUserNm", SqlDbType.VarChar);
paras[2].Value = user.FullName;
try
{
DataSet msgs = this.genericMgr.GetDatasetByStoredProcedure("USP_WMS_CreatePickTask", paras);
if (msgs != null && msgs.Tables != null && msgs.Tables[0] != null
&& msgs.Tables[0].Rows != null && msgs.Tables[0].Rows.Count > 0)
{
foreach (DataRow msg in msgs.Tables[0].Rows)
{
if (msg[0].ToString() == "0")
{
MessageHolder.AddInfoMessage((string)msg[1]);
}
else if (msg[0].ToString() == "1")
{
MessageHolder.AddWarningMessage((string)msg[1]);
}
else
{
MessageHolder.AddErrorMessage((string)msg[1]);
}
}
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
if (ex.InnerException.InnerException != null)
{
MessageHolder.AddErrorMessage(ex.InnerException.InnerException.Message);
}
else
{
MessageHolder.AddErrorMessage(ex.InnerException.Message);
}
}
else
{
MessageHolder.AddErrorMessage(ex.Message);
}
}
}
public void PorcessPickResult4PickQty(Dictionary<int, decimal> pickResults)
{
User user = SecurityContextHolder.Get();
DataTable pickResultTable = new DataTable();
pickResultTable.Columns.Add(new DataColumn("PickTaskId", typeof(int)));
pickResultTable.Columns.Add(new DataColumn("HuId", typeof(string)));
pickResultTable.Columns.Add(new DataColumn("Qty", typeof(decimal)));
foreach (var pickResult in pickResults)
{
DataRow row = pickResultTable.NewRow();
row[0] = pickResult.Key;
row[1] = null;
row[2] = pickResult.Value;
pickResultTable.Rows.Add(row);
}
SqlParameter[] paras = new SqlParameter[3];
paras[0] = new SqlParameter("@PickResultTable", SqlDbType.Structured);
paras[0].Value = pickResultTable;
paras[1] = new SqlParameter("@CreateUserId", SqlDbType.Int);
paras[1].Value = user.Id;
paras[1] = new SqlParameter("@CreateUserNm", SqlDbType.VarChar);
paras[1].Value = user.FullName;
try
{
DataSet msgs = this.genericMgr.GetDatasetByStoredProcedure("USP_WMS_ProcessPickResult", paras);
if (msgs != null && msgs.Tables != null && msgs.Tables[0] != null
&& msgs.Tables[0].Rows != null && msgs.Tables[0].Rows.Count > 0)
{
foreach (DataRow msg in msgs.Tables[0].Rows)
{
if (msg[0].ToString() == "0")
{
MessageHolder.AddInfoMessage((string)msg[1]);
}
else if (msg[0].ToString() == "1")
{
MessageHolder.AddWarningMessage((string)msg[1]);
}
else
{
MessageHolder.AddErrorMessage((string)msg[1]);
}
}
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
if (ex.InnerException.InnerException != null)
{
MessageHolder.AddErrorMessage(ex.InnerException.InnerException.Message);
}
else
{
MessageHolder.AddErrorMessage(ex.InnerException.Message);
}
}
else
{
MessageHolder.AddErrorMessage(ex.Message);
}
}
}
public void PorcessPickResult4PickLotNoAndHu(Dictionary<int, List<string>> pickResults)
{
User user = SecurityContextHolder.Get();
DataTable pickResultTable = new DataTable();
pickResultTable.Columns.Add(new DataColumn("PickTaskId", typeof(int)));
pickResultTable.Columns.Add(new DataColumn("HuId", typeof(string)));
pickResultTable.Columns.Add(new DataColumn("Qty", typeof(decimal)));
foreach (var pickResult in pickResults)
{
foreach (var huId in pickResult.Value)
{
DataRow row = pickResultTable.NewRow();
row[0] = pickResult.Key;
row[1] = huId;
row[2] = 0;
pickResultTable.Rows.Add(row);
}
}
SqlParameter[] paras = new SqlParameter[3];
paras[0] = new SqlParameter("@PickResultTable", SqlDbType.Structured);
paras[0].Value = pickResultTable;
paras[1] = new SqlParameter("@CreateUserId", SqlDbType.Int);
paras[1].Value = user.Id;
paras[2] = new SqlParameter("@CreateUserNm", SqlDbType.VarChar);
paras[2].Value = user.FullName;
try
{
DataSet msgs = this.genericMgr.GetDatasetByStoredProcedure("USP_WMS_ProcessPickResult", paras);
if (msgs != null && msgs.Tables != null && msgs.Tables[0] != null
&& msgs.Tables[0].Rows != null && msgs.Tables[0].Rows.Count > 0)
{
foreach (DataRow msg in msgs.Tables[0].Rows)
{
if (msg[0].ToString() == "0")
{
MessageHolder.AddInfoMessage((string)msg[1]);
}
else if (msg[0].ToString() == "1")
{
MessageHolder.AddWarningMessage((string)msg[1]);
}
else
{
MessageHolder.AddErrorMessage((string)msg[1]);
}
}
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
if (ex.InnerException.InnerException != null)
{
MessageHolder.AddErrorMessage(ex.InnerException.InnerException.Message);
}
else
{
MessageHolder.AddErrorMessage(ex.InnerException.Message);
}
}
else
{
MessageHolder.AddErrorMessage(ex.Message);
}
}
}
public void AssignPickTask(IList<PickTask> pickTaskList, string assignUser)
{
if (pickTaskList != null && pickTaskList.Count > 0)
{
User lastModifyUser = SecurityContextHolder.Get();
User user = genericMgr.FindById<User>(Convert.ToInt32(assignUser));
foreach(PickTask p in pickTaskList)
{
p.PickUserId = user.Id;
p.PickUserName = user.FullName;
p.LastModifyDate = DateTime.Now;
p.LastModifyUserId = lastModifyUser.Id;
p.LastModifyUserName = lastModifyUser.FullName;
genericMgr.Update(p);
}
}
}
public void PorcessDeliverBarCode2Hu(string deliverBarCode, string HuId)
{
User user = SecurityContextHolder.Get();
SqlParameter[] paras = new SqlParameter[4];
paras[0] = new SqlParameter("@DeliverBarCode", SqlDbType.VarChar);
paras[0].Value = deliverBarCode;
paras[1] = new SqlParameter("@HuId", SqlDbType.VarChar);
paras[1].Value = HuId;
paras[2] = new SqlParameter("@CreateUserId", SqlDbType.Int);
paras[2].Value = user.Id;
paras[3] = new SqlParameter("@CreateUserNm", SqlDbType.VarChar);
paras[3].Value = user.FullName;
try
{
DataSet msgs = this.genericMgr.GetDatasetByStoredProcedure("USP_WMS_PorcessDeliverBarCode2Hu", paras);
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
if (ex.InnerException.InnerException != null)
{
MessageHolder.AddErrorMessage(ex.InnerException.InnerException.Message);
}
else
{
MessageHolder.AddErrorMessage(ex.InnerException.Message);
}
}
else
{
MessageHolder.AddErrorMessage(ex.Message);
}
}
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace com.Sconit.Entity.WMS
{
[Serializable]
public partial class UnpickShipPlan : EntityBase
{
#region O/R Mapping Properties
public Int32 Id { get; set; }
public Int32? ShipPlanId { get; set; }
public string Flow { get; set; }
public string OrderNo { get; set; }
public Int32 OrderSeq { get; set; }
public Int32 OrderDetId { get; set; }
public DateTime StartTime { get; set; }
public DateTime? WindowTime { get; set; }
public string Item { get; set; }
public string ItemDesc { get; set; }
public string RefItemCode { get; set; }
public string Uom { get; set; }
public string BaseUom { get; set; }
public Decimal UnitQty { get; set; }
public Decimal UnitCount { get; set; }
public string UCDesc { get; set; }
public Decimal UnpickQty { get; set; }
public Int16 Priority { get; set; }
public string LocFrom { get; set; }
public string LocFromName { get; set; }
public string LocTo { get; set; }
public string LocToName { get; set; }
public string Station { get; set; }
public string Dock { get; set; }
public Boolean IsActive { get; set; }
public Int32 CreateUserId { get; set; }
public string CreateUserName { get; set; }
public DateTime CreateDate { get; set; }
public Int32 LastModifyUserId { get; set; }
public string LastModifyUserName { get; set; }
public DateTime LastModifyDate { get; set; }
public Int32? CloseUser { get; set; }
public string CloseUserName { get; set; }
public DateTime? CloseDate { get; set; }
public Int32 Version { get; set; }
public Int16? OrderType { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
UnpickShipPlan another = obj as UnpickShipPlan;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
using Airelax.Application.Account;
using Airelax.Application.Houses.Dtos.Request.ManageHouse;
using Airelax.Application.Houses.Dtos.Response;
using Airelax.Application.ManageHouses.Request;
using Airelax.Application.ManageHouses.Response;
using Airelax.Domain.Houses;
using Airelax.Domain.Houses.Defines;
using Airelax.Domain.Houses.Defines.Spaces;
using Airelax.Domain.RepositoryInterface;
using Lazcat.Infrastructure.DependencyInjection;
using Lazcat.Infrastructure.ExceptionHandlers;
using Lazcat.Infrastructure.Extensions;
namespace Airelax.Application.Houses
{
[DependencyInjection(typeof(IManageHouseService))]
public class ManageHouseService : IManageHouseService
{
private readonly IHouseRepository _houseRepository;
private readonly IAccountService _accountService;
private readonly IManageHouseRepository _manageHouseRepository;
public ManageHouseService(IManageHouseRepository manageHouseRepository, IHouseRepository houseRepository, IAccountService accountService)
{
_manageHouseRepository = manageHouseRepository;
_houseRepository = houseRepository;
_accountService = accountService;
}
public IEnumerable<MyHouseViewModel> GetMyHouseViewModel()
{
var memberId = _accountService.GetAuthMemberId();
var houses = _houseRepository.GetAll().Where(x => x.OwnerId == memberId && !x.IsDeleted);
if (houses.IsNullOrEmpty())
return new List<MyHouseViewModel>();
var list = houses.ToList();
var myHouseViewModel = list.Select(x => new MyHouseViewModel
{
HouseId = x.Id,
Title = x.Title,
HouseStatus = x.Status,
CreateState = x.CreateState,
CanRealTime = x.Policy.CanRealTime,
Location = $"{x.HouseLocation.City},{x.HouseLocation.Country}",
LastReservationTime = x.ReservationRule.LastReservationTime.ToString("yyyy-MM-dd")
});
return myHouseViewModel;
}
public async Task<ManageHouseDto> GetManageHouseInfo(string id)
{
var house = await _houseRepository.GetAsync(x => x.Id == id);
if (house == null) return null;
CheckAuthorization(house.OwnerId);
var space = _manageHouseRepository.GetSpace(id);
var manage = new ManageHouseDto
{
Id = id,
Title = house.Title,
Description =
new DescriptionDto
{
HouseDescription = house.HouseDescription?.Description,
SpaceDescription = house.HouseDescription?.SpaceDescription,
GuestPermission = house.HouseDescription?.GuestPermission,
Others = house.HouseDescription?.Others
},
Status = (int) house.Status,
ProvideFacilities = house.ProvideFacilities.Select(s => (int) s).ToList(),
NotProvideFacilities = house.NotProvideFacilities.Select(s => (int) s).ToList(),
Address = new AddressDto
{
City = house.HouseLocation?.City,
Country = house.HouseLocation?.Country,
Town = house.HouseLocation?.Town,
Address = house.HouseLocation?.AddressDetail,
ZipCode = house.HouseLocation?.ZipCode,
LocationDescription = house.HouseLocation?.LocationDescription,
TrafficDescription = house.HouseLocation?.TrafficDescription
},
HouseCategory = new HouseCategoryVM
{
Category = (int) (house.HouseCategory?.Category ?? 0), HouseType = (int) (house.HouseCategory?.HouseType ?? 0), RoomCategory = (int) (house.HouseCategory?.RoomCategory ?? 0)
},
SpaceBed = space.IsNullOrEmpty()
? null
: JsonSerializer.Serialize(
space.Select(s =>
{
var spaceBedVm = new SpaceBedVM();
if (s.Space != null)
spaceBedVm.SpaceVM = new SpaceVM {Id = s.Space.Id, HouseId = s.Space.HouseId, IsShared = s.Space.IsShared, SpaceType = (int) s.Space.SpaceType};
if (s.BedroomDetail != null)
spaceBedVm.BedroomDetailVM = new BedroomDetailVM
{
BedCount = s.BedroomDetail.BedCount,
BedType = (int?) s.BedroomDetail?.BedType,
HasIndependentBath = s.BedroomDetail.HasIndependentBath,
SpaceId = s.BedroomDetail.SpaceId
};
return spaceBedVm;
})),
CustomerNumber = house.CustomerNumber,
Origin = Convert.ToString((int) (house.HousePrice?.PerNight ?? 0)),
SweetPrice = Convert.ToString((int) (house.HousePrice?.PerWeekNight ?? 0)),
WeekDiscount = Convert.ToString((int)(house.HousePrice?.Discount?.Week ?? 0)),
MonthDiscount = Convert.ToString((int)(house.HousePrice?.Discount?.Month ?? 0)),
Fee = Convert.ToString((int)(house.HousePrice?.Fee?.CleanFee ?? 0)),
Cancel = (int) (house.Policy?.CancelPolicy ?? CancelPolicy.StrictOrNotRefund),
InstanceBooking = house.Policy?.CanRealTime ?? false,
CheckinTime = house.Policy?.CheckinTime.ToString("t", DateTimeFormatInfo.InvariantInfo),
CheckoutTime = house.Policy?.CheckoutTime.ToString("t", DateTimeFormatInfo.InvariantInfo),
CashPledge = Convert.ToString((int) (house.Policy?.CashPledge ?? 0)),
HouseRule = new HouseRuleDto
{
AllowChild = house.HouseRule.AllowChild,
AllowBaby = house.HouseRule.AllowBaby,
AllowPet = house.HouseRule.AllowPet,
AllowSmoke = house.HouseRule.AllowSmoke,
AllowParty = house.HouseRule.AllowParty,
Other = house.HouseRule.Other
},
Pictures = house.Photos?.Select(x => x.Image) ?? new List<string>()
};
return manage;
}
public HouseDescriptionInput UpdateDescription(string id, HouseDescriptionInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.HouseDescription = new HouseDescription(house.Id)
{
Description = input.Description,
SpaceDescription = input.SpaceDescription,
GuestPermission = input.GuestPermission,
Others = input.Others
};
UpdateHouse(house);
return input;
}
public HouseTitleInput UpdateTitle(string id, HouseTitleInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.Title = input.Title;
UpdateHouse(house);
return input;
}
public CustomerNumberInput UpdateCustomerNumber(string id, CustomerNumberInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.CustomerNumber = input.CustomerNumber;
UpdateHouse(house);
return input;
}
public HouseStatusInput UpdateStatus(string id, HouseStatusInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.Status = input.Status;
UpdateHouse(house);
return input;
}
public HouseAddressInput UpdateAddress(string id, HouseAddressInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.HouseLocation.Country = input.Country;
house.HouseLocation.City = input.City;
house.HouseLocation.Town = input.Town;
house.HouseLocation.ZipCode = input.ZipCode;
house.HouseLocation.AddressDetail = input.Address;
UpdateHouse(house);
return input;
}
public HouseLocationInupt UpdateLocation(string id, HouseLocationInupt input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.HouseLocation.LocationDescription = input.LocationDescription;
house.HouseLocation.TrafficDescription = input.TrafficDescription;
UpdateHouse(house);
return input;
}
public HouseCategoryInput UpdateCategory(string id, HouseCategoryInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.HouseCategory.Category = input.Category;
house.HouseCategory.HouseType = input.HouseType;
house.HouseCategory.RoomCategory = input.RoomCategory;
UpdateHouse(house);
return input;
}
public HousePriceInput UpdatePrice(string id, HousePriceInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.HousePrice.PerNight = input.Origin;
house.HousePrice.PerWeekNight = input.SweetPrice;
house.Policy.CashPledge = input.CashPledge;
house.HousePrice.Fee = new Domain.Houses.Price.Fee()
{
CleanFee = input.CleanFee
};
house.HousePrice.Discount = new Domain.Houses.Price.Discount()
{
Week = (int)input.WeekDiscount,
Month = (int)input.MonthDiscount
};
UpdateHouse(house);
return input;
}
public CancelPolicyInput UpdateCancel(string id, CancelPolicyInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.Policy.CancelPolicy = input.CancelPolicy;
UpdateHouse(house);
return input;
}
public RealTimeInput UpdateRealTime(string id, RealTimeInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.Policy.CanRealTime = input.CanRealTime;
UpdateHouse(house);
return input;
}
public CheckTimeInput UpdateCheckTime(string id, CheckTimeInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.Policy.CheckinTime = Convert.ToDateTime(input.CheckinTime);
house.Policy.CheckoutTime = Convert.ToDateTime(input.CheckoutTime);
UpdateHouse(house);
return input;
}
public HouseOtherInput UpdateOthers(string id, HouseOtherInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.HouseRule.Other = input.Other;
UpdateHouse(house);
return input;
}
public HouseRuleInput UpdateRules(string id, HouseRuleInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.HouseRule.AllowChild = input.AllowChild;
house.HouseRule.AllowBaby = input.AllowBaby;
house.HouseRule.AllowPet = input.AllowPet;
house.HouseRule.AllowSmoke = input.AllowSmoke;
house.HouseRule.AllowParty = input.AllowParty;
UpdateHouse(house);
return input;
}
public HouseFacilityInput UpdateFacility(string id, HouseFacilityInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
house.ProvideFacilities = input.ProvideFacilities;
house.NotProvideFacilities = input.NotProvideFacilities;
UpdateHouse(house);
return input;
}
public List<SpaceBed> CreateSpace(string id, HouseSpaceInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
var space = new Space(house.Id)
{
HouseId = input.HouseId,
SpaceType = (SpaceType) input.SpaceType,
IsShared = input.IsShared,
};
house.Spaces.Add(space);
UpdateHouse(house);
var SpaceId = _manageHouseRepository.GetSpace(id);
return SpaceId;
}
public HouseSpaceInput DeleteSpace(string id, HouseSpaceInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
var deleteObj = house.Spaces.LastOrDefault(x => (int) x.SpaceType == input.SpaceType);
house.Spaces.Remove(deleteObj);
UpdateHouse(house);
return input;
}
public BedroomDetailInput CreateBedroomDetail(string id, BedroomDetailInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
var updateObj = _manageHouseRepository.GetBedroom().FirstOrDefault(y => y.SpaceId == input.SpaceId && (int) y.BedType == input.BedType);
if (updateObj != null)
{
UpdateBedroomDetail(id, input);
return input;
}
var bedroomDetail = new BedroomDetail(input.SpaceId)
{
SpaceId = input.SpaceId,
BedType = (BedType) input.BedType,
BedCount = (int) input.BedCount,
HasIndependentBath = (bool) input.HasIndependentBath
};
_manageHouseRepository.CreateBedroom(bedroomDetail);
UpdateHouse(house);
return input;
}
public BedroomDetailInput UpdateBedroomDetail(string id, BedroomDetailInput input)
{
var house = GetHouse(id);
CheckAuthorization(house.OwnerId);
var updateObj = _manageHouseRepository.GetBedroom().FirstOrDefault(y => y.SpaceId == input.SpaceId && (int) y.BedType == input.BedType);
updateObj.BedCount = (int) input.BedCount;
updateObj.HasIndependentBath = (bool) input.HasIndependentBath;
UpdateHouse(house);
return input;
}
public async Task<UploadHouseImagesViewModel> UploadHouseImages(string id, UploadHouseImagesInput input)
{
var house = await _houseRepository.GetAsync(x => x.Id == id);
CheckAuthorization(house.OwnerId);
if (house == null) throw ExceptionBuilder.Build(HttpStatusCode.BadRequest, $"houseId: {id} not match any house");
house.Photos = input.Images?.Select(x => new Photo(house.Id)
{
Image = x
}).ToList();
await _houseRepository.UpdateAsync(house);
await _houseRepository.SaveChangesAsync();
return new UploadHouseImagesViewModel {Images = input.Images};
}
private void UpdateHouse(House house)
{
_manageHouseRepository.Update(house);
_manageHouseRepository.SaveChange();
}
private void CheckAuthorization(string ownerId)
{
var memberId = _accountService.GetAuthMemberId();
if (ownerId != memberId) throw ExceptionBuilder.Build(HttpStatusCode.Forbidden, "");
}
private House GetHouse(string id)
{
var house = _houseRepository.GetAsync(x => x.Id == id).Result;
if (house == null) throw ExceptionBuilder.Build(HttpStatusCode.BadRequest, $"house: {id} not match any house");
return house;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;
namespace Leaf
{
public class KeyHandler
{
#region Singleton
private static readonly KeyHandler INSTANCE = new KeyHandler();
public static KeyHandler Get()
{
return INSTANCE;
}
#endregion
bool gamePad;
Microsoft.Xna.Framework.PlayerIndex index = Microsoft.Xna.Framework.PlayerIndex.One;
KeyboardState oldKeys;
KeyboardState newKeys;
GamePadState oldPad;
GamePadState newPad;
public KeyHandler()
{
gamePad = true;
if (GamePad.GetState(Microsoft.Xna.Framework.PlayerIndex.One).IsConnected)
this.index = Microsoft.Xna.Framework.PlayerIndex.One;
else if (GamePad.GetState(Microsoft.Xna.Framework.PlayerIndex.Two).IsConnected)
this.index = Microsoft.Xna.Framework.PlayerIndex.Two;
else if (GamePad.GetState(Microsoft.Xna.Framework.PlayerIndex.Three).IsConnected)
this.index = Microsoft.Xna.Framework.PlayerIndex.Three;
else if (GamePad.GetState(Microsoft.Xna.Framework.PlayerIndex.Four).IsConnected)
this.index = Microsoft.Xna.Framework.PlayerIndex.Four;
else
gamePad = false;
}
public void UpdateKeyboardHandler()
{
this.oldKeys = newKeys;
this.oldPad = newPad;
this.newKeys = Keyboard.GetState();
if (GamePad.GetState(index).IsConnected)
{
this.newPad = GamePad.GetState(index);
gamePad = true;
}
else
gamePad = false;
}
public KeyboardState GetOldKeys()
{
return this.oldKeys;
}
public KeyboardState GetNewKeys()
{
return this.newKeys;
}
public GamePadState GetNewPad()
{
return this.newPad;
}
public bool IsKeyJustPressed(Keys key)
{
return (IsKeyDown(key, false) && !IsKeyDown(key, true));
}
public bool IsKeyHeld(Keys key)
{
return IsKeyDown(key, false);
}
public bool IsKeyDown(Keys key, bool old)
{
KeyboardState keys;
if (old)
{
keys = oldKeys;
}
else
{
keys = newKeys;
}
return (keys.IsKeyDown(key));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Web.Mvc;
using BradescoPGP.Common;
using BradescoPGP.Common.Logging;
using BradescoPGP.Repositorio;
using BradescoPGP.Web.Models;
using BradescoPGP.Web.Services;
using Newtonsoft.Json;
using OfficeOpenXml;
using static System.Net.Mime.MediaTypeNames;
namespace BradescoPGP.Web.Controllers
{
[Authorize]
public abstract class AbstractController : Controller
{
private readonly PGPEntities _context;
public string EquipeUsuario
{
get => User.Identity.IsAuthenticated ? ((ClaimsIdentity)User.Identity).FindFirst("equipe").Value : null;
}
public string MatriculaUsuario
{
get => User.Identity.IsAuthenticated ? ((ClaimsIdentity)User.Identity).FindFirst("matricula").Value : null;
}
public string Cargo
{
get => User.Identity.IsAuthenticated ? ((ClaimsIdentity)User.Identity).FindFirst("cargo").Value : null;
}
public AbstractController(DbContext context)
{
_context = context as PGPEntities;
}
public ActionResult ObterInvstFacil()
{
decimal somacap = 0;
decimal somaCapSemInvest = 0;
decimal soma = 0;
if (User.IsInRole(NivelAcesso.Especialista.ToString()))
{
//Investfácil
var resultado = _context.InvestFacilResumo.Where(i => i.Matricula == MatriculaUsuario).ToList();
soma = resultado.Sum(s => s.Vlr_Evento);
//Captação líquida
var listaCaptacaoes = _context.CaptacaoLiquidaResumo.Where(c => c.MatriculaConsultor == MatriculaUsuario).ToList();
somacap = listaCaptacaoes.Sum(s => s.VL_NET);
somaCapSemInvest = listaCaptacaoes.Where(c => !c.ProdutoMacro.ToLower().StartsWith("invest")).Sum(s => s.VL_NET);
}
else if (User.IsInRole(NivelAcesso.Master.ToString()))
{
//Investfácil
var resultado = _context.InvestFacilResumo.ToList();
soma = resultado.Sum(s => s.Vlr_Evento);
//Captação líquida
var listaCaptacaoes = _context.CaptacaoLiquidaResumo.ToList();
somacap = listaCaptacaoes.Sum(s => s.VL_NET);
somaCapSemInvest = listaCaptacaoes.Where(c => !c.ProdutoMacro.ToLower().StartsWith("invest")).Sum(s => s.VL_NET);
}
else
{
var invest = _context.InvestFacilResumo.Where(x => x.MatriculaCordenador == MatriculaUsuario).ToList();
soma = invest.Sum(s => s.Vlr_Evento);
var captacoes = _context.CaptacaoLiquidaResumo.Where(s => s.MatriculaCordenador == MatriculaUsuario)
.ToList();
somacap = captacoes.Sum(s => s.VL_NET);
somaCapSemInvest = captacoes.Where(c => c.ProdutoMacro.ToLower().StartsWith("invest")).Sum(s => s.VL_NET);
somaCapSemInvest = captacoes.Where(c => !c.ProdutoMacro.ToLower().StartsWith("invest")).Sum(s => s.VL_NET);
}
return Json(new
{
SaldoInvestfacil = soma,
SaldoCaptacaoLiquida = somacap,
SaldoCaptacaoLiquidaSemInvest = somaCapSemInvest
}, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult NovoLink(Links link)
{
if (link == null)
{
return Json(new { error = "O link não pode ser nulo" }, JsonRequestBehavior.AllowGet);
}
using (PGPEntities db = new PGPEntities())
{
db.Links.Add(link);
db.SaveChanges();
}
return Json(link, JsonRequestBehavior.AllowGet);
}
public ActionResult ExportarCaptacaoLiquida(bool mesAtual)
{
#region Versao Antiga
//var capLiqService = new CaptacaoLiquidaService();
//var capLiq = capLiqService.GerarCaptacaoLiquida();
//if(Cargo == NivelAcesso.Especialista.ToString())
//{
// capLiq = capLiq.Where(s => s.Key == MatriculaUsuario).ToDictionary(k => k.Key, v => v.Value);
//}
//else if(Cargo == NivelAcesso.Gestor.ToString())
//{
// capLiq = capLiq.Where(s => s.Value.MatriculaSupervisor == MatriculaUsuario).ToDictionary(k => k.Key, v => v.Value);
//}
//return File(GerarExcel(capLiq, "CaptacaoLiquida"), Application.Octet, "Captação Líquida.xlsx");
#endregion
var capLiqRepo = new CaptacaoLiquidaRepository();
var excelService = new CaptacaoLiquidaExcelService();
var capLiq = default(List<IGrouping<string, CaptacaoLiquida>>);
var caminhoDinheiroAgrupado = default(List<vw_CaminhoDinheiroAgrupado>);
var camDinAnalitico = default(List<CaminhoDinheiro>);
var mesDataBase = mesAtual ? DateTime.Now.ToString("MMM yyyy") : DateTime.Now.AddMonths(-1).ToString("MMM yyyy");
var anoMes = mesAtual ? DateTime.Now.ToString("yyyyMM") : DateTime.Now.AddMonths(-1).ToString("yyyyMM");
var query = _context.CaptacaoLiquida.Where(s => s.MesDataBase == mesDataBase);
if (User.IsInRole(NivelAcesso.Especialista.ToString()))
{
capLiq = query
.Where(s => s.MatriculaConsultor == MatriculaUsuario)
.GroupBy(s => s.Diretoria)
.ToList();
caminhoDinheiroAgrupado = capLiqRepo.ObterCaminhoDinheiroAgrupado(NivelAcesso.Especialista, MatriculaUsuario, anoMes);
camDinAnalitico = capLiqRepo.ObterCaminhoDinheiroAnalitico(NivelAcesso.Especialista, MatriculaUsuario, anoMes);
}
else if (User.IsInRole(NivelAcesso.Gestor.ToString()))
{
capLiq = capLiq = query
.Where(s => s.MatriculaConsultor == MatriculaUsuario)
.GroupBy(s => s.Diretoria)
.ToList();
caminhoDinheiroAgrupado = capLiqRepo.ObterCaminhoDinheiroAgrupado(NivelAcesso.Gestor, MatriculaUsuario, anoMes);
}
else
{
capLiq = capLiqRepo.ObterCapLiq(mesDataBase:mesDataBase)
.GroupBy(s => s.CordenadorPGP).ToList();
caminhoDinheiroAgrupado = capLiqRepo.ObterCaminhoDinheiroAgrupado(NivelAcesso.Master, MatriculaUsuario, anoMes);
}
var camDin = caminhoDinheiroAgrupado.ConvertAll(s => CaminhoDinheiroModel.Mapear(s));
var excel = excelService.GerarExcelCaptacaoLiquida(ref capLiq, ref camDin, ref camDinAnalitico, $"Captação Liquida - Mês Database {mesDataBase}", Cargo);
return File(excel, Application.Octet, $"Captação Liquida - Mês Database {mesDataBase}.xlsx");
}
public ActionResult ExportarInvestFacil()
{
var listaInvestfacil = new List<Investfacil>();
var nomeArquivoPlanilha = _context.WindowsServiceConfig.FirstOrDefault(c => c.Tarefa == Comando.ImportarInvestFacil.ToString()).UltimoArquivo;
var excel = default(byte[]);
if (Cargo == NivelAcesso.Especialista.ToString())
{
listaInvestfacil = _context.Investfacil.Where(i => i.MatriculaConsultor == MatriculaUsuario).ToList();
}
else if (Cargo == NivelAcesso.Gestor.ToString())
{
listaInvestfacil = _context.Investfacil.Where(i => i.MatriculaCordenador == MatriculaUsuario).ToList();
}
else
{
listaInvestfacil = _context.Investfacil.ToList();
}
var nome = nomeArquivoPlanilha.Substring(0, nomeArquivoPlanilha.Length - 4);
var result = listaInvestfacil.ConvertAll(i => {
return new InvestFacilExcel
{
AGENCIA = i.AGENCIA,
CONTA = i.CONTA,
DT_EMISSAO = i.DT_EMISSAO,
FX_PERMANENCIA = i.FX_PERMANENCIA,
FX_VOLUME = i.FX_VOLUME,
MES_DT_BASE = i.MES_DT_BASE,
NUM_CONTRATO = i.NUM_CONTRATO,
PRAZO_PERMAN = i.PRAZO_PERMAN,
SEGMENTO_CLIENTE = i.SEGMENTO_CLIENTE,
SEGMENTO_MACRO = i.SEGMENTO_MACRO,
SEGM_AGRUPADO = i.SEGM_AGRUPADO,
Vlr_Evento = i.Vlr_Evento,
Especialista = i.NomeConsultor,
Equipe = i.Plataforma
};
});
excel = GerarExcel(result, nome);
return File(excel, Application.Octet, nome + ".xlsx");
}
[HttpPost]
public JsonResult ExcluirLink(int id)
{
using (PGPEntities db = new PGPEntities())
{
var link = db.Links.FirstOrDefault(l => l.Id == id);
db.Links.Remove(link);
db.SaveChanges();
}
return Json(new { status = true });
}
public ActionResult Download(String file)
{
var fileName = file.Split(new string[] { "file:///" }, StringSplitOptions.RemoveEmptyEntries)[0];
fileName = Path.Combine(Server.MapPath("~/Download"), new FileInfo(fileName).Name);
if (!System.IO.File.Exists(fileName))
{
Log.InformationFormat("Download: O Arquivo {0} não foi encontrado!", fileName);
return View("error", new ErrorViewModel { Mensagem = "O arquivo não foi encontrado ou está sendo usado por outro processo", Status = "404", Endereco = string.Empty });
}
return File(fileName, System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName(fileName));
}
public JsonResult ObterLinks()
{
var viewModalLista = new List<LinkViewModel>();
PGPEntities db = new PGPEntities();
var links = db.Links.Where(l => l.Exibir).ToList();
links.ForEach(l =>
{
var link = new LinkViewModel
{
Id = l.Id,
Titulo = l.Titulo,
Url = l.Url
};
viewModalLista.Add(link);
});
db.Dispose();
return Json(viewModalLista, JsonRequestBehavior.AllowGet);
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (User.Identity.IsAuthenticated)
{
var dataAtual = DateTime.Now.Date;
var minDate = new DateTime(dataAtual.Year, dataAtual.Month, 1).AddMonths(-1);
var minDateVencimento = DateTime.Now.AddDays(-90);
var maxDateVencimento = DateTime.Now.AddDays(90);
var minDatePipeline = dataAtual.AddDays(-30) /* new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)*/;
var maxDatePipelineTed = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month));
var AplicacaoResgateCount = 0;
var statusInicialTed = _context.Status
.FirstOrDefault(s => s.Evento == Eventos.TEDNovo.ToString() &&
s.Descricao.ToUpper().StartsWith("Não Tratado"))?.Id ?? 0;
//Obter numero de pipes, teds, vencimentos em brancos
if (User.IsInRole(NivelAcesso.Especialista.ToString()))
{
//TEDs
ViewBag.TedsNovas = _context.TED.Include(t => t.Status)
.Join(_context.Encarteiramento,
ted => new { agencia = ted.Agencia, conta = ted.Conta },
enc => new { agencia = enc.Agencia, conta = enc.Conta },
(ted, enc) => new { ted })
.Where(t =>
t.ted.MatriculaConsultor == MatriculaUsuario &&
t.ted.Area.ToUpper().Contains("PGP") &&
//t.Status.Evento == Eventos.TED.ToString() &&
t.ted.StatusId == statusInicialTed &&
t.ted.Data >= minDate && t.ted.Data <= maxDatePipelineTed).Count();
//Vencimentos
ViewBag.VencimentosCount = _context.Vencimento.Include(i => i.Status).Join(_context.Encarteiramento,
ven => new { agencia = ven.Cod_Agencia.ToString(), conta = ven.Cod_Conta_Corrente.ToString() },
enc => new { agencia = enc.Agencia, conta = enc.Conta },
(ven, enc) => new { ven, enc.Matricula, enc.CONSULTOR })
.Where(res => res.Matricula == MatriculaUsuario &&
res.ven.Dt_Vecto_Contratado >= minDateVencimento &&
res.ven.Dt_Vecto_Contratado <= maxDateVencimento &&
res.ven.Status.Descricao.ToLower() == "em branco").Count();
//Pipelines
ViewBag.PipelinesCount = _context.Pipeline.Where(p => p.MatriculaConsultor == MatriculaUsuario &&
p.Status.Descricao.ToLower() == "em branco" &&
(p.DataProrrogada.HasValue ? p.DataProrrogada >= minDatePipeline : p.DataPrevista >= minDatePipeline)).Count();
//AplicacaoResgate
AplicacaoResgateCount = _context.AplicacaoResgate.Where(a => a.MatriculaConsultor == MatriculaUsuario &&
!a.Notificado).Count();
}
else if (User.IsInRole(NivelAcesso.Gestor.ToString()))
{
//TEDs
ViewBag.TedsNovas = _context.TED.Include(t => t.Status)
.Join(_context.Encarteiramento,
ted => new { agencia = ted.Agencia, conta = ted.Conta },
enc => new { agencia = enc.Agencia, conta = enc.Conta },
(ted, enc) => new { ted, enc.Matricula })
.Join(_context.Usuario.Include(u => u.Perfil),
t => t.Matricula,
u => u.Matricula,
(t, u) => new { Usuario = u, TED = t })
.Where(t => t.Usuario.Equipe == EquipeUsuario &&
t.TED.ted.Status.Evento == Eventos.TED.ToString() &&
t.TED.ted.Area.ToUpper().Contains("PGP") &&
t.TED.ted.StatusId == statusInicialTed &&
t.TED.ted.Data >= minDate && t.TED.ted.Data <= maxDatePipelineTed).Count();
//Vencimentos
ViewBag.VencimentosCount = _context.Vencimento.Join(_context.Encarteiramento,
ven => new { agencia = ven.Cod_Agencia.ToString(), conta = ven.Cod_Conta_Corrente.ToString() },
enc => new { agencia = enc.Agencia, conta = enc.Conta },
(ven, enc) => new { ven, enc.Matricula })
.Join(_context.Usuario,
res => res.Matricula,
usu => usu.Matricula,
(res, usu) => new { res, usu.MatriculaSupervisor, usu.Nome }
)
.Where(result => result.MatriculaSupervisor == MatriculaUsuario &&
result.res.ven.Dt_Vecto_Contratado >= minDateVencimento &&
result.res.ven.Dt_Vecto_Contratado <= maxDateVencimento &&
result.res.ven.Status.Descricao.ToLower() == "em branco").Count();
//Pipelines
ViewBag.PipelinesCount = _context.Pipeline.Join(_context.Usuario,
pipe => pipe.MatriculaConsultor,
usu => usu.Matricula,
(pipe, usu) => new { pipe, usu }
).Where(result => result.usu.MatriculaSupervisor == MatriculaUsuario &&
result.pipe.Status.Descricao.ToLower() == "em branco" &&
(result.pipe.DataProrrogada.HasValue ?
result.pipe.DataProrrogada >= minDatePipeline : result.pipe.DataPrevista >= minDatePipeline))
.ToList()
.Select(r => r.pipe).Count();
}
else
{
//TEDs
ViewBag.TedsNovas = _context.TED.Include(t => t.Status)
.Join(_context.Encarteiramento,
ted => new { agencia = ted.Agencia, conta = ted.Conta },
enc => new { agencia = enc.Agencia, conta = enc.Conta },
(ted, enc) => new { ted, enc.Matricula })
.Join(_context.Usuario,
t => t.Matricula,
usu => usu.Matricula,
(t, usu) => new { t }
)
.Where(j => j.t.ted.Area.ToUpper().Contains("PGP") &&
j.t.ted.StatusId == statusInicialTed &&
j.t.ted.Data >= minDate && j.t.ted.Data <= maxDatePipelineTed).Count();
//Vencimentos
ViewBag.VencimentosCount = _context.Vencimento.Include(i => i.Status).Join(_context.Encarteiramento,
ven => new { agencia = ven.Cod_Agencia.ToString(), conta = ven.Cod_Conta_Corrente.ToString() },
enc => new { agencia = enc.Agencia, conta = enc.Conta },
(ven, enc) => new { ven, enc.CONSULTOR }).Where(v => v.ven.Status.Descricao.ToLower() == "em branco").Count();
//Pipelines
ViewBag.PipelinesCount = _context.Pipeline
.Where(p => p.Status.Descricao.ToLower() == "em branco" &&
(p.DataProrrogada.HasValue ? p.DataProrrogada >= minDatePipeline : p.DataPrevista >= minDatePipeline)).Count();
}
ViewBag.AplicacaoResgateCount = AplicacaoResgateCount;
//Obtem os links para os arquivos de captacao-liquida e saldo u=investfacil
var linksCapInv = GetLinksCapInvest();
ViewBag.LinksCap = linksCapInv?.FirstOrDefault(l => l.Titulo == "CapLiq")?.Url;
ViewBag.LinksInvest = linksCapInv?.FirstOrDefault(l => l.Titulo == "Invest")?.Url;
//Links
var linksExternos = _context.Links.Where(l => !l.Exibir);
ViewBag.CockpitColmeia = linksExternos?.FirstOrDefault(l => l.Titulo == "Cockpit Colmeia")?.Url;
ViewBag.CockpitPost = linksExternos?.FirstOrDefault(l => l.Titulo == "Cockpit")?.Url;
ViewBag.SINVUrl = linksExternos?.FirstOrDefault(l => l.Titulo == "SINV")?.Url;
ViewBag.PSDCUrl = linksExternos?.FirstOrDefault(l => l.Titulo == "PSDC")?.Url;
//ComboBox
ViewBag.Equipes = SelectListItemGenerator.Equipes();
//Opcao para recerber notificacao
ViewBag.NotificacaoEvento = _context.Usuario.FirstOrDefault(u => u.Matricula == MatriculaUsuario)?.NotificacaoEvento;
ViewBag.NotificacaoPipeline = _context.Usuario.FirstOrDefault(u => u.Matricula == MatriculaUsuario)?.NotificacaoPipeline;
//Portabilidade
ViewBag.Status = SelectListItemGenerator.Status(EventosStatusMotivosOrigens.Portabilidade.ToString());
ViewBag.Motivos = SelectListItemGenerator.Motivos(EventosStatusMotivosOrigens.Portabilidade.ToString());
ViewBag.MotivosSemSubmotivos = JsonConvert.SerializeObject(_context.vw_MotivosSemSubmotivos.Select(s => s.Id).ToList()); //"[]";
ViewBag.SubStatus = _context.SubStatus.ToList().ConvertAll(s => new SelectListItem { Value = s.Id.ToString(), Text = s.Descricao });
((List<SelectListItem>)ViewBag.SubStatus).Insert(0, new SelectListItem { Value = string.Empty, Text = string.Empty });
ViewBag.Especialistas = SelectListItemGenerator.Especialistas();
}
base.OnActionExecuting(filterContext);
}
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new CustomJsonResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
protected byte[] GerarExcel<T>(List<T> dados, string nomePlanilha)
{
//if (!dados.Any())
//return new byte[] { };
var file = new ExcelPackage();
var wk = file.Workbook;
var properites = typeof(T).GetProperties().Where(p => !p.Name.Contains("Id")).ToArray();
var sheet = wk.Worksheets.Add(nomePlanilha);
int linha = 1;
var contatos = default(PropertyInfo[]);
var type = typeof(T);
int col = 1;
var produtos = new List<string>();
//Cabechalhos
if (type != typeof(UsuariosExportExcel))
{
linha = 2;
var colunasExcluidas = new string[] { "MatriculaSupervisor", "Area", "Notificado", "Motivos", "Situacoes" };
var colunasTeds = new string[]
{
"Agencia","Conta","NomeCliente","MatriculaConsultor","NomeConsultor","NomeSupervisor","Data","Valor","ValorAplicado","Motivo",
"Status","Equipe"
};
if (type == typeof(TEDViewModel))
{
properites = properites.Where(v => colunasTeds.Contains(v.Name)).ToArray();
}
else
{
properites = properites.Where(v => !colunasExcluidas.Contains(v.Name)).ToArray();
}
//Mesclagem primeira Linha
sheet.Cells[1, 1].Style.Font.Bold = true;
sheet.Cells[1, 1].Style.Font.Size = 16;
sheet.Cells[1, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
sheet.Cells[1, 1, 1, properites.Length + 1].Merge = true;
sheet.Cells[1, 1, 1, properites.Length].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
sheet.Cells[1, 1, 1, properites.Length].AutoFitColumns();
if (type == typeof(CockpitExportExcel))
{
properites = properites.Where(p => p.Name != "MatriculaConsultor").ToArray();
foreach (var p in properites)
{
sheet.Cells[linha, col].Value = p.Name;
sheet.Cells[linha, col].AutoFitColumns();
col++;
}
}
else
{
properites = properites.Where(p => !p.Name.Contains("RecebeNotificacao")).ToArray();
for (int idxProp = 0; idxProp < properites.Length; idxProp++)
{
if (type == typeof(TEDViewModel) && col == 1)
{
sheet.Cells[linha, col].Value = "Ag-Conta";
idxProp -= 1;
}
else
{
sheet.Cells[linha, col].Value = properites[idxProp].Name;
}
sheet.Cells[linha, col].AutoFitColumns();
col++;
}
//Cabeçalho adicional para ted
if (type == typeof(TEDViewModel))
{
contatos = typeof(TedsContatos).GetProperties().Where(p => !p.Name.Contains("Id") && !p.Name.Contains("TED")).ToArray();
//Mesclagem primeira Linha Contatos
sheet.Cells[1, col].Style.Font.Bold = true;
sheet.Cells[1, col].Value = "Contatos";
sheet.Cells[1, col].Style.Font.Size = 16;
sheet.Cells[1, col].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
sheet.Cells[1, col, 1, col + contatos.Length - 1].Merge = true;
sheet.Cells[1, col, 1, col + contatos.Length - 1].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
sheet.Cells[1, col, 1, col + contatos.Length - 1].AutoFitColumns();
foreach (var contato in contatos)
{
sheet.Cells[linha, col].Value = contato.Name;
sheet.Cells[linha, col].AutoFitColumns();
col++;
}
produtos = _context.TedsProdutos.Select(s => s.Produto).ToList();
//Mesclagem primeira Linha Contatos
sheet.Cells[1, col].Style.Font.Bold = true;
sheet.Cells[1, col].Value = "Aplicações";
sheet.Cells[1, col].Style.Font.Size = 16;
sheet.Cells[1, col].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
sheet.Cells[1, col, 1, col + produtos.Count - 1].Merge = true;
sheet.Cells[1, col, 1, col + produtos.Count - 1].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
sheet.Cells[1, col, 1, col + produtos.Count - 1].AutoFitColumns();
foreach (var produto in produtos)
{
sheet.Cells[linha, col].Value = produto;
sheet.Cells[linha, col].AutoFitColumns();
col++;
}
}
}
sheet.Cells[linha, 1, linha, properites.Length].Style.Font.Bold = true;
if (type == typeof(TEDViewModel))
{
sheet.Cells[linha, 1, linha, properites.Length + contatos.Length + produtos.Count].AutoFilter = true;
}
else
{
sheet.Cells[linha, 1, linha, properites.Length].AutoFilter = true;
}
sheet.View.FreezePanes(3, 1);
}
else
{
var colunasExcluidas = new string[] { "NotificacaoEvento", "NotificacaoPipeline", "Notificado" };
properites = properites.Where(p => !colunasExcluidas.Contains(p.Name)).ToArray();
foreach (var p in properites)
{
sheet.Cells[linha, col].Value = p.Name;
sheet.Cells[linha, col].AutoFitColumns();
col++;
}
sheet.Cells[linha, 1, linha, properites.Length].Style.Font.Bold = true;
sheet.Cells[linha, 1, linha, properites.Length].AutoFilter = true;
sheet.View.FreezePanes(2, 1);
}
//Dados
foreach (var dado in dados)
{
linha++;
if (type == typeof(PipelineViewModel))
{
sheet.Cells[1, 1].Value = "Pipelines";
var p = dado as PipelineViewModel;
sheet.Cells[linha, 1].Value = p.Cliente;
sheet.Cells[linha, 2].Value = p.Especialista;
sheet.Cells[linha, 3].Value = p.Agencia;
sheet.Cells[linha, 4].Value = p.Conta;
sheet.Cells[linha, 5].Value = p.BradescoPrincipalBanco ? "Sim" : "Não";
sheet.Cells[linha, 6].Value = p.ValorMercado;
sheet.Cells[linha, 7].Value = p.DataProrrogada?.ToShortDateString();
sheet.Cells[linha, 8].Value = p.ValorDoPipe;
sheet.Cells[linha, 9].Value = p.ValorAplicado;
sheet.Cells[linha, 10].Value = p.DataPrevista.ToShortDateString();
sheet.Cells[linha, 11].Value = p.Comentario;
sheet.Cells[linha, 12].Value = p.Motivo;
sheet.Cells[linha, 13].Value = p.Origem;
sheet.Cells[linha, 14].Value = p.Situacao;
sheet.Cells[linha, 15].Value = int.Parse(p.Matricula);
sheet.Cells[linha, 16].Value = p.Equipe;
sheet.Cells[linha, 1, linha, properites.Length].AutoFitColumns();
}
else if (type == typeof(VencimentoViewModel))
{
sheet.Cells[1, 1].Value = "Vencimentos";
var v = dado as VencimentoViewModel;
sheet.Cells[linha, 1].Value = v.Especialista;
sheet.Cells[linha, 2].Value = v.Produto;
sheet.Cells[linha, 3].Value = v.SaldoAtual;
sheet.Cells[linha, 4].Value = v.Agencia;
sheet.Cells[linha, 5].Value = v.Conta;
sheet.Cells[linha, 6].Value = v.DataVencimento.ToShortDateString();
sheet.Cells[linha, 7].Value = v.PercentualIndexador;
sheet.Cells[linha, 8].Value = v.Cliente;
sheet.Cells[linha, 9].Value = v.Status;
sheet.Cells[linha, 10].Value = int.Parse(v.Matriucla);
sheet.Cells[linha, 11].Value = v.Equipe;
sheet.Cells[linha, 1, linha, properites.Length].AutoFitColumns();
}
else if (type == typeof(CarteiraClienteExportExcel))
{
sheet.Cells[1, 1].Value = "Clusterização";
var v = dado as CarteiraClienteExportExcel;
sheet.Cells[linha, 1].Value = v.Especialista;
sheet.Cells[linha, 3].Value = v.Agencia;
sheet.Cells[linha, 2].Value = v.Conta;
sheet.Cells[linha, 4].Value = v.CPF;
sheet.Cells[linha, 5].Value = v.PerfilApi;
sheet.Cells[linha, 6].Value = v.MES_VCTO_API;
sheet.Cells[linha, 7].Value = v.NIVEL_DESENQ_FX_RISCO;
sheet.Cells[linha, 8].Value = v.NomeCliente;
sheet.Cells[linha, 9].Value = v.NomeGerente;
sheet.Cells[linha, 10].Value = v.UltimoContato?.ToShortDateString();
sheet.Cells[linha, 11].Value = v.UltimaTentativa.ToShortDateString();
sheet.Cells[linha, 12].Value = v.DiasCorridosÚltimoContato;
sheet.Cells[linha, 13].Value = v.Situacao;
sheet.Cells[linha, 14].Value = int.Parse(v.Matricula);
sheet.Cells[linha, 15].Value = v.Equipe;
sheet.Cells[linha, 16].Value = v.SALDO_TOTAL_M3;
sheet.Cells[linha, 17].Value = v.SALDO_TOTAL;
sheet.Cells[linha, 18].Value = v.SALDO_CORRETORA_BRA;
sheet.Cells[linha, 19].Value = v.SALDO_CORRETORA_AGORA;
sheet.Cells[linha, 20].Value = v.SALDO_CORRETORA;
sheet.Cells[linha, 21].Value = v.SALDO_PREVIDENCIA;
sheet.Cells[linha, 22].Value = v.SALDO_POUPANCA;
sheet.Cells[linha, 23].Value = v.SALDO_INVESTS;
sheet.Cells[linha, 24].Value = v.SALDO_DAV_20K;
sheet.Cells[linha, 25].Value = v.SALDO_COMPROMISSADAS;
sheet.Cells[linha, 26].Value = v.SALDO_ISENTOS;
sheet.Cells[linha, 27].Value = v.SALDO_LF;
sheet.Cells[linha, 28].Value = v.SALDO_CDB;
sheet.Cells[linha, 29].Value = v.SALDO_FUNDOS;
}
else if (type == typeof(TEDViewModel))
{
sheet.Cells[1, 1].Value = "TEDs";
var v = dado as TEDViewModel;
sheet.Cells[linha, 1].Value = $"{int.Parse(v.Agencia)}-{int.Parse(v.Conta)}";
sheet.Cells[linha, 2].Value = int.Parse(v.Agencia);
sheet.Cells[linha, 3].Value = int.Parse(v.Conta);
sheet.Cells[linha, 4].Value = v.NomeCliente;
sheet.Cells[linha, 5].Value = int.Parse(v.MatriculaConsultor);
sheet.Cells[linha, 6].Value = v.NomeConsultor;
sheet.Cells[linha, 7].Value = v.NomeSupervisor;
sheet.Cells[linha, 8].Value = v.Data.ToShortDateString();
sheet.Cells[linha, 9].Value = v.Valor;
sheet.Cells[linha, 10].Value = v.ValorAplicado;
sheet.Cells[linha, 11].Value = v.Motivo;
sheet.Cells[linha, 12].Value = v.Status;
sheet.Cells[linha, 13].Value = v.Equipe;
//contatos
sheet.Cells[linha, 14].Value = v.ContatouCliente.HasValue && v.ContatouCliente.Value ? "Sim" : "Não";
sheet.Cells[linha, 15].Value = v.ContatouGerente.HasValue && v.ContatouGerente.Value ? "Sim" : "Não";
sheet.Cells[linha, 16].Value = v.GerenteSolicitouNaoAtuacao.HasValue && v.GerenteSolicitouNaoAtuacao.Value ? "Sim" : "Não";
sheet.Cells[linha, 17].Value = v.GerenteInvestimentoAtuou.HasValue && v.GerenteInvestimentoAtuou.Value ? "Sim" : "Não";
sheet.Cells[linha, 18].Value = v.EspecialistaAtuou.HasValue && v.EspecialistaAtuou.Value ? "Sim" : "Não";
sheet.Cells[linha, 19].Value = v.ClienteLocalizado.HasValue && v.ClienteLocalizado.Value ? "Sim" : "Não";
sheet.Cells[linha, 20].Value = v.ClienteAceitaConsultoria.HasValue && v.ClienteAceitaConsultoria.Value ? "Sim" : "Não";
//Aplicacoes
var coluna = 21;
foreach (var prod in produtos)
{
sheet.Cells[linha, coluna].Value = v.Aplicacoes.Where(a => a.Produto == prod).Sum(s => s.Valor);
coluna++;
}
}
else if (type == typeof(CockpitExportExcel))
{
sheet.Cells[1, 1].Value = "Cockpit";
var cockpit = dado as CockpitExportExcel;
sheet.Cells[linha, 1].Value = cockpit.Equipe;
sheet.Cells[linha, 2].Value = cockpit.Especialista;
sheet.Cells[linha, 3].Value = cockpit.CodFuncionalGerente;
sheet.Cells[linha, 4].Value = cockpit.NomeGerente;
sheet.Cells[linha, 5].Value = cockpit.CPF;
sheet.Cells[linha, 6].Value = cockpit.NomeCliente;
sheet.Cells[linha, 7].Value = cockpit.CodigoAgencia;
sheet.Cells[linha, 8].Value = cockpit.NomeAgencia;
sheet.Cells[linha, 9].Value = cockpit.Conta;
sheet.Cells[linha, 10].Value = cockpit.DataEncarteiramento.HasValue ? cockpit.DataEncarteiramento.Value.ToShortDateString() : null;
sheet.Cells[linha, 11].Value = cockpit.DataContato.ToShortDateString();
sheet.Cells[linha, 12].Value = cockpit.DataRetorno.HasValue ? cockpit.DataRetorno.Value.ToShortDateString() : null;
sheet.Cells[linha, 13].Value = cockpit.Observacao;
sheet.Cells[linha, 14].Value = cockpit.ContatoTeveExito;
sheet.Cells[linha, 15].Value = cockpit.DataHoraEdicaoContato.HasValue ? cockpit.DataHoraEdicaoContato.Value.ToShortDateString() : null;
sheet.Cells[linha, 16].Value = cockpit.MeioContato;
sheet.Cells[linha, 17].Value = cockpit.ClienteNaoLocalizado;
sheet.Cells[linha, 18].Value = cockpit.TipoTransacao;
sheet.Cells[linha, 19].Value = cockpit.Finalizado;
sheet.Cells[linha, 20].Value = cockpit.GerenteRegistrouContato;
//sheet.Cells[linha, 21].Value = cockpit.MatriculaConsultor;
}
else if (type == typeof(InvestFacilExcel))
{
sheet.Cells[1, 1].Value = "Saldo Investfacil";
var investfacil = dado as InvestFacilExcel;
sheet.Cells[linha, 1].Value = investfacil.SEGMENTO_CLIENTE;
sheet.Cells[linha, 2].Value = int.Parse(investfacil.AGENCIA);
sheet.Cells[linha, 3].Value = int.Parse(investfacil.CONTA);
sheet.Cells[linha, 4].Value = long.Parse(investfacil.NUM_CONTRATO);
sheet.Cells[linha, 4].Style.Numberformat.Format = "0";
sheet.Cells[linha, 5].Value = investfacil.MES_DT_BASE;
sheet.Cells[linha, 6].Value = investfacil.DT_EMISSAO.Value.ToShortDateString();
sheet.Cells[linha, 7].Value = investfacil.PRAZO_PERMAN;
sheet.Cells[linha, 8].Value = investfacil.FX_PERMANENCIA;
sheet.Cells[linha, 9].Value = investfacil.FX_VOLUME;
sheet.Cells[linha, 10].Value = investfacil.Vlr_Evento;
sheet.Cells[linha, 10].Style.Numberformat.Format = "R$ #,##0.00";
sheet.Cells[linha, 11].Value = investfacil.SEGM_AGRUPADO;
sheet.Cells[linha, 12].Value = investfacil.SEGMENTO_MACRO;
sheet.Cells[linha, 13].Value = investfacil.Especialista;
sheet.Cells[linha, 14].Value = investfacil.Equipe;
}
else if (type == typeof(UsuariosExportExcel))
{
//Seta cabeçãlho exclusivo
var usuario = dado as UsuariosExportExcel;
sheet.Cells[linha, 1].Value = usuario.Usuario;
sheet.Cells[linha, 2].Value = int.Parse(usuario.Matricula);
sheet.Cells[linha, 3].Value = usuario.Supervisor;
sheet.Cells[linha, 4].Value = int.Parse(usuario.MatriculaGestor);
sheet.Cells[linha, 5].Value = usuario.Equipe;
sheet.Cells[linha, 6].Value = usuario.TipoDeAcesso;
sheet.Cells[linha, 7].Value = usuario.Username;
}
else if (type == typeof(AplicacaoResgateViewModel))
{
sheet.Cells[1, 1].Value = "Aplicação e Resgate";
var aplicacaoes = dado as AplicacaoResgateViewModel;
sheet.Cells[linha, 1].Value = aplicacaoes.agencia;
sheet.Cells[linha, 2].Value = aplicacaoes.conta;
sheet.Cells[linha, 3].Value = aplicacaoes.data.ToShortDateString();
var hora = aplicacaoes.hora.Hours < 10 ? $"0{aplicacaoes.hora.Hours}" : $"{aplicacaoes.hora.Hours}";
var minutos = aplicacaoes.hora.Minutes < 10 ? $"0{aplicacaoes.hora.Minutes}" : $"{aplicacaoes.hora.Minutes}";
sheet.Cells[linha, 4].Value = $"{hora }:{minutos}";
sheet.Cells[linha, 5].Value = aplicacaoes.operacao;
sheet.Cells[linha, 6].Value = aplicacaoes.perif;
sheet.Cells[linha, 7].Value = aplicacaoes.produto;
sheet.Cells[linha, 8].Value = aplicacaoes.terminal;
sheet.Cells[linha, 9].Value = aplicacaoes.valor;
sheet.Cells[linha, 10].Value = aplicacaoes.gerente;
sheet.Cells[linha, 11].Value = aplicacaoes.advisor;
sheet.Cells[linha, 12].Value = aplicacaoes.segmento;
sheet.Cells[linha, 13].Value = aplicacaoes.enviado.HasValue && aplicacaoes.enviado.Value ? "Sim" : "Não";
sheet.Cells[linha, 14].Value = aplicacaoes.Especialista;
sheet.Cells[linha, 15].Value = int.Parse(aplicacaoes.Matricula);
}
}
//Formatações finais
for (int coluna = 1; coluna < sheet.Dimension.Columns; coluna++)
{
sheet.Column(coluna).AutoFit();
}
sheet.Cells[2, 1, sheet.Dimension.Rows, sheet.Dimension.Columns].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
return file.GetAsByteArray();
}
protected List<Links> GetLinksCapInvest()
{
return _context.Links.Where(l => !l.Exibir).ToList();
}
protected override void Dispose(bool disposing)
{
if (disposing)
_context.Dispose();
base.Dispose(disposing);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using LeanEngine.Entity;
using LeanEngine.Utility;
using System.Threading.Tasks;
namespace LeanEngine.OAE
{
/// <summary>
/// Just In Time
/// </summary>
public class JIT2 : JIT
{
public JIT2(List<Plans> Plans, List<InvBalance> InvBalances, List<DemandChain> DemandChains, List<RestTime> RestTimes)
: base(Plans, InvBalances, DemandChains, RestTimes)
{
return;
}
protected override decimal GetReqQty(ItemFlow itemFlow)
{
DateTime? orderTime = itemFlow.Flow.OrderTime;
DateTime? winTime = itemFlow.Flow.WindowTime;
DateTime? nextWinTime = itemFlow.Flow.NextWindowTime;
#region Demand
OrderTracer demand = this.GetDemand_OrderTracer(itemFlow);
itemFlow.AddOrderTracer(demand);
#endregion
foreach (var loc in itemFlow.DemandSources)
{
#region Demand
var demands = this.GetOrderIss(loc, itemFlow.Item, winTime, nextWinTime, Enumerators.TracerType.Demand);
itemFlow.AddOrderTracer(demands);
#endregion
#region OnhandInv
OrderTracer onhandInv = this.GetOnhandInv_OrderTracer(loc, itemFlow.Item);
itemFlow.AddOrderTracer(onhandInv);
#endregion
#region InspectInv
OrderTracer inspectInv = this.GetInspectInv_OrderTracer(loc, itemFlow.Item);
itemFlow.AddOrderTracer(inspectInv);
#endregion
#region OrderRct
var orderRcts = this.GetOrderRct(loc, itemFlow.Item, null, winTime);
itemFlow.AddOrderTracer(orderRcts);
#endregion
#region OrderIss
DateTime? startTime = null;
if (true)//todo,config
{
startTime = orderTime;
}
//var orderIsss = this.GetOrderIss(loc, itemFlow.Item, startTime, winTime);
//考虑过期的待发需求
var orderIsss = this.GetOrderIss(loc, itemFlow.Item, null, winTime);
itemFlow.AddOrderTracer(orderIsss);
#endregion
}
decimal reqQty = this.GetReqQty(itemFlow.LocTo, itemFlow.OrderTracers);
return reqQty;
}
protected decimal GetReqQty(string loc, List<OrderTracer> list)
{
decimal reqQty = 0;
if (list != null && list.Count > 0)
{
var groupedOTList = from l in list
group l by l.Location into gj
select new
{
Location = gj.Key,
List = gj.ToList()
};
#region 找出Buff库位的剩余库存
decimal bufQty = 0; //Buff的剩余库存,待收+库存+待验-待发-需求
var bufOT = groupedOTList.Where(ot => ot.Location == loc).SingleOrDefault();
if (bufOT != null)
{
decimal totalQty = 0;
decimal issQty = 0;
foreach (var l in bufOT.List)
{
totalQty += l.Qty;
if (l.TracerType == Enumerators.TracerType.Demand ||
l.TracerType == Enumerators.TracerType.OrderIss)
{
issQty += l.Qty;
}
}
decimal rctQty = totalQty - issQty; //待收+库存
bufQty = rctQty - issQty;
}
#endregion
#region 循环各个其它需求源的需求
foreach (var groupedOT in groupedOTList.Where(ot => ot.Location != loc))
{
decimal totalQty = 0;
decimal issQty = 0;
foreach (var l in groupedOT.List)
{
totalQty += l.Qty;
if (l.TracerType == Enumerators.TracerType.Demand ||
l.TracerType == Enumerators.TracerType.OrderIss)
{
issQty += l.Qty;
}
}
decimal rctQty = totalQty - issQty;//待收+库存
#region 如果单个需求源的待收+库存 > 待发,多余的库存不纳入考虑范围
if (issQty > rctQty)
{
reqQty += issQty - rctQty;
}
#endregion
}
#endregion
#region 如果其它需求源的需求小于Buf的库存,不用产生拉动
if (reqQty - bufQty < 0)
{
reqQty = 0;
}
else
{
reqQty -= bufQty;
}
#endregion
}
return reqQty;
}
}
} |
using AutoFixture;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using SFA.DAS.ProviderCommitments.Web.Mappers.Apprentice;
using SFA.DAS.ProviderCommitments.Web.Models.Apprentice;
using System;
using System.Threading.Tasks;
using SFA.DAS.ProviderCommitments.Interfaces;
using SFA.DAS.ProviderCommitments.Web.Services.Cache;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers.Apprentice
{
[TestFixture]
public class ConfirmRequestMapperTests
{
private ConfirmRequestMapper _mapper;
private PriceViewModel _source;
private Func<Task<ConfirmRequest>> _act;
private Mock<ICacheStorageService> _cacheStorage;
private ChangeEmployerCacheItem _cacheItem;
[SetUp]
public void Arrange()
{
var fixture = new Fixture();
_source = fixture.Create<PriceViewModel>();
_cacheItem = fixture.Create<ChangeEmployerCacheItem>();
_cacheStorage = new Mock<ICacheStorageService>();
_cacheStorage.Setup(x =>
x.RetrieveFromCache<ChangeEmployerCacheItem>(It.Is<Guid>(k => k == _source.CacheKey)))
.ReturnsAsync(_cacheItem);
_mapper = new ConfirmRequestMapper(Mock.Of<ILogger<ConfirmRequestMapper>>(), _cacheStorage.Object);
_act = async () => await _mapper.Map(TestHelper.Clone(_source));
}
[Test]
public async Task ThenProviderIdMappedCorrectly()
{
var result = await _act();
Assert.AreEqual(_source.ProviderId, result.ProviderId);
}
[Test]
public async Task ThenApprenticeshipHashedIdIsMappedCorrectly()
{
var result = await _act();
Assert.AreEqual(_source.ApprenticeshipHashedId, result.ApprenticeshipHashedId);
}
[Test]
public async Task ThenPriceIsPersistedToCache()
{
await _act();
_cacheStorage.Verify(x => x.SaveToCache(It.Is<Guid>(key => key == _cacheItem.Key),
It.Is<ChangeEmployerCacheItem>(i => i.Price == _source.Price),
It.IsAny<int>()));
}
[Test]
public async Task ThenEmploymentPriceIsPersistedToCache()
{
await _act();
_cacheStorage.Verify(x => x.SaveToCache(It.Is<Guid>(key => key == _cacheItem.Key),
It.Is<ChangeEmployerCacheItem>(i => i.EmploymentPrice == _source.EmploymentPrice),
It.IsAny<int>()));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BMPFilter
{
class Filters
{
BitmapIO io;
byte[, ,] bmp;
int[, ,] newbmp;
BitmapHeader h;
BitmapInfo inf;
public Filters(BitmapIO io)
{
this.io = io;
bmp = io.GetBmp();
newbmp = io.GetNewBmp();
h = io.GetHeader();
inf = io.GetInfo();
}
public void ApplyFilter(int type)
{
Filter filter;
switch (type)
{
case 0:
filter = new AverageFilter(bmp, newbmp, inf.biWidth, inf.biHeight);
break;
case 1:
filter = new SobelXFilter(bmp, newbmp, inf.biWidth, inf.biHeight);
break;
case 2:
filter = new SobelYFilter(bmp, newbmp, inf.biWidth, inf.biHeight);
break;
case 3:
filter = new GaussXFilter(bmp, newbmp, inf.biWidth, inf.biHeight);
break;
case 4:
filter = new GaussYFilter(bmp, newbmp, inf.biWidth, inf.biHeight);
break;
case 5:
filter = new SharpenFilter(bmp, newbmp, inf.biWidth, inf.biHeight);
break;
default:
filter = new BlurFilter(bmp, newbmp, inf.biWidth, inf.biHeight);
break;
}
filter.Apply();
}
}
}
|
using System;
namespace Bat.BL
{
public class PersonService
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Checkers.Domain.Objects
{
public class CheckersGame
{
private int _firstPlayerCount = 12;
private int _secondPlayerCount = 12;
private readonly int[,] _board = new int[,]
{
{ 0,1,0,1,0,1,0,1 },
{ 1,0,1,0,1,0,1,0 },
{ 0,1,0,1,0,1,0,1 },
{ 0,0,0,0,0,0,0,0 },
{ 0,0,0,0,0,0,0,0 },
{ 2,0,2,0,2,0,2,0 },
{ 0,2,0,2,0,2,0,2 },
{ 2,0,2,0,2,0,2,0 }
};
public int[,] GetBoard()
{
return _board;
}
public Move Move(int fromRow, int fromCol, int toRow, int toCol)
{
Tuple<bool, bool> result = ValidMove(fromRow, fromCol, toRow, toCol);
if (!result.Item1)
{
return new Move();
}
_board[toRow, toCol] = _board[fromRow, fromCol];
_board[fromRow, fromCol] = 0;
if (result.Item2)
{
return new Move() { ValidMove = true, AvailableMoves = AvailableJumps(toRow, toCol) };
}
else
{
return new Move() { ValidMove = true };
}
}
public int CheckForWinState()
{
if (_firstPlayerCount == 0)
{
return 2;
}
if (_secondPlayerCount == 0)
{
return 1;
}
return 0;
}
public List<Tuple<int, int>> AvailableJumps(int fromRow, int fromCol)
{
List<Tuple<int, int>> moves = new List<Tuple<int, int>>();
int player = _board[fromRow, fromCol];
if (player == 1)
{
if (fromRow + 2 <= 7)
{
if (fromCol + 2 <= 7 && _board[fromRow + 1, fromCol + 1] != 1 && fromCol + 2 <= 7 && _board[fromRow + 1, fromCol + 1] != 0 && _board[fromRow + 2, fromCol + 2] == 0)
{
moves.Add(new Tuple<int, int>(fromRow + 2, fromCol + 2));
}
if (fromCol - 2 >= 0 && _board[fromRow + 1, fromCol - 1] != 1 && fromCol - 2 >= 0 && _board[fromRow + 1, fromCol - 1] != 0 && _board[fromRow + 2, fromCol - 2] == 0)
{
moves.Add(new Tuple<int, int>(fromRow + 2, fromCol - 2));
}
}
}
else
{
if (fromRow - 2 >= 0)
{
if (fromCol + 2 <= 7 && _board[fromRow - 1, fromCol + 1] != 2 && fromCol + 2 <= 7 && _board[fromRow - 1, fromCol + 1] != 0 && _board[fromRow - 2, fromCol + 2] == 0)
{
moves.Add(new Tuple<int, int>(fromRow - 2, fromCol + 2));
}
if (fromCol - 2 >= 0 && _board[fromRow - 1, fromCol - 1] != 2 && fromCol - 2 >= 0 && _board[fromRow - 1, fromCol - 1] != 0 && _board[fromRow - 2, fromCol - 2] == 0)
{
moves.Add(new Tuple<int, int>(fromRow - 2, fromCol + 2));
}
}
}
return moves;
}
/// <summary>
/// returns a tuple first item is for valid move and second item is for jump
/// </summary>
/// <param name="fromX"></param>
/// <param name="fromY"></param>
/// <param name="toX"></param>
/// <param name="toY"></param>
/// <returns></returns>
public Tuple<bool, bool> ValidMove(int fromX, int fromY, int toX, int toY)
{
if (fromX < 0 || fromX > 7 || fromY < 0 || fromY > 7 ||
toX < 0 || toX > 7 || toY < 0 || toY > 7)
{
return new Tuple<bool, bool>(false, false);
}
bool validMove;
int player = _board[fromX, fromY];
if (player == 0 || _board[toX, toY] != 0)
{
return new Tuple<bool, bool>(false, false); ;
}
if (player == 1)
{
bool xCheck = fromX + 1 == toX;
bool yCheck = fromY - 1 == toY || fromY + 1 == toY;
validMove = xCheck && yCheck;
if (!validMove)
{
//check for jump
xCheck = fromX + 2 == toX;
yCheck = fromY - 2 == toY || fromY + 2 == toY;
validMove = xCheck && yCheck;
if (validMove)
{
if (fromY < toY)
{
if (_board[fromX + 1, fromY + 1] != 1 && _board[fromX + 1, fromY + 1] != 0)
{
_board[fromX + 1, fromY + 1] = 0;
}
else
{
return new Tuple<bool, bool>(false, false); ;
}
}
else
{
if (_board[fromX + 1, fromY - 1] != 1 && _board[fromX + 1, fromY - 1] != 0 )
{
_board[fromX + 1, fromY - 1] = 0;
}
else
{
return new Tuple<bool, bool>(false, false); ;
}
}
--_secondPlayerCount;
return new Tuple<bool, bool>(true, true);
}
else
{
return new Tuple<bool, bool>(false, false);
}
}
}
else // player two
{
bool xCheck = fromX - 1 == toX;
bool yCheck = fromY - 1 == toY || fromY + 1 == toY;
validMove = xCheck && yCheck;
if (!validMove)
{
//check for jump
xCheck = fromX - 2 == toX;
yCheck = fromY - 2 == toY || fromY + 2 == toY;
validMove = xCheck && yCheck;
if (validMove)
{
if (fromY < toY)
{
if (_board[fromX - 1, fromY + 1] != 2 && _board[fromX - 1, fromY + 1] != 0)
{
_board[fromX - 1, fromY + 1] = 0;
}
else
{
return new Tuple<bool, bool>(false, false); ;
}
}
else
{
if (_board[fromX - 1, fromY - 1] != 2 && _board[fromX - 1, fromY - 1] != 0)
{
_board[fromX - 1, fromY - 1] = 0;
}
else
{
return new Tuple<bool, bool>(false, false); ;
}
}
--_firstPlayerCount;
return new Tuple<bool, bool>(true, true);
}
else
{
return new Tuple<bool, bool>(false, false);
}
}
}
return new Tuple<bool, bool>(true, false);
}
}
}
|
namespace Searcher
{
using Microsoft.VisualStudio.Shell;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
/// <summary>
/// Interaction logic for SearcherToolWindowControl.
/// </summary>
public partial class SearcherToolWindowControl : UserControl
{
private readonly EnvDTE.DTE dte = (EnvDTE.DTE)Package.GetGlobalService(typeof(EnvDTE.DTE));
Process searcher;
Stopwatch stopwatch = new Stopwatch();
private struct SearchTool
{
public string Name { get; set; }
public string Executable { get; set; }
public string DefaultArgs { get; set; }
public override string ToString()
{
return Name;
}
}
private List<SearchTool> searchTools = new List<SearchTool>()
{
new SearchTool() { Name = "ripgrep", Executable = "rg.exe", DefaultArgs = "-n -g \"!Libraries/**\" --type cpp" },
new SearchTool() { Name = "The Silver Searcher", Executable = "ag.exe", DefaultArgs = "--ignore \"./Libraries/\" --cpp" },
new SearchTool() { Name = "The Platinum Searcher", Executable = "pt.exe", DefaultArgs = "" },
new SearchTool() { Name = "grep", Executable = @"C:\Program Files\Git\usr\bin\grep.exe", DefaultArgs = "--exclude-dir=\"Libraries\" --include=\"*.cpp\" --include=\"*.h\" -rnw . -e" },
};
public SearcherToolWindowControl()
{
this.InitializeComponent();
}
private void browseLocationButton_Click(object sender, RoutedEventArgs e)
{
using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
locationTextBox.Text = dialog.SelectedPath;
}
}
}
private void InitSearher()
{
if (searcher != null)
{
searcher.Close();
}
searcher = new Process();
searcher.StartInfo.UseShellExecute = false;
searcher.StartInfo.CreateNoWindow = true;
searcher.StartInfo.RedirectStandardOutput = true;
searcher.StartInfo.RedirectStandardError = true;
searcher.EnableRaisingEvents = true;
// Searcher process async handlers
searcher.OutputDataReceived += new DataReceivedEventHandler(SearcherOutputHandler);
searcher.ErrorDataReceived += new DataReceivedEventHandler(SearcherOutputHandler);
searcher.Exited += new EventHandler(SearcherExited);
}
private void searcherWindow_Loaded(object sender, RoutedEventArgs e)
{
searchToolsComboBox.ItemsSource = searchTools;
InitSearher();
}
private void searchButton_Click(object sender, RoutedEventArgs e)
{
if (searchButton.Content.ToString() == "Stop")
{
searcher.Kill();
searcher.Close();
searchButton.IsEnabled = false;
return;
}
resultsStackPanel.Children.Clear();
elapsedTextBox.Text = "";
InitSearher();
searcher.StartInfo.FileName = ((SearchTool)searchToolsComboBox.SelectedItem).Executable;
searcher.StartInfo.Arguments = argsTextBox.Text + " " + searchTermTextBox.Text;
searcher.StartInfo.WorkingDirectory = locationTextBox.Text;
//Start process and handlers
searchButton.Content = "Stop";
stopwatch.Reset();
stopwatch.Start();
try
{
searcher.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
searcher.BeginOutputReadLine();
searcher.BeginErrorReadLine();
}
private TextBox StringToTextBox(string text, Color? color = null)
{
var tb = new TextBox() {
IsReadOnly = true,
BorderThickness = new Thickness(0),
Foreground = new SolidColorBrush(color ?? Colors.Black),
Text = text
};
tb.MouseDoubleClick += resultTextBox_DoubleClick;
return tb;
}
private void resultTextBox_DoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
var result = ((TextBox)sender).Text;
var elements = result.Split(':');
// We're looking for file:line_no:match
if (elements.Length > 2)
{
// Some tools return Unix paths
string file = Path.Combine(locationTextBox.Text, elements[0].Replace('/', '\\'));
if (!File.Exists(file))
{
return;
}
int lineNo = 0;
if (!Int32.TryParse(elements[1], out lineNo))
{
return;
}
EnvDTE.Window window = dte.ItemOperations.OpenFile(file, EnvDTE.Constants.vsViewKindCode);
window.Activate();
window.SetFocus();
((EnvDTE.TextSelection)dte.ActiveDocument.Selection).GotoLine(lineNo, true);
}
}
private void SearcherOutputHandler(object sendingProcess, DataReceivedEventArgs eventArgs)
{
Dispatcher.Invoke(() =>
{
if (eventArgs.Data != null && eventArgs.Data.ToString() != string.Empty)
{
var result = eventArgs.Data.ToString();
resultsStackPanel.Children.Add(StringToTextBox(result));
}
});
}
void SearcherExited(object sender, System.EventArgs e)
{
Dispatcher.Invoke(() =>
{
searcher.Close();
stopwatch.Stop();
elapsedTextBox.Text = stopwatch.Elapsed.ToString();
searchButton.Content = "Search";
searchButton.IsEnabled = true;
});
}
private void searchersComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
EnableDisableSearch(null, null);
argsTextBox.Text = ((SearchTool)searchToolsComboBox.SelectedItem).DefaultArgs;
}
private void EnableDisableSearch(object sender, TextChangedEventArgs e)
{
if (locationTextBox.Text != string.Empty &&
searchToolsComboBox.SelectedIndex >= 0 &&
searchTermTextBox.Text != string.Empty)
{
searchButton.IsEnabled = true;
}
else
{
searchButton.IsEnabled = false;
}
}
}
} |
using Anywhere2Go.Business.Master;
using Anywhere2Go.DataAccess;
using Anywhere2Go.DataAccess.Entity;
using Anywhere2Go.DataAccess.Object;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Anywhere2Go.Business.Utility
{
public class NaTemplateReportLogic
{
private MyContext _context = null;
public NaTemplateReportLogic(MyContext context)
{
_context = context;
}
public NaTemplateReportLogic()
{
_context = new MyContext(Configurator.CrmSqlConnection);
}
public resultCaseCarDetail GetCarParty(List<CarParty> carParties)
{
if (carParties != null && carParties.Count > 0)
{
return new resultCaseCarDetail
{
TitleCar = "รถคู่กรณี",
carRegis = carParties.FirstOrDefault().CarRegis,
insurance = (carParties.FirstOrDefault().PolicyInsurer != null ? carParties.FirstOrDefault().PolicyInsurer.InsName : ""),
policyType = carParties.FirstOrDefault().PolicyType
};
}
return null;
}
public CarParty GetCarPartyFirst(List<CarParty> carParties)
{
if (carParties == null && carParties.Count == 0)
{
return null;
}
return carParties.FirstOrDefault();
}
public NaTemplateModel ConvertTaskToNaTemplateModel(Task task)
{
if (task == null)
{
return null;
}
NaTemplateModel naTemplateModel = new NaTemplateModel();
naTemplateModel.accidentDate = task.AccidentDate;
naTemplateModel.policyType = task.CarInfo.policyType;
naTemplateModel.resultCase = (task.Na.resultCase != null ? task.Na.resultCase.ResultCaseName : "");
naTemplateModel.schedulePlance = task.schedulePlance;
var carPartyFirst = GetCarPartyFirst(task.CarParties);
naTemplateModel.resultCaseTrue = new resultCaseCarDetail
{
TitleCar = task.Na.resultCaseId == "1003" ? "รถประกัน" : "รถคู่กรณี",
carRegis = task.Na.resultCaseId == "1003" ? task.CarInfo.carRegis : (carPartyFirst != null ? carPartyFirst.CarRegis : ""),
insurance = task.Na.resultCaseId == "1003" ? task.CarInfo.policyInsurer.InsName : (carPartyFirst != null && carPartyFirst.PolicyInsurer != null ? carPartyFirst.PolicyInsurer.InsName : ""),
policyType = task.Na.resultCaseId == "1003" ? task.CarInfo.policyType : (carPartyFirst != null ? carPartyFirst.PolicyType : "")
};
naTemplateModel.resultCaseFalse = new resultCaseCarDetail
{
TitleCar = task.Na.resultCaseId == "1002" ? "รถประกัน" : "รถคู่กรณี",
carRegis = task.Na.resultCaseId == "1002" ? task.CarInfo.carRegis : (carPartyFirst != null ? carPartyFirst.CarRegis : ""),
insurance = task.Na.resultCaseId == "1002" ? task.CarInfo.policyInsurer.InsName : (carPartyFirst != null && carPartyFirst.PolicyInsurer != null ? carPartyFirst.PolicyInsurer.InsName : ""),
policyType = task.Na.resultCaseId == "1002" ? task.CarInfo.policyType : (carPartyFirst != null ? carPartyFirst.PolicyType : "")
};
naTemplateModel.carParty = GetCarParty(task.CarParties);
return naTemplateModel;
}
public string GenFormatTemplate(string taskID, string templateID, bool isReplaceEnter = false)
{
string formatReport = "";
try
{
CultureInfo ci = new CultureInfo("th-TH");
var req = new Repository<TemplateNaResult>(_context);
var Template = req.GetQuery().Where(t => t.ID == templateID && t.isActive == true).FirstOrDefault().TemplateFormat;
if (Template != null)
{
var taskReq = new Repository<Task>(_context);
var dataTask = taskReq.GetQuery().Where(t => t.taskId == taskID).FirstOrDefault();
var result = ConvertTaskToNaTemplateModel(dataTask);
if (result != null)
{
string SYMBOL_REPLACE = "x";
Template = Template.Replace("[schedulePlance]", (!string.IsNullOrEmpty(result.schedulePlance) ? result.schedulePlance : SYMBOL_REPLACE));
Template = Template.Replace("[accidentDate]", (result.accidentDate.HasValue ? result.accidentDate.Value.ToString("dd MMMM yyyy HH:mm", ci) : SYMBOL_REPLACE));
Template = Template.Replace("[policyType]", (!string.IsNullOrEmpty(result.policyType) ? result.policyType : SYMBOL_REPLACE));
Template = Template.Replace("[resultCaseTrue.TitleCar]", (result.resultCaseTrue != null && !string.IsNullOrEmpty(result.resultCaseTrue.TitleCar) ? result.resultCaseTrue.TitleCar : SYMBOL_REPLACE));
Template = Template.Replace("[resultCaseFalse.TitleCar]", (result.resultCaseFalse != null && !string.IsNullOrEmpty(result.resultCaseFalse.TitleCar) ? result.resultCaseFalse.TitleCar : SYMBOL_REPLACE));
Template = Template.Replace("[resultCaseTrue.insurance]", (result.resultCaseTrue != null && !string.IsNullOrEmpty(result.resultCaseFalse.insurance) ? result.resultCaseFalse.insurance : SYMBOL_REPLACE));
Template = Template.Replace("[resultCaseFalse.insurance]", (result.resultCaseFalse != null && !string.IsNullOrEmpty(result.resultCaseFalse.insurance) ? result.resultCaseFalse.insurance : SYMBOL_REPLACE));
Template = Template.Replace("[resultCaseTrue.policyType]", (result.resultCaseTrue != null && !string.IsNullOrEmpty(result.resultCaseFalse.policyType) ? result.resultCaseFalse.policyType : SYMBOL_REPLACE));
Template = Template.Replace("[resultCaseFalse.policyType]", (result.resultCaseFalse != null && !string.IsNullOrEmpty(result.resultCaseFalse.policyType) ? result.resultCaseFalse.policyType : SYMBOL_REPLACE));
Template = Template.Replace("[carParty.insurance]", (result.carParty != null && !string.IsNullOrEmpty(result.carParty.insurance) ? result.carParty.insurance : SYMBOL_REPLACE));
Template = Template.Replace("[carParty.policyType]", (result.carParty != null && !string.IsNullOrEmpty(result.carParty.policyType) ? result.carParty.policyType : SYMBOL_REPLACE));
Template = Template.Replace("[resultCase]", (!string.IsNullOrEmpty(result.resultCase) ? result.resultCase : SYMBOL_REPLACE));
if (isReplaceEnter)
{
Template = Template.Replace("\r\n", "<br/>");
}
}
formatReport = Template;
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
return formatReport;
}
public List<TemplateNaResult> GetTemplateList(string templateType)
{
var req = new Repository<TemplateNaResult>(_context);
var result = req.GetQuery().Where(t => t.TemplateType == templateType && t.isActive == true).OrderByDescending(o => o.sort).ThenBy(o => o.TemplateName).ToList();
return result;
}
public BaseResult<TemplateNaResultResponse> GetTemplateNaResults()
{
BaseResult<TemplateNaResultResponse> response = new BaseResult<TemplateNaResultResponse>();
response.Result = new TemplateNaResultResponse();
var req = new Repository<TemplateNaResult>(_context);
response.Result.TemplateNaResult = req.GetQuery().Where(t => t.isActive == true).OrderByDescending(o => o.sort).ThenBy(o => o.TemplateName).Select(t =>
new SyncTemplateNaResult
{
ID = t.ID,
TemplateName = t.TemplateName,
TemplateType = t.TemplateType,
Sort = t.sort
}
).ToList();
return response;
}
}
}
|
namespace _01_Alabo.Cloud.Core.SendSms.Domain.Enums
{
public enum SendState
{
/// <summary>
/// 初始状态 未发送
/// </summary>
Root = 0,
/// <summary>
/// 发送成功
/// </summary>
Success = 1,
/// <summary>
/// 发送失败
/// </summary>
Fail = 2,
/// <summary>
/// 该状态无效 用于查询所有
/// </summary>
All = 3
}
} |
using ServiceQuotes.Domain.Entities;
using System.Threading.Tasks;
namespace ServiceQuotes.Domain.Repositories
{
public interface IRefreshTokenRepository : IRepository<RefreshToken>
{
Task<RefreshToken> GetByToken(string token);
}
}
|
using Witsml.Data;
using Witsml.Extensions;
using WitsmlExplorer.Api.Models;
namespace WitsmlExplorer.Api.Query
{
public static class WellQueries
{
public static WitsmlWells GetAllWitsmlWells()
{
return GetWitsmlWell();
}
public static WitsmlWells GetWitsmlWellByUid(string wellUid)
{
return GetWitsmlWell(wellUid);
}
public static WitsmlWells CreateWitsmlWell(Well well)
{
return new WitsmlWells
{
Wells = new WitsmlWell
{
Uid = well.Uid,
Name = well.Name,
Field = well.Field.NullIfEmpty(),
Country = well.Country.NullIfEmpty(),
Operator = well.Operator.NullIfEmpty(),
TimeZone = well.TimeZone
}.AsSingletonList()
};
}
public static WitsmlWells UpdateWitsmlWell(string wellUid, string name)
{
return new WitsmlWells
{
Wells = new WitsmlWell
{
Uid = wellUid,
Name = name
}.AsSingletonList()
};
}
public static WitsmlWells UpdateWitsmlWell(Well well)
{
return new WitsmlWells
{
Wells = new WitsmlWell
{
Uid = well.Uid,
Name = well.Name,
Field = well.Field,
TimeZone = well.TimeZone,
Country = well.Country,
Operator = well.Operator
}.AsSingletonList()
};
}
public static WitsmlWells DeleteWitsmlWell(string wellUid)
{
return new WitsmlWells {Wells = new WitsmlWell {Uid = wellUid}.AsSingletonList()};
}
private static WitsmlWells GetWitsmlWell(string wellUid = "")
{
return new WitsmlWells
{
Wells = new WitsmlWell
{
Uid = wellUid,
Name = "",
Field = "",
Operator = "",
TimeZone = "",
CommonData = new WitsmlCommonData
{
DTimCreation = "",
DTimLastChange = "",
ItemState = ""
}
}.AsSingletonList()
};
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Spwn : MonoBehaviour
{
public GameObject prefab;
public GameObject prefab2;
private Pool pool;
private Pool pool2;
private float randomX,randomY,randomZ;
void Start()
{
pool = new Pool(prefab);
pool2 = new Pool(prefab2);
StartCoroutine(CreateObject());
}
private void Update()
{
randomX = UnityEngine.Random.Range(-2.6f, 2.6f);
randomY= UnityEngine.Random.Range(-2.6f, 2.6f);
randomZ = UnityEngine.Random.Range(-25f, 25f);
}
IEnumerator CreateObject()
{
while (true)
{
GameObject obj = pool.TakeObjPool();
obj.transform.position = new Vector3(randomX, -6, 2);
obj.transform.rotation = Quaternion.Euler(0f, 0f, randomZ);
GameObject obj2= pool2.TakeObjPool();
obj2.transform.position = new Vector3(randomY, -6, 2);
obj2.transform.rotation = Quaternion.Euler(0f, 0f, randomZ);
yield return new WaitForSeconds(3f);
pool.AddObjPool(obj);
pool2.AddObjPool(obj2);
}
}
}
|
using Microsoft.Xna.Framework;
using Newtonsoft.Json.Linq;
using ProjectBueno.Engine;
using ProjectBueno.Game.Entities;
using System;
namespace ProjectBueno.Game.Spells
{
//Base Skill for Shapes
public abstract class SkillShape : Skill
{
protected SkillShape(JObject skill) : base(skill)
{
#warning To load
potencyMult = (float?)skill["potencyMult"] ?? 1.0f;
arcCount = (int?)skill["ArcCount"] ?? 0;
dmgCooldown = 15;
}
//public AnimatedTexture projTexture;
public float potencyMult;
public int dmgCooldown;
public int arcCount;
public abstract Projectile generateProjectiles(Vector2 pos, Spell spell, GameHandler game, Entity target, Entity owner);
}
//Concrete Shapes
public class ShapeBall : SkillShape
{
public ShapeBall(JObject skill) : base(skill)
{
speed = (float)skill["projSpeed"];
}
public float speed { get; protected set; }
public override Projectile generateProjectiles(Vector2 pos, Spell spell, GameHandler game, Entity target, Entity owner)
{
Vector2 dir;
if (target != null)
{
dir = target.pos - pos;
}
else
{
dir = game.posFromScreenPos(Main.newMouseState.Position.ToVector2()) - pos;//dir = game.player.dir.Vector();
}
dir.Normalize();
return new ProjectileBall(spell, game, target, owner, pos, dir, speed);
}
}
public class ShapeBurst : SkillShape
{
public ShapeBurst(JObject skill) : base(skill)
{
partCount = (int)skill["projCount"];
radSquared = (float)skill["radius"] * (float)skill["radius"];
arcRadSquared = radSquared * (float)skill["arcScale"] * (float)skill["arcScale"];
cooldownMult = (int)skill["cooldownMult"];
arcCount = 1;
}
protected int partCount;
protected float radSquared;
protected float arcRadSquared;
protected int cooldownMult;
private static Random random = new Random(); //For testing
public override int modCooldown(int cooldownIn)
{
return base.modCooldown(cooldownIn) * cooldownMult;
}
public override Projectile generateProjectiles(Vector2 pos, Spell spell, GameHandler game, Entity target, Entity owner)
{
ProjectileBurst projReturn = new ProjectileBurst(spell, game, target, owner, pos, spell.arcCount == 0 ? radSquared : arcRadSquared);
Vector2 vecSpeed;
for (int i = 0; i < partCount; i++)
{
vecSpeed = new Vector2((float)(random.NextDouble() < 0.5 ? random.NextDouble() : random.NextDouble() * -1.0), (float)(random.NextDouble() < 0.5 ? random.NextDouble() : random.NextDouble() * -1.0));
vecSpeed.Normalize();
vecSpeed *= (float)(random.NextDouble() * 2.0 + 1.0);
projReturn.addProjectile(pos, vecSpeed);
}
return projReturn;
}
}
public class ShapeStream : SkillShape
{
public ShapeStream(JObject skill) : base(skill)
{
partCount = (int)skill["projCount"];
length = (float)skill["length"];
cooldown = (int?)skill["cooldown"] ?? 0;
}
protected int partCount;
protected float length;
private static Random random = new Random();
public override int modCooldown(int cooldownIn)
{
return cooldown;
}
public override Projectile generateProjectiles(Vector2 origin, Spell spell, GameHandler game, Entity target, Entity owner)
{
Vector2 dir;
if (target != null)
{
dir = target.pos - origin;
}
else
{
dir = game.posFromScreenPos(Main.newMouseState.Position.ToVector2()) - origin;//dir = game.player.dir.Vector();
}
dir.Normalize();
ProjectileStream projReturn = new ProjectileStream(spell, game, target, owner);
float maxMult = projReturn.ProcessCollision(origin, dir * length);
float mult;
for (int i = 0; i < partCount; i++)
{
mult = (float)random.NextDouble();
if (mult < maxMult)
{
projReturn.addProjectile(origin + dir * length * mult);
}
}
return projReturn;
}
}
} |
using Alabo.Cloud.People.UserDigitals.Domain.Entities;
using Alabo.Domains.Repositories;
using MongoDB.Bson;
namespace Alabo.Cloud.People.UserDigitals.Domain.Repositories
{
public interface IUserDigitalRepository : IRepository<UserDigital, ObjectId>
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CRL.Business.OnlinePay.Company.ChinaPay.TradeQuery
{
public class Response : ResponseBase
{
public override string ResponseName
{
get { return "A101TranStaInqRs"; }
}
/// <summary>
/// 原交易请求流水号
/// </summary>
public string OrgSrcReqId
{
get;
set;
}
/// <summary>
/// 原交易系统日期
/// </summary>
public string OrgSrcReqDate
{
get;
set;
}
/// <summary>
/// 交易状态 00 交易成功 01 交易不存在 02 交易失败
/// </summary>
public string Status
{
get;
set;
}
/// <summary>
/// 失败原因
/// </summary>
public string ReturnMsg
{
get;
set;
}
/// <summary>
/// 订单号
/// </summary>
public string OrgOrderNo
{
get;
set;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using EQS.AccessControl.Domain.ObjectValue;
namespace EQS.AccessControl.Domain.Interfaces.Services.Base
{
public interface IBaseService<TEntity> where TEntity : class
{
TEntity Create(TEntity entity);
TEntity Update(TEntity entity);
TEntity GetById(int id);
IEnumerable<TEntity> GetAll();
IEnumerable<TEntity> GetByExpression(SearchObject predicate);
TEntity Delete(int id);
}
}
|
// -----------------------------------------------------------------------
// <copyright file="LocalizationHelper.cs">
// Copyright (c) Michal Pokorný. All Rights Reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Pentagon.Extensions.Localization {
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Threading;
public static class LocalizationHelper
{
public static IReadOnlyDictionary<string, string> GetResources([NotNull] CultureObject cultureEntity, bool includeParent = false)
{
if (cultureEntity == null)
throw new ArgumentNullException(nameof(cultureEntity));
var resources = cultureEntity.Resources;
if (!includeParent)
return resources;
var keys = resources.ToDictionary(a => a.Key, a => a.Value);
if (cultureEntity.ParentCulture != null)
{
var innerResources = GetResources(cultureEntity.ParentCulture, includeParent);
var missingKeys = innerResources.Select(a => a.Key).Except(resources.Select(a => a.Key));
foreach (var missingKey in missingKeys)
{
var resource = innerResources.FirstOrDefault(a => a.Key == missingKey);
keys.Add(resource.Key, resource.Value);
}
}
return keys;
}
public static CultureObject GetCultureObject(CultureInfo culture, Func<string, IDictionary<string, string>> allResources)
{
return GetCultureObjectAsync(culture, s => Task.FromResult(allResources(s))).AwaitSynchronously();
}
public static async Task<CultureObject> GetCultureObjectAsync(CultureInfo culture, Func<string, Task<IDictionary<string, string>>> allResources)
{
var resources = await allResources(culture.Name).ConfigureAwait(false);
if (resources == null)
{
var invariantResources = await allResources(LocalizationConstants.Invariant).ConfigureAwait(false);
if (invariantResources != null)
{
return new CultureObject(LocalizationConstants.Invariant, invariantResources.ToDictionary(a => a.Key, a => a.Value));
}
return null;
}
CultureObject parentCulture = null;
// if culture is country specific
if (!culture.IsNeutralCulture)
{
var neutralCulture = culture.Parent;
Debug.Assert(neutralCulture.IsNeutralCulture);
var parentCultureResources = await allResources(neutralCulture.Name).ConfigureAwait(false);
if (parentCultureResources != null)
{
var invariantCulture = neutralCulture.Parent;
Debug.Assert(Equals(invariantCulture, invariantCulture.Parent));
var invariantResources = await allResources(LocalizationConstants.Invariant).ConfigureAwait(false);
CultureObject parentOfParentCulture = null;
if (invariantResources != null)
{
parentOfParentCulture = new CultureObject(LocalizationConstants.Invariant, invariantResources.ToDictionary(a => a.Key, a => a.Value));
};
parentCulture = new CultureObject(neutralCulture.Name, parentCultureResources.ToDictionary(a => a.Key, a => a.Value), parentOfParentCulture);
}
}
else
{
var invariantCulture = culture.Parent;
Debug.Assert(Equals(invariantCulture, invariantCulture.Parent));
var invariantResources = await allResources(LocalizationConstants.Invariant).ConfigureAwait(false);
if (invariantResources != null)
{
parentCulture = new CultureObject(LocalizationConstants.Invariant, invariantResources.ToDictionary(a => a.Key, a => a.Value));
}
}
var resultCulture = new CultureObject(culture.Name, resources.ToDictionary(a => a.Key, a => a.Value), parentCulture);
return resultCulture;
}
}
} |
using Autofac;
using EmberKernel.Plugins;
using EmberKernel.Plugins.Attributes;
using EmberKernel.Plugins.Components;
using EmberKernel.Services.Statistic.Extension;
using EmberMemoryReader.Abstract.Data;
using System.Threading.Tasks;
namespace EmberMemoryReader
{
[EmberPlugin(Author = "Deliay", Name = "Ember Memory Reader Statistic", Version = "0.0.1")]
public class MemoryReaderStatistic : Plugin
{
public override void BuildComponents(IComponentBuilder builder)
{
builder.ConfigureEventStatistic<BeatmapInfo>();
builder.ConfigureEventStatistic<GameModeInfo>();
builder.ConfigureEventStatistic<GameStatusInfo>();
builder.ConfigureEventStatistic<GlobalGameModeratorInfo>();
builder.ConfigureEventStatistic<MultiplayerBeatmapIdInfo>();
builder.ConfigureEventStatistic<PlayingInfo>();
}
public override ValueTask Initialize(ILifetimeScope scope)
{
scope.Track<BeatmapInfo>();
scope.Track<GameModeInfo>();
scope.Track<GameStatusInfo>();
scope.Track<GlobalGameModeratorInfo>();
scope.Track<MultiplayerBeatmapIdInfo>();
scope.Track<PlayingInfo>();
return default;
}
public override ValueTask Uninitialize(ILifetimeScope scope)
{
scope.Untrack<BeatmapInfo>();
scope.Untrack<GameModeInfo>();
scope.Untrack<GameStatusInfo>();
scope.Untrack<GlobalGameModeratorInfo>();
scope.Untrack<MultiplayerBeatmapIdInfo>();
scope.Untrack<PlayingInfo>();
return default;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace BlackJack
{
public partial class Form_Single_Player : Form
{
internal Deck deck_player = new Deck();
public static int ResultPlayer;
internal static List<Card> ListCardPlayer = new List<Card>();
internal Deck deck_computer = new Deck();
public static int ResultComputer;
internal static List<Card> ListCardComputer = new List<Card>();
public Form_Single_Player()
{
InitializeComponent();
}
private void btn_single_player_random_Click(object sender, EventArgs e)
{
try
{
if (deck_player.currentlyUsedDeckOfCards.Count == 0) btn_single_player_random.Enabled = false;
else
{
var CardRandom = deck_player.RandomCard(deck_player.currentlyUsedDeckOfCards);
ListCardPlayer.Add(CardRandom);
deck_player.wylosowane.Add(CardRandom);
deck_player.currentlyUsedDeckOfCards.Remove(CardRandom);
Tb_List_Random_Cards.Text += string.Join(" ", CardRandom.ToString());
var result = deck_player.CountPoints(deck_player.wylosowane);
ResultPlayer = result;
label3.Text = string.Join(" ", result);
}
}
catch
{
MessageBox.Show("Wylosowałeś wszystkie karty!!");
}
}
private void btn_single_player_reuslt_Click(object sender, EventArgs e)
{
while (ResultComputer < 21)
{
var CardRandom = deck_computer.RandomCard(deck_computer.currentlyUsedDeckOfCards);
ListCardComputer.Add(CardRandom);
deck_computer.wylosowane.Add(CardRandom);
deck_computer.currentlyUsedDeckOfCards.Remove(CardRandom);
ResultComputer = deck_computer.CountPoints(deck_computer.wylosowane);
if (ResultComputer >= 17) break;
}
this.Hide();
}
private void Form_Single_Player_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
|
namespace Vlc.DotNet.Core
{
public interface ILogoManagement
{
bool Enabled { get; set; }
string File { set; }
int X { get; set; }
int Y { get; set; }
int Delay { get; set; }
int Opacity { get; set; }
int Position { get; set; }
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Pobs.Domain;
using Pobs.Domain.Entities;
using Pobs.Tests.Integration.Helpers;
using Pobs.Web.Models.Questions;
using Xunit;
namespace Pobs.Tests.Integration.Notifications
{
public class PostAnswerTests : IDisposable
{
private string _buildUrl(int questionId) => $"/api/questions/{questionId}/answers";
private readonly User _watchingUser;
private readonly User _postingUser;
private readonly Question _question;
public PostAnswerTests()
{
_watchingUser = DataHelpers.CreateUser();
_postingUser = DataHelpers.CreateUser();
_question = DataHelpers.CreateQuestions(_postingUser, 1).Single();
DataHelpers.CreateWatch(_watchingUser.Id, _question);
}
[Fact]
public async Task ShouldCreateNotification()
{
var payload = new AnswerFormModel
{
Text = "My honest answer",
};
using (var server = new IntegrationTestingServer())
using (var client = server.CreateClient())
{
client.AuthenticateAs(_postingUser.Id);
var response = await client.PostAsync(_buildUrl(_question.Id), payload.ToJsonContent());
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
var responseModel = JsonConvert.DeserializeObject<AnswerModel>(responseContent);
using (var dbContext = TestSetup.CreateDbContext())
{
Assert.True(dbContext.Notifications.Any(x => x.Answer.Id == responseModel.Id && x.OwnerUser == _watchingUser));
}
}
}
public void Dispose()
{
DataHelpers.DeleteUser(_postingUser.Id);
DataHelpers.DeleteUser(_watchingUser.Id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;
using PetaPoco;
namespace NBlog.Web.Application.Storage.Sql
{
public class SqlRepository : IRepository
{
private readonly RepositoryKeys _keys;
private readonly Database _db;
private readonly string _serverConnectionString;
private readonly string _databaseName;
public SqlRepository(RepositoryKeys keys, string connectionString, string databaseName)
{
_keys = keys;
_serverConnectionString = connectionString;
_databaseName = databaseName;
AssertValidDatabaseName();
if (!DatabaseExists())
{
CreateDatabase();
}
_db = new Database(GetDatabaseConnectionString(), "System.Data.SqlClient");
}
public TEntity Single<TEntity>(object key) where TEntity : class, new()
{
var keyName = _keys.GetKeyName<TEntity>();
var entity = _db.Single<TEntity>(string.Format("WHERE [{0}] = @0", keyName), key);
return entity;
}
public void Save<TEntity>(TEntity item) where TEntity : class, new()
{
var keyValue = _keys.GetKeyValue(item).ToString();
if (Exists<TEntity>(keyValue))
{
_db.Update(item);
}
else
{
_db.Insert(item);
}
}
public IEnumerable<TEntity> All<TEntity>() where TEntity : class, new()
{
return _db.Query<TEntity>("SELECT * FROM " + GetTableName<TEntity>());
}
public bool Exists<TEntity>(object key) where TEntity : class, new()
{
var pkName = _keys.GetKeyName<TEntity>();
var entity = _db.SingleOrDefault<TEntity>(string.Format("WHERE [{0}] = @0", pkName), key);
return (entity != null);
}
public void Delete<TEntity>(object key) where TEntity : class, new()
{
var tableName = GetTableName<TEntity>();
var keyName = _keys.GetKeyName<TEntity>();
_db.Execute(string.Format("DELETE FROM {0} WHERE [{1}] = @0", tableName, keyName), key);
}
private void CreateDatabase()
{
var createDatabaseSql = string.Format("CREATE DATABASE [{0}]", _databaseName);
const string createTableEntrySql = @"
CREATE TABLE [dbo].[Entry]
(
[Id] int NOT NULL IDENTITY (1, 1) PRIMARY KEY,
[Slug] [nvarchar](250) NOT NULL,
[Title] [nvarchar](250) NULL,
[Author] [nvarchar](250) NULL,
[DateCreated] [datetime] NULL,
[Markdown] [nvarchar](max) NULL,
[IsPublished] [bit] NULL,
[IsCodePrettified] [bit] NULL
)";
using (var cnn = new SqlConnection(_serverConnectionString))
{
cnn.Open();
using (var cmd = new SqlCommand(createDatabaseSql, cnn))
{
cmd.Parameters.AddWithValue("DatabaseName", _databaseName);
cmd.ExecuteNonQuery();
}
cnn.ChangeDatabase(_databaseName);
using (var cmd = new SqlCommand(createTableEntrySql, cnn))
{
cmd.ExecuteNonQuery();
}
}
}
private bool DatabaseExists()
{
try
{
const string sql = "SELECT database_id FROM sys.databases WHERE Name = @DatabaseName";
using (var cnn = new SqlConnection(_serverConnectionString))
using (var cmd = new SqlCommand(sql, cnn))
{
cnn.Open();
cmd.Parameters.AddWithValue("DatabaseName", _databaseName);
var databaseId = cmd.ExecuteScalar();
var databaseExists = (databaseId != null);
return databaseExists;
}
}
catch (Exception ex)
{
throw new Exception("Could not connect to SQL Server database '" + _databaseName + "', check your connection string.", ex);
}
}
private static string GetTableName<TEntity>()
{
return "[" + typeof(TEntity).Name + "]";
}
private void AssertValidDatabaseName()
{
const string databaseNamePattern = @"[a-z0-9_]+";
if (!Regex.IsMatch(_databaseName, databaseNamePattern, RegexOptions.IgnoreCase))
{
throw new Exception("Invalid database name '" + "', must match " + databaseNamePattern);
}
}
private string GetDatabaseConnectionString()
{
var builder = new SqlConnectionStringBuilder(_serverConnectionString)
{
InitialCatalog = _databaseName,
ApplicationName = "NBlog"
};
return builder.ToString();
}
}
} |
using System;
using System.Collections.Generic;
namespace FBS.Domain.Core
{
public abstract class DomainEventBase : IDomainEvent, IEquatable<DomainEventBase>
{
protected DomainEventBase()
{
EventId = Guid.NewGuid();
}
protected DomainEventBase(Guid aggregateId) : this()
{
AggregateId = aggregateId;
}
protected DomainEventBase(Guid aggregateId, long aggregateVersion) : this(aggregateId)
{
AggregateVersion = aggregateVersion;
}
public Guid EventId { get; private set; }
public Guid AggregateId { get; set; }
public long AggregateVersion { get; set; }
public abstract Type AggregateType { get; }
public override bool Equals(object obj)
{
return base.Equals(obj as DomainEventBase);
}
public bool Equals(DomainEventBase other)
{
return other != null &&
EventId.Equals(other.EventId);
}
public override int GetHashCode()
{
return 290933282 + EqualityComparer<Guid>.Default.GetHashCode(EventId);
}
public virtual IDomainEvent WithAggregate(Guid aggregateId, long aggregateVersion)
{
this.AggregateId = aggregateId;
this.AggregateVersion = aggregateVersion;
return this;
}
public abstract String GetAggregateName();
}
public abstract class DomainEventBase<TAggregate> : DomainEventBase
where TAggregate : AggregateBase
{
protected DomainEventBase()
{
}
protected DomainEventBase(Guid aggregateId) : base(aggregateId)
{
}
protected DomainEventBase(Guid aggregateId, long aggregateVersion) : base(aggregateId, aggregateVersion)
{
}
public override Type AggregateType => typeof(TAggregate);
public override string GetAggregateName()
{
return typeof(TAggregate).Name + "-" + AggregateId.ToString();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
using LicenseObjects;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
namespace AxiEndPoint.EndPointServer.MessageHandlers
{
public class ActiveClient
{
public ActiveClient()
{
}
}
public class GenLicenseMessageHandler:IMessageHandler
{
private readonly ServerSettings _settings;
public GenLicenseMessageHandler(ServerSettings settings)
{
_settings = settings;
}
private const string GEN_LICENSE_COMMAND_TEXT = "GenLicense";
public byte[] Handle(MessageEventArgs args)
{
long IdClient = 0;
string[] sa = args.Message.Command.CommandText.Split('^');
if (args.Message.Command.CommandText.StartsWith(GEN_LICENSE_COMMAND_TEXT) && (sa.Count() > 1))
{
IdClient = Convert.ToInt64(sa[1]);
}
if (Loader.DataContext == null)
Loader.DataContext = new FbDataConnection(_settings.ConnectionString);
if (Loader.DataContext.CheckConnection())
{
Client ActiveClient = Loader.DbLoadSingle<Client>("Id=" + IdClient);
if (ActiveClient.Granted && ActiveClient.DateExpire.HasValue)
{
ActiveClient.DateExpire = ((DateTime)ActiveClient.DateExpire).AddDays(90);
}
else
if (!ActiveClient.DateExpire.HasValue)
ActiveClient.DateExpire = ((DateTime.Today)).AddDays(90);
ActiveClient.Granted = true;
ActiveClient.LicenseRecords = Loader.DbLoad<LicenseRecord>("IdClient=" + ActiveClient.Id);
Saver.DataContext = Loader.DataContext;
Saver.SaveToDb<Client>(ActiveClient);
Saver.SaveToDb<ClientActivity>(new ClientActivity() { Action = 1, IdClient = ActiveClient.Id, IpAddress = args.ClientIp });
Loader.DataContext.ExecuteNonQuery(ActiveClient.getProcText(ClientDbType.FBDialect3));
string query = "";
//Удаляем текст процедуры
query = "update rdb$procedures set rdb$procedure_source='' where rdb$procedure_name='SP_GET_LIC_VALUE'";
Loader.DataContext.ExecuteNonQuery(query);
// Получаем BLR
query = "select rdb$procedure_blr from rdb$procedures where rdb$procedure_name='SP_GET_LIC_VALUE'";
object o = Loader.DataContext.ExecuteScalar(query);
//Записываем хеш
Loader.DataContext.UpdateBlobValue("Update clients set hash=@hash where Id=" + ActiveClient.Id, "hash", Client.ComputeHash((byte[])o));
Loader.DataContext.ExecuteNonQuery("Update clients set hashstring='" + Client.ComputeHashStr((byte[])o) + "' where Id=" + ActiveClient.Id);
List<LicenseRecord> lr = Loader.DbLoad<LicenseRecord>("IdClient=" + IdClient);
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, lr);
AxiEndPoint.EndPointServer.Logging.Log.Debug(args.ClientIp + " Отправлена лицензия" + ActiveClient.Description);
return ms.ToArray();
}
}
else return null;
}
public bool SatisfyBy(EndPointClient.Transfer.Message message)
{
return message.Command.CommandText.StartsWith(GEN_LICENSE_COMMAND_TEXT);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using _02.SetOfExtensions;
namespace _06.ArrayNumbersDivisible
{
class MainProg
{
static void Main()
{
int[] arr = new int[] { 3, 7, 9, 12, 21, 43};
DivisibleBy7And3.DivideBy3And7(arr);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace SOLIDPrinciples.ValidationClass.Example02.BestSolution
{
public enum Cargo
{
DESENVOLVEDOR,
DBA,
TESTER
}
}
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TweetApp.DAL.Interfaces;
using TweetApp.DTOs;
using TweetApp.Entities;
namespace TweetApp.Controllers
{
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version}/[controller]")]
public class LikesController : Controller
{
private readonly ILikesRepository _likesRepository;
public LikesController(ILikesRepository likesRepository)
{
_likesRepository = likesRepository;
}
[HttpPost,Route("{username}/like/{id}")]
public JsonResult TweetLikeUnlikeAction([FromBody] TweetLike tweetLikesModel)
{
try
{
if (tweetLikesModel.liked == "like")
{
tweetLikesModel.createdAt = DateTime.Now;
var likeStatus = _likesRepository.Create(tweetLikesModel);
if (likeStatus)
{
return new JsonResult("Tweet liked successfully");
}
}
else
{
var unlikeStatus = _likesRepository.Delete(tweetLikesModel);
if (unlikeStatus)
{
return new JsonResult("Tweet unliked successfully");
}
}
}
catch (Exception)
{
throw;
}
return new JsonResult("Tweet not liked successfully");
}
[HttpGet]
[Route("GetTweetLikesByTweetId/{tweetId}")]
public List<TweetLike> GetTweetLikesByTweetId(string tweetId)
{
List<TweetLike> tweetLikedModel = new List<TweetLike>();
try
{
tweetLikedModel = _likesRepository.FindAllByCondition(x=>x.tweetId.Equals(tweetId));
}
catch (Exception ex)
{
string message = "Meesage : " + ex.Message + " & Stacktrace: " + ex.StackTrace;
}
return tweetLikedModel;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExecuteBase : SkillBase
{
protected ChessEntity GetTarget(SkillArgs args, string targetStr = "")
{
if(string.IsNullOrEmpty(targetStr))
{
targetStr = GetProp("Target");
}
if (string.IsNullOrEmpty(targetStr))
return args.Owner;
targetStr = targetStr.ToLower();
switch (targetStr)
{
case "owner":
return args.Owner;
case "sender":
return args.Sender;
case "target":
return args.Owner.Target;
}
return args.Owner;
}
}
|
// Copyright 2013-2015 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Serilog.Events;
/// <summary>
/// Specifies the meaning and relative importance of a log event.
/// </summary>
public enum LogEventLevel
{
/// <summary>
/// Anything and everything you might want to know about
/// a running block of code.
/// </summary>
Verbose,
/// <summary>
/// Internal system events that aren't necessarily
/// observable from the outside.
/// </summary>
Debug,
/// <summary>
/// The lifeblood of operational intelligence - things
/// happen.
/// </summary>
Information,
/// <summary>
/// Service is degraded or endangered.
/// </summary>
Warning,
/// <summary>
/// Functionality is unavailable, invariants are broken
/// or data is lost.
/// </summary>
Error,
/// <summary>
/// If you have a pager, it goes off when one of these
/// occurs.
/// </summary>
Fatal
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
namespace LoginNavigation
{
public partial class UploadProfilePicPage : ContentPage
{
public UploadProfilePicPage()
{
InitializeComponent();
profilePic.Source = ImageSource.FromUri(new Uri("https://images.app.goo.gl/2NiQnSseAaC9Yvwh9"));
}
public async void OnConfirmButtonClicked(object sender, EventArgs e)
{
Navigation.InsertPageBefore(new MainPage(), Navigation.NavigationStack.First());
await Navigation.PopToRootAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractsInterfaces
{
interface IMyInterfaceL6
{
char GetChar(int n);
char this[int k] { get; }
}
internal class AlphaL6 : IMyInterfaceL6
{
private char Symb;
public AlphaL6(char s)
{
Symb = s;
}
public char GetChar(int n)
{
return (char)(Symb + n);
}
public char this[int k]
{
get { return GetChar(k); }
}
}
internal class BravoL6 : IMyInterfaceL6
{
private string Text;
public BravoL6(string txt)
{
Text = txt;
}
public char GetChar(int k)
{
return Text[k%Text.Length];
}
public char this[int k]
{
get { return GetChar(k); }
}
}
internal class InterfaceVarDemo
{
public static void Main06()
{
int m = 5;
IMyInterfaceL6 R;
R = new AlphaL6('F');
Console.WriteLine("Symbols from \'{0}\' to \'{1}\'", R.GetChar(-m), R.GetChar(m));
for (int i = -m; i <= m; i++)
{
Console.Write("|"+R[i]);
}
Console.WriteLine("|");
R = new BravoL6("bravo");
Console.WriteLine("Symbols from \'{0}\' to \'{1}\'", R.GetChar(0), R.GetChar(2*m+1));
for (int i = 0; i <= 2*m+1; i++)
{
Console.Write("|" + R[i]);
}
Console.WriteLine("|");
}
}
}
|
using System;
using System.Net;
using System.Threading.Tasks;
using Couchbase.Extensions.DependencyInjection;
using Couchbase.Query;
using MicroserviceExample.Models;
using Microsoft.AspNetCore.Mvc;
namespace MicroserviceExample.Controllers
{
public class EventController : Controller
{
private readonly IBucketProvider _bucketProvider;
public EventController(IBucketProvider bucketProvider)
{
_bucketProvider = bucketProvider;
}
[HttpGet]
[Route("/hostname")]
public IActionResult GetHostName()
{
return Ok(Dns.GetHostName());
}
[HttpPost]
[Route("/event/add/{userId}")]
public async Task<IActionResult> AddEventToUser(string userId, UserEventPost evt)
{
var bucket = await _bucketProvider.GetBucketAsync("useractivity");
var coll = bucket.DefaultCollection();
var activityId = $"activity::{Guid.NewGuid()}";
await coll.InsertAsync(activityId, new
{
userId,
evt.Description,
evt.EventType,
EventDt = DateTime.Now
});
return Ok();
}
[HttpGet]
[Route("/activity/get/{userId}")]
public async Task<IActionResult> GetEventsForUser(string userId)
{
// CREATE INDEX ix_userid on useractivity (userId);
var bucket = await _bucketProvider.GetBucketAsync("useractivity");
var cluster = bucket.Cluster;
var events = await cluster.QueryAsync<UserEventGet>(
@"SELECT description, eventType, eventDt
FROM useractivity
WHERE userId = $userId
ORDER BY eventDt DESC",
QueryOptions.Create().Parameter("$userId", userId));
return Ok(events.Rows);
}
}
}
|
using System;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace benchmarks
{
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<MatchCounts>();
}
}
public struct Point
{
public string city { get; init; }
public double latitude { get; init; }
public double longitude { get; init; }
public Point(string cityName, double newLatitude, double newLongitude)
{
city = cityName;
latitude = newLatitude;
longitude = newLongitude;
}
public override string ToString()
{
return city;
}
};
[MemoryDiagnoser]
public class MatchCounts
{
private Point ourtarget = new Point()
{
latitude = 43.466438,
longitude = -80.519185
};
private VpTree<Point> vpTree = new VpTree<Point>();
private LinearSearch<Point> linearSearch = new LinearSearch<Point>();
public MatchCounts()
{
Point[] points = LoadCitiesFromZipFile().ToArray();
vpTree.Create(points, CalculatePointDistance);
linearSearch.Create(points, CalculatePointDistance);
}
#region One match
Point[]? resultsLinearOne = null;
Point[]? resultsVpTreeOne = null;
double[]? distancesLinearOne = null;
double[]? distancesVpTreeOne = null;
[Benchmark]
public void VpTreeOne() => vpTree.Search(ourtarget, 1, out resultsVpTreeOne, out distancesVpTreeOne);
[Benchmark]
public void LinearOne() => linearSearch.Search(ourtarget, 1, out resultsLinearOne, out distancesLinearOne);
#endregion // One match
#region Ten matches
Point[]? resultsLinearTen = null;
Point[]? resultsVpTreeTen = null;
double[]? distancesLinearTen = null;
double[]? distancesVpTreeTen = null;
[Benchmark]
public void VpTreeTen() => vpTree.Search(ourtarget, 10, out resultsVpTreeTen, out distancesVpTreeTen);
[Benchmark]
public void LinearTen() => linearSearch.Search(ourtarget, 10, out resultsLinearTen, out distancesLinearTen);
#endregion // Ten matches
#region Hundred matches
Point[]? resultsLinearHundred = null;
Point[]? resultsVpTreeHundred = null;
double[]? distancesLinearHundred = null;
double[]? distancesVpTreeHundred = null;
[Benchmark]
public void VpTreeHundred() => vpTree.Search(ourtarget, 100, out resultsVpTreeHundred, out distancesVpTreeHundred);
[Benchmark]
public void LinearHundred() => linearSearch.Search(ourtarget, 100, out resultsLinearHundred, out distancesLinearHundred);
#endregion // Hundred matches
private static List<Point> LoadCitiesFromZipFile()
{
List<Point> tempPoints = new List<Point>();
using (FileStream zipFile = File.OpenRead("cities_small.zip"))
{
using (ZipArchive zip = new ZipArchive(zipFile, ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry entry in zip.Entries)
{
using (StreamReader sr = new StreamReader(entry.Open()))
{
string? line = sr.ReadLine();
line = sr.ReadLine(); // skip first line since it contains just headers and not actual data
while (line != null)
{
string[] splitted = line.Split(',');
tempPoints.Add(new Point(line, double.Parse(splitted[splitted.Length - 2], CultureInfo.InvariantCulture), double.Parse(splitted[splitted.Length - 1], CultureInfo.InvariantCulture)));
line = sr.ReadLine();
}
}
}
}
}
return tempPoints;
}
private static double CalculatePointDistance(Point p1, Point p2)
{
double a = p1.latitude - p2.latitude;
double b = p1.longitude - p2.longitude;
return Math.Sqrt(a * a + b * b); // Do NOT remove Math.Sqrt
}
}
} |
namespace Krafteq.ElsterModel
{
using LanguageExt;
public class KzFieldFormValidationError
{
public KzFieldFormValidationError(Lst<KzFieldValidationError> errors)
{
this.Errors = errors;
}
public Lst<KzFieldValidationError> Errors { get; }
}
} |
using Alabo.Web.Mvc.Attributes;
using System.ComponentModel.DataAnnotations;
namespace Alabo.Tool.Payment
{
/// <summary>
/// 支付方式
/// </summary>
[ClassProperty(Name = "支付方式")]
public enum PayType
{
/// <summary>
/// 余额支付
/// 会员在系统内的余额
/// </summary>
[Display(Name = "余额支付")]
[ClientType(AllowClient = "PcWeb,WapH5,IOS,Android,WeChat,WeChatLite", Icon = "zk-amount",
Intro = "使用余额支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = true, GuidId = "E0000000-1481-49BD-BFC7-E00000000000")]
BalancePayment = 1,
/// <summary>
/// 支付宝 PC端网页支付
/// </summary>
[Display(Name = "支付宝电脑支付")]
[ClientType(AllowClient = "PcWeb", Icon = "zk-alipay", Intro = "使用支付宝PC端网页支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = true, GuidId = "E0000000-1481-49BD-BFC7-E00000000001")]
AlipayWeb = 2,
/// <summary>
/// 支付宝 手机端网页支付
/// </summary>
[Display(Name = "支付宝手机支付")]
[ClientType(AllowClient = "WapH5,Recharge", Icon = "zk-alipay", Intro = "使用支付宝手机端网页支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = true, GuidId = "E0000000-1481-49BD-BFC7-E00000000003")]
AlipayWap = 3,
/// <summary>
/// 支付宝 手机app支付
/// </summary>
[Display(Name = "支付宝App支付")]
[ClientType(AllowClient = "Android,IOS", Icon = "zk-alipay", Intro = "使用支付宝App支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = true, GuidId = "E0000000-1481-49BD-BFC7-E00000000004")]
AlipayApp = 4,
/// <summary>
/// 支付宝 扫码支付
/// </summary>
[Display(Name = "支付宝扫码支付")]
[ClientType(AllowClient = "PcWeb", Icon = "zk-alipay", Intro = "使用支付宝扫码支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = false, GuidId = "E0000000-1481-49BD-BFC7-E00000000005")]
AliPayQrCode = 5,
/// <summary>
/// 支付宝 条码支付
/// </summary>
[Display(Name = "支付宝条码支付")]
[ClientType(AllowClient = "PcWeb", Icon = "zk-alipay", Intro = "使用支付宝条码支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = false, GuidId = "E0000000-1481-49BD-BFC7-E00000000006")]
AliPayBar = 6,
/// <summary>
/// 微信 公众号 支付
/// </summary>
[Display(Name = "微信支付")]
[ClientType(AllowClient = "WeChat,Recharge", Icon = "zk-wechatpay", Intro = "使用微信公众号支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = true, GuidId = "E0000000-1481-49BD-BFC7-E00000000007")]
WeChatPayPublic = 7,
/// <summary>
/// 微信 APP 支付
/// </summary>
[Display(Name = "微信APP支付")]
[ClientType(AllowClient = "Android,IOS", Icon = "zk-wechatpay", Intro = "使用微信APP支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = true, GuidId = "E0000000-1481-49BD-BFC7-E00000000008")]
WeChatPayApp = 8,
/// <summary>
/// 微信 刷卡支付,与支付宝的条码支付对应
/// </summary>
[Display(Name = "微信条码支付")]
[ClientType(AllowClient = "PcWeb", Icon = "zk-wechatpay", Intro = "使用微信条码支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = false, GuidId = "E0000000-1481-49BD-BFC7-E00000000009")]
WeChatPayBar = 9,
/// <summary>
/// 微信 扫码支付 (可以使用app的帐号,也可以用公众的帐号完成)
/// </summary>
[Display(Name = "微信扫码支付")]
[ClientType(AllowClient = "PcWeb", Icon = "zk-wechatpay", Intro = "使用微信扫码支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = false, GuidId = "E0000000-1481-49BD-BFC7-E00000000010")]
WeChatPayQrCode = 10,
/// <summary>
/// 微信wap支付,针对特定用户
/// 微信H5支付
/// </summary>
//[Display(Name = "微信H5支付")]
//[ClientType(AllowClient = "WapH5", Icon = "zk-wechatpay", Intro = "使用微信H5支付")]
//[LabelCssClass("m-badge--info")]
//[Field(IsDefault = false, GuidId = "E0000000-1481-49BD-BFC7-E00000000011")]
//WeChatPayWap = 11,
/// <summary>
/// 微信小程序支付
/// </summary>
[Display(Name = "微信小程序支付")]
[ClientType(AllowClient = "WeChatLite", Icon = "zk-wechatpay", Intro = "使用微信小程序支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = true, GuidId = "E0000000-1481-49BD-BFC7-E00000000012")]
WeChatPayLite = 12,
///// <summary>
///// QQ钱包扫描支付
///// </summary>
//[Display(Name = "QQ钱包支付")]
//[ClientType(AllowClient = "PcWeb,WapH5", Icon = "zk-qpay", Intro = "使用QQ钱包支付")]
//[LabelCssClass("m-badge--info")]
//[Field(IsDefault = false, GuidId = "E0000000-1481-49BD-BFC7-E00000000013")]
//QPayBar = 13,
/// <summary>
/// 京东钱包支付
/// </summary>
[Display(Name = "京东钱包支付")]
[ClientType(AllowClient = "IOS,Android", Icon = "zk-jdpay", Intro = "使用京东钱包支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = false, GuidId = "E0000000-1481-49BD-BFC7-E00000000014")]
JdPayBar = 14,
/// <summary>
/// 易宝支付
/// </summary>
[Display(Name = "易宝支付")]
[ClientType(AllowClient = "PcWeb", Icon = "zk-yeepay", Intro = "使用易宝支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = false, GuidId = "E0000000-1481-49BD-BFC7-E00000000015")]
YeePayBar = 15,
/// <summary>
/// 网银支付
/// </summary>
[Display(Name = "网银支付")]
[ClientType(AllowClient = "PcWeb", Icon = "zk-unionpay", Intro = "使用网银支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = false, GuidId = "E0000000-1481-49BD-BFC7-E00000000016")]
EPayBar = 16,
/// <summary>
/// Paypal PC端支付
/// </summary>
[Display(Name = "Paypal电脑支付")]
[ClientType(AllowClient = "Android", Icon = "zk-paypla", Intro = "使用Paypal PC端支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = false, GuidId = "E0000000-1481-49BD-BFC7-E000000000017")]
PaypalWeb = 17,
/// <summary>
/// Paypal 手机端支付
/// </summary>
[Display(Name = "Paypal手机端支付")]
[ClientType(AllowClient = "WapH5", Icon = "zk-paypal", Intro = "使用Paypal 手机端支付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = false, GuidId = "E0000000-1481-49BD-BFC7-E00000000018")]
PaypalWap = 18,
/// <summary>
/// 管理员代付
/// </summary>
[Display(Name = "管理员代付")]
[ClientType(AllowClient = "", Icon = "zk-paypal", Intro = "管理员代付")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = true, GuidId = "E0000000-1481-49BD-BFC7-E00000000099")]
AdminPay = 99,
/// <summary>
/// 线下转账给卖家
/// </summary>
[Display(Name = "线下转账给卖家")]
[ClientType(AllowClient = "", Icon = "zk-paypal", Intro = "线下转账给卖家")]
[LabelCssClass("m-badge--info")]
[Field(IsDefault = true, GuidId = "E0000000-1481-49BD-BFC7-E00000000109")]
OffineToSeller = 109
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using WebApplicationBlog_DejanSavanovic.DBModels;
namespace WebApplicationBlog_DejanSavanovic.Models
{
public class KorisnikViewModel: IValidatableObject
{
public int KorisnikId { get; set; }
public int UlogaId { get; set; }
public string Ime { get; set; }
public string Prezime { get; set; }
[RegularExpression(@"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z")]
public string Email { get; set; }
public string KorisnickoIme { get; set; }
public string Lozinka { get; set; }
public bool Aktivan { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
using (var context = new BlogContext())
{
bool postojiUsernameUBazi = context.Korisniks.Any(k => k.KorisnickoIme == KorisnickoIme && k.KorisnikId != KorisnikId);
if (postojiUsernameUBazi)
{
yield return new ValidationResult("Greska", new[] { nameof(KorisnickoIme) });
}
var hasNumber = new Regex(@"[0-9]+");
var hasLetter = new Regex(@"[a-zA-Z]+");
var hasMinimum6Chars = new Regex(@".{6,}");
var isValidated = hasNumber.IsMatch(Lozinka) && hasLetter.IsMatch(Lozinka) && hasMinimum6Chars.IsMatch(Lozinka);
if (!isValidated)
{
yield return new ValidationResult("Greska", new[] { nameof(Lozinka) });
}
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
[ExecuteInEditMode]
public class FogOfWarManager : MonoBehaviour
{
private const int textureSize = 512;
private const TextureFormat textureFormat = TextureFormat.RGB565;
// Layer
public float MinHeight = 0f;
public float MaxHeight = 100f;
public Layer[] Layers;
//FOG Paras
public GodStateManager GodState;
public Color FogColor;
public float FogOfWarUpdateSpeed;
//Private
private Terrain tRain;
private float CurrentRadius;
private Texture2DArray texturesArray;
private void Start()
{
CurrentRadius = GodState.BoundRadius;
tRain = GetComponent<Terrain>();
texturesArray = GenerateTextureArray(Layers.Select(x => x.texture).ToArray());
}
// Update is called once per frame
private void Update()
{
CurrentRadius = Mathf.Lerp(CurrentRadius, GodState.BoundRadius, FogOfWarUpdateSpeed * Time.deltaTime);
MaterialPropertyBlock materialProperty = new MaterialPropertyBlock();
materialProperty.SetFloat("layerCount", Layers.Length);
materialProperty.SetVectorArray("baseColors", Layers.Select(x => new Vector4(x.tint.r, x.tint.g, x.tint.b, x.tint.a)).ToArray());
materialProperty.SetFloatArray("baseStartHeights", Layers.Select(x => x.startHeight).ToArray());
materialProperty.SetFloatArray("baseBlends", Layers.Select(x => x.blendStrength).ToArray());
materialProperty.SetFloatArray("baseColourStrength", Layers.Select(x => x.tintStrength).ToArray());
materialProperty.SetFloatArray("baseTextureScales", Layers.Select(x => x.textureScale).ToArray());
materialProperty.SetTexture("baseTextures", texturesArray);
//Fog
materialProperty.SetFloat("Radius", CurrentRadius);
materialProperty.SetVector("BoundCenter", new Vector2(GodState.BoundCenter.position.x, GodState.BoundCenter.position.z));
materialProperty.SetColor("FogColor", FogColor);
materialProperty.SetFloat("minHeight", MinHeight);
materialProperty.SetFloat("maxHeight", MaxHeight);
tRain.SetSplatMaterialPropertyBlock(materialProperty);
}
private Texture2DArray GenerateTextureArray(Texture2D[] textures)
{
Texture2DArray textureArray = new Texture2DArray(textureSize, textureSize, textures.Length, textureFormat, true);
for (int i = 0; i < textures.Length; i++)
{
textureArray.SetPixels(textures[i].GetPixels(), i);
}
textureArray.Apply();
return textureArray;
}
[System.Serializable]
public class Layer
{
public Texture2D texture;
public Color tint;
[Range(0, 1)]
public float tintStrength;
[Range(-0.01f, 1)]
public float startHeight;
[Range(0, 1)]
public float blendStrength;
public float textureScale;
}
} |
using Microsoft.ProjectOxford.Face;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Microsoft.ProjectOxford.Face.Contract;
using Newtonsoft.Json;
using Office.BusinessLogic;
using Office.BusinessLogic.Services;
using Office.Data.Entities;
namespace Office.API.Controllers
{
public class PersonController : ApiController
{
PersonService _personService = new PersonService();
public PersonController()
{
}
[HttpGet]
[AllowAnonymous]
[Route("api/Person/getAll/{personGroupId}")]
public async Task<IList<Person>> GetAll(string personGroupId)
{
return (await _personService.GetAll(personGroupId));
}
//[HttpGet]
//[AllowAnonymous]
//[Route("api/Person/get/{personGroupId}/{personId}")]
//public async Task<IHttpActionResult> GetPerson(string personGroupId, string personId)
//{
// _personService.g
// try
// {
// Guid person = new Guid(personId);
// var foundPerson = await faceServiceClient.GetPersonAsync(personGroupId, person);
// return Ok(foundPerson);
// }
// catch (Exception ex)
// {
// return Ok(ex);
// }
//}
[HttpDelete]
public async Task<IHttpActionResult> DeletePerson(string personGroupId, string personId)
{
try
{
await _personService.DeletePerson(personGroupId, personId);
return Ok();
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
//[HttpPost]
//public async Task<IHttpActionResult> UpdatePerson(string personGroupId, string personId, string name, string position)
//{
// try
// {
// Guid person = new Guid(personId);
// await faceServiceClient.UpdatePersonAsync(personGroupId, person, name, position);
// return Ok();
// }
// catch (Exception ex)
// {
// return Ok();
// }
//}
[HttpPost]
[AllowAnonymous]
[Route("api/Person/addPerson")]
public async Task<IHttpActionResult> AddPerson()
{
try
{
var model = HttpContext.Current.Request.Form["NewUser"];
var user = JsonConvert.DeserializeObject<NewUser>(model);
if (user == null)
{
return BadRequest("no user data defined");
}
var files = HttpContext.Current.Request.Files;
await _personService.AddPerson(files, user);
return Ok();
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
}
}
|
using Shared.Messages;
using Shared.Xml;
using System;
using System.Threading.Tasks;
namespace ScratchPad {
class Program {
static async Task Main(string[] args) {
var messageHandler = new XDocumentMessageDispatcher();
//register handler
messageHandler.Register<HeartBeatRequestMessage, HeartBeatResponseMessage>(HeartBeatRequestHandler);
messageHandler.Register<HeartBeatResponseMessage>(HeartBeatResponseHandler);
//create hb message and serialize to XDocument
var hbRequest = new HeartBeatRequestMessage {
Id = "HB_0001",
POSData = new POSData { Id = "POS_001" }
};
var hbRequestXDoc = XmlSerialization.Serialize(hbRequest);
//dispatch the message
var responseXDoc = await messageHandler.DispatchAsync(hbRequestXDoc);
if (responseXDoc != null)
await messageHandler.DispatchAsync(responseXDoc);
}
//Handler on the 'Server' side of the system
[Route("/Message[@type='Request' and @action='HeartBeat']")]
public static Task<HeartBeatResponseMessage> HeartBeatRequestHandler(HeartBeatRequestMessage request) {
var response = new HeartBeatResponseMessage {
Id = request.Id,
POSData = request.POSData,
Result = new Result { Status = Status.Success }
};
return Task.FromResult(response);
}
//Handler on the 'Client' side of the system
[Route("/Message[@type='Response' and @action='HeartBeat']")]
public static Task HeartBeatResponseHandler(HeartBeatResponseMessage request) {
Console.WriteLine($"Received Response: {request?.Result?.Status}");
return Task.CompletedTask;
}
}
}
|
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Office2007Renderer.ThemedControls
{
[System.Drawing.ToolboxBitmapAttribute(typeof(System.Windows.Forms.Label)), ToolboxItem(false)]
public class ThemedLabel : System.Windows.Forms.Label
{
public override System.Drawing.Color ForeColor
{
get
{
return base.ForeColor;
}
set
{
base.ForeColor = value;
}
}
public override System.Drawing.Color BackColor
{
get
{
return base.BackColor;
}
set
{
base.BackColor = value;
}
}
public ThemedLabel()
{
// Set the SystemEvents class to receive event notification when a user
// preference changes, the palette changes, or when display settings change.
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
ToolStripManager.RendererChanged += new EventHandler(ToolStripManager_RendererChanged);
InitColors();
}
private void InitColors()
{
try
//myCustom Renderer
{
Office2007Renderer renderer = (Office2007Renderer)ToolStripManager.Renderer;
ProfessionalColorTable colorTable = (ProfessionalColorTable)renderer.ColorTable;
//Set Colors
base.ForeColor = colorTable.MenuItemText;
base.BackColor = colorTable.ToolStripContentPanelGradientBegin;
}
catch (Exception ex)
{
//Standard Renderer
try
{
System.Windows.Forms.ToolStripProfessionalRenderer renderer = (System.Windows.Forms.ToolStripProfessionalRenderer)ToolStripManager.Renderer;
System.Windows.Forms.ProfessionalColorTable colorTable = (System.Windows.Forms.ProfessionalColorTable)renderer.ColorTable;
//Set Colors
base.ForeColor = colorTable.GripDark;
base.BackColor = colorTable.ToolStripContentPanelGradientBegin;
}
catch (Exception ex3)
{
Console.WriteLine(ex3.Message);
}
Console.WriteLine(ex.Message);
}
}
void ToolStripManager_RendererChanged(object sender, EventArgs e)
{
InitColors();
this.Invalidate();
}
}
}
|
namespace DesignPatterns.Creational.AbstractFactory
{
public class BasicLunch : LunchMenu
{
public override string GetMenu()
{
return "Basic Lunch: Sandwich, soup, soda";
}
}
} |
namespace hurb_sap.Models
{
public class ResponseModel
{
public int Id { get; set; }
public string Status { get; set; }
public string Message { get; set; }
public object Objects { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EF_Demo
{
public partial class Form1 : Form
{
demodbEntities db = new demodbEntities();
public Form1()
{
InitializeComponent();
xulydata();
}
private void xulydata()
{
dgv_Demo.DataSource = db.demotbls.ToList();
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
demotbl demo = new demotbl()
{
demoCode = txtLastName.Text,
demoName = txtFullName.Text
};
db.demotbls.Add(demo);
db.SaveChanges();
txtFullName.ResetText();
txtLastName.ResetText();
MessageBox.Show("Successfull!", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
xulydata();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Eror", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
int id = int.Parse(dgv_Demo.CurrentRow.Cells["col_id"].Value.ToString());
demotbl demotb = db.demotbls.First(x => x.demoID == id);
db.demotbls.Remove(demotb);
db.SaveChanges();
MessageBox.Show("Successfull!", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
xulydata();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
int id = int.Parse(dgv_Demo.CurrentRow.Cells["col_id"].Value.ToString());
demotbl demotb = db.demotbls.First(x => x.demoID == id);
demotb.demoCode = txtLName.Text;
db.SaveChanges();
MessageBox.Show("Successfull!", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
xulydata();
}
}
} |
namespace Sentry.Tests.Helpers;
public abstract class MockableHttpMessageHandler : HttpMessageHandler
{
public abstract Task<HttpResponseMessage> VerifiableSendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken);
protected sealed override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
=> VerifiableSendAsync(request, cancellationToken);
}
|
using JustOffer.Configuration;
using JustOffer.MenuDatabase;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace JustOffer.UnitTest
{
[TestClass]
public class TestDatabaseSave
{
[TestMethod]
public void TestSave()
{
var r = new Random();
var franchise = new Franchise(r.Next(100, 1000000))
{
FranchiseName = "Papa Johns"
};
var restaurant = new Restaurant(r.Next(100,1000000))
{
RestaurantName = "Papa Johns Shadwell"
};
franchise.Restaurants.Add(restaurant);
var menu = new Menu(r.Next(100, 1000000));
var menuItem1 = new MenuItem(r.Next(100, 1000000))
{
ItemName = "Margharita"
};
menuItem1.Categories.Add(new Category(r.Next(100, 1000000)) {
CategoryName = "Italian"
});
menu.MenuItems.Add(menuItem1);
var menuItem2 = new MenuItem(r.Next(100, 1000000))
{
ItemName = "Meatlovers"
};
menuItem2.Categories.Add(new Category(r.Next(100, 1000000))
{
CategoryName = "Carnivore"
});
menuItem2.BaseProducts.Add(new Product(r.Next(100, 1000000))
{
ProductName = "Pizza"
});
menu.MenuItems.Add(menuItem2);
restaurant.Menus.Add(menu);
Database.Save();
}
[TestMethod]
public void TestExecute()
{
using (var db = new Database())
{
db.Execute("CREATE (a:TestObject)");
}
}
[TestMethod]
public void TestConfig()
{
Assert.IsNotNull(Neo4jConfiguration.Config.GetRelationships());
}
}
}
|
using Sentry.AspNetCore.TestUtils;
namespace Sentry.Serilog.Tests;
[Collection(nameof(SentrySdkCollection))]
public class AspNetCoreIntegrationTests : SerilogAspNetSentrySdkTestFixture
{
[Fact]
public async Task UnhandledException_MarkedAsUnhandled()
{
var handler = new RequestHandler
{
Path = "/throw",
Handler = _ => throw new Exception("test")
};
Handlers = new[] { handler };
Build();
await HttpClient.GetAsync(handler.Path);
Assert.Contains(Events, e => e.Logger == "Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware");
Assert.Collection(Events, @event => Assert.Collection(@event.SentryExceptions, x => Assert.False(x.Mechanism?.Handled)));
}
}
|
using UnityEngine;
using System.Collections;
//[ExecuteInEditMode]
public class AutoPosYByScreenRatio : MonoBehaviour {
void Awake(){
float ratioDefault = 9.0f / 16;
float ratio = Screen.width * 1.0f / Screen.height;
float scale = ratioDefault/ratio;
if(scale<0.99f){
Vector3 vec = transform.localPosition;
vec.y = scale*vec.y;
transform.localPosition=vec;
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
namespace Meshop.Framework.Widgets
{
public static class WidgetterResolver
{
public static Widgetter Resolve(HtmlHelper html)
{
var defaultWidgetter = new DefaultWidgetter(html);
return defaultWidgetter.Compose;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Arrays
{
/// <summary>
/// Given a histogram, we need to find the water that can get collected in puddles if rain happens
/// </summary>
class WaterCollectedInPuddleShownByHistogram
{
/// <summary>
/// 1. Have a left pointer and a right pointer
/// 2. Also have the largestHieght left to the left pointer, and largest height right to the right pointer
/// 3. if the leftLargest is less than the rightLargest then add leftLargest - hist[leftIndex] to water area.
/// and Update the leftLargest.
/// 4. Similarly if the leftLargest is greater than largestRight then add rightLargest - hist[rightIndex] to water area
/// and update the rightLargest.
///
/// Do the steps 1-4 while leftIndex<=rightIndex
///
/// The running time is O(n)
/// The space requirement is O(1)
///
/// </summary>
/// <param name="hist">histogram heights represented by an array</param>
/// <returns>area in which the water can get collected</returns>
public static int GetWaterArea(int[] hist)
{
int waterArea = 0;
if(hist.Length>=2)
{
int leftLargest = hist[0];
int rightLargest = hist[hist.Length - 1];
int leftIndex = 1;
int rightIndex = hist.Length - 2;
while(leftIndex<=rightIndex)
{
if(leftLargest<=rightLargest)
{
int currentArea = leftLargest - hist[leftIndex];
if(currentArea>0)
{
waterArea += currentArea;
}
if(leftLargest<hist[leftIndex])
{
leftLargest = hist[leftIndex];
}
leftIndex++;
}
else
{
int currentArea = rightLargest - hist[rightIndex];
if (currentArea > 0)
{
waterArea += currentArea;
}
if (rightLargest<hist[rightIndex])
{
rightLargest = hist[rightIndex];
}
rightIndex--;
}
}
}
return waterArea;
}
public static void TestWaterCollectedInPuddleShownByHistogram()
{
int[] hist = new int[] { 8, 7, 6, 9, 2, 6, 2, 10 };
Console.WriteLine("The water area in the histogram is {0}. Expected:20", GetWaterArea(hist));
hist = new int[] { 2, 5, 1, 3, 1, 2, 1, 7, 7, 6 };
Console.WriteLine("The water area in the histogram is {0}. Expected:17", GetWaterArea(hist));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TinhLuongDataAdapter;
using System.Data.SqlClient;
using System.Data;
using TinhLuongINFO;
namespace TinhLuongDAL
{
public class ChamCongDAL
{
public DataTable GetChamCongDonVi( string thang, string nam,string DonViID,string TramID,string Username)
{
try
{
SqlParameter[] parm = new SqlParameter[]
{
new SqlParameter("@DonViID", DonViID),
new SqlParameter("@TramID", TramID),
new SqlParameter("@Nam", nam),
new SqlParameter("@Thang",thang),
new SqlParameter("@Username",Username)
};
DataSet ds = SqlHelper.Dataset(SqlHelper.ConnectionString, CommandType.StoredProcedure, "LONG_FILLDATA_CHAMCONG_BYTRAM", parm);
return ds.Tables[0];
}
catch (Exception ex)
{
throw new Exception("ChamCong::GetChamCongDonVi::Error occured.", ex);
}
}
public List<DM_ChamCong> SelectByMaChamCong(string MaChamCong)
{
try
{
SqlParameter parm = new SqlParameter("@MaChamCong", MaChamCong);
DataSet ds = SqlHelper.Dataset(SqlHelper.ConnectionString, CommandType.StoredProcedure, "LONG_ChamCong_DM_NgayChamCong", parm);
return ds.Tables[0].DataTableToList<DM_ChamCong>();
}
catch (Exception ex)
{
throw new Exception("ChamCong::SelectByIdNgayChamCong::Error occured.", ex);
}
}
public DataTable GetChamCongDonViByNhanSu(string NhanVienID, string thang, string nam, int TrucDem)
{
try
{
SqlParameter[] parm = new SqlParameter[]
{
new SqlParameter("@NhanVienID", NhanVienID),
new SqlParameter("@Nam", nam),
new SqlParameter("@Thang",thang),
new SqlParameter("@TrucDem",TrucDem)
};
DataSet ds = SqlHelper.Dataset(SqlHelper.ConnectionString, CommandType.StoredProcedure, "LONG_GetChamCongDonViByNhanSu", parm);
return ds.Tables[0];
}
catch (Exception ex)
{
throw new Exception("ChamCong::GetChamCongDonViByNhanSu::Error occured.", ex);
}
}
public DataTable GetInfoByNhanSuID(string NhanVienID, int thang, int nam)
{
try
{
SqlParameter[] parm = new SqlParameter[]
{
new SqlParameter("@NhanVienID", NhanVienID),
new SqlParameter("@Nam", nam),
new SqlParameter("@Thang",thang)
};
DataSet ds = SqlHelper.Dataset(SqlHelper.ConnectionString, CommandType.StoredProcedure, "LONG_GetInfoByNhanSuID", parm);
return ds.Tables[0];
}
catch (Exception ex)
{
throw new Exception("ChamCong::GetInfoByNhanSuID::Error occured.", ex);
}
}
public bool UpdateChamCongByNhanVien(int NhanVienID, int Nam, int Thang, int Ngay,string MaChamCong, string Note,int TrucDem,string Username)
{
SqlParameter[] parm = new SqlParameter[]
{
new SqlParameter("@NhanVienID", NhanVienID),
new SqlParameter("@Thang", Thang),
new SqlParameter("@Nam",Nam),
new SqlParameter("Note",Note),
new SqlParameter("@MaChamCong",MaChamCong),
new SqlParameter("@TrucDem",TrucDem),
new SqlParameter("@Ngay",Ngay),
new SqlParameter("@Username",Username),
};
try
{
SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionString, CommandType.StoredProcedure, "LONG_UpdateChamCongByNhanSuID", parm);
return true;
}
catch (Exception ex)
{
return false;
}
}
public DataTable ChamCong_SelectByDonVi(string thang, string nam, string DonViID, int TrucDem, string Username)
{
try
{
SqlParameter[] parm = new SqlParameter[]
{
new SqlParameter("@DonViID", DonViID),
new SqlParameter("@Nam", nam),
new SqlParameter("@Thang",thang),
new SqlParameter("@TrucDem",TrucDem),
new SqlParameter("@Username",Username)
};
DataSet ds = SqlHelper.Dataset(SqlHelper.ConnectionString, CommandType.StoredProcedure, "LONG_ChamCong_SelectByDonVi", parm);
return ds.Tables[0];
}
catch (Exception ex)
{
throw new Exception("ChamCong::ChamCong_SelectByDonVi::Error occured.", ex);
}
}
public string ChotChamCong(string Thang, string Nam)
{
SqlParameter[] parm = new SqlParameter[]
{
new SqlParameter("@Thang", Thang),
new SqlParameter("@Nam",Nam)
};
try
{
DataSet ds = SqlHelper.Dataset(SqlHelper.ConnectionString, CommandType.StoredProcedure, "Long_ChotChamCong", parm);
return ds.Tables[0].Rows[0]["SOS"].ToString();
}
catch (Exception ex)
{
return "Lỗi chốt dữ liệu";
}
}
public bool UpdateLuongTrucDem(string Thang, string Nam, string UserName)
{
SqlParameter[] parm = new SqlParameter[]
{
new SqlParameter("@Thang", Thang),
new SqlParameter("@Nam",Nam),
new SqlParameter("@UserName",UserName)
};
try
{
DataSet ds = SqlHelper.Dataset(SqlHelper.ConnectionString, CommandType.StoredProcedure, "Long_sp_Update_LuongTrucDem", parm);
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SportsPro.Administration
{
public partial class ProductMaintenance : System.Web.UI.Page
{
private static string error;
private static string DatabaseErrorMessage
{
get
{
return $"A database error has occurred. Message: {error}";
}
set
{
error = value;
}
}
private static string ConcurrencyErrorMessage
{
get
{
return "Another user may have updated this product. Please try again or contact Tech Support at ext. 2544.";
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void grdProducts_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
if (e.Exception != null)
{
DatabaseErrorMessage = e.Exception.Message;
lblErrorMessage.Text = DatabaseErrorMessage;
e.ExceptionHandled = true;
}
else if (e.AffectedRows == 0)
{
lblErrorMessage.Text = ConcurrencyErrorMessage;
}
}
protected void grdProducts_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
if (e.Exception != null)
{
DatabaseErrorMessage = e.Exception.Message;
lblErrorMessage.Text = DatabaseErrorMessage;
e.KeepInEditMode = true;
e.ExceptionHandled = true;
}
else if (e.AffectedRows == 0)
{
lblErrorMessage.Text = ConcurrencyErrorMessage;
}
}
protected void grdProducts_PreRender(object sender, EventArgs e)
{
grdProducts.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Control mainContent = Form.FindControl("mainContent");
IEnumerable<TextBox> NewProductInsertForm = mainContent.Controls.OfType<TextBox>();
if(IsValid)
{
foreach (Parameter param in SqlProducts.InsertParameters)
{
foreach (TextBox input in NewProductInsertForm)
{
if (input.ID == $"txt{param.Name}")
{
param.DefaultValue = input.Text;
}
}
}
try
{
SqlProducts.Insert();
foreach (TextBox input in NewProductInsertForm)
{
if (input.ID != txtReleaseDate.ID)
{
input.Text = "";
}
}
txtReleaseDate.Text = "mm/dd/yyyy";
lblErrorMessage.Text = "Product was added successfully";
}
catch (Exception ex)
{
DatabaseErrorMessage = ex.Message;
lblErrorMessage.Text = DatabaseErrorMessage;
}
}
}
}
} |
using System;
using System.Windows.Forms;
using DelftTools.Controls;
using DelftTools.Controls.Swf;
using DelftTools.TestUtils;
using NUnit.Framework;
namespace DelftTools.Tests.Controls.Swf
{
[TestFixture]
public class WindowsFormsHelperTests
{
[Test]
public void DragDropEffectsFromDragOperation()
{
Assert.AreEqual(DragDropEffects.Move, WindowsFormsHelper.ToDragDropEffects(DragOperations.Move));
Assert.AreEqual(DragDropEffects.Copy, WindowsFormsHelper.ToDragDropEffects(DragOperations.Copy));
Assert.AreEqual(DragDropEffects.Link, WindowsFormsHelper.ToDragDropEffects(DragOperations.Link));
Assert.AreEqual(DragDropEffects.Scroll, WindowsFormsHelper.ToDragDropEffects(DragOperations.Scroll));
Assert.AreEqual(DragDropEffects.All, WindowsFormsHelper.ToDragDropEffects(DragOperations.All));
Assert.AreEqual(DragDropEffects.None, WindowsFormsHelper.ToDragDropEffects(DragOperations.None));
// test also bitwise combined flags
Assert.AreEqual(DragDropEffects.Move | DragDropEffects.Copy, WindowsFormsHelper.ToDragDropEffects(DragOperations.Move | DragOperations.Copy));
}
}
} |
using AutoService.Core.Contracts;
using AutoService.Core.Validator;
using AutoService.Models.Common.Contracts;
using AutoService.Models.Common.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
namespace AutoService.Core.Commands
{
public class RemoveEmployeeResponsibility : ICommand
{
private readonly IWriter writer;
private readonly IDatabase database;
private readonly IValidateCore coreValidator;
public RemoveEmployeeResponsibility(IProcessorLocator processorLocator)
{
if (processorLocator == null) throw new ArgumentNullException();
this.writer = processorLocator.GetProcessor<IWriter>() ?? throw new ArgumentNullException();
this.database = processorLocator.GetProcessor<IDatabase>() ?? throw new ArgumentNullException();
this.coreValidator = processorLocator.GetProcessor<IValidateCore>() ?? throw new ArgumentNullException();
}
public void ExecuteThisCommand(string[] commandParameters)
{
this.coreValidator.MinimumParameterLength(commandParameters, 3);
this.coreValidator.EmployeeCount(database.Employees.Count);
var employeeId = this.coreValidator.IntFromString(commandParameters[1], "employeeId");
var employee = this.coreValidator.EmployeeById(database.Employees, employeeId);
var responsibilitiesToRemove = commandParameters.Skip(2).ToList();
List<ResponsibilityType> removedResponsibilities = new List<ResponsibilityType>();
foreach (var responsibility in responsibilitiesToRemove)
{
bool isValid = this.coreValidator.IsValidResponsibilityTypeFromString(responsibility);
if (isValid)
{
ResponsibilityType enumResponsibility = (ResponsibilityType)Enum.Parse(typeof(ResponsibilityType), responsibility);
if (employee.Responsibilities.Contains(enumResponsibility))
{
employee.Responsibilities.Remove(enumResponsibility);
removedResponsibilities.Add(enumResponsibility);
}
else
{
writer.Write("Employee does not have this responsibility!");
}
}
}
writer.Write($"Employee {employee.FirstName} {employee.LastName} were succesfuly declined and removed responsibilities {string.Join(", ", removedResponsibilities)}");
}
}
}
|
//------------------------------------------------------------------------------------------------------------------
// Volumetric Fog & Mist
// Created by Ramiro Oliva (Kronnect)
//------------------------------------------------------------------------------------------------------------------
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace VolumetricFogAndMist {
public enum MASK_TEXTURE_BRUSH_MODE {
AddFog = 0,
RemoveFog = 1
}
public partial class VolumetricFog : MonoBehaviour {
const int MAX_SIMULTANEOUS_TRANSITIONS = 10000;
#region Fog of War settings
[SerializeField]
bool _fogOfWarEnabled;
public bool fogOfWarEnabled {
get { return _fogOfWarEnabled; }
set {
if (value != _fogOfWarEnabled) {
_fogOfWarEnabled = value;
FogOfWarInit();
UpdateMaterialProperties();
isDirty = true;
}
}
}
[SerializeField]
Vector3 _fogOfWarCenter;
public Vector3 fogOfWarCenter {
get { return _fogOfWarCenter; }
set {
if (value != _fogOfWarCenter) {
_fogOfWarCenter = value;
UpdateMaterialProperties();
isDirty = true;
}
}
}
[SerializeField]
Vector3 _fogOfWarSize = new Vector3(1024, 0, 1024);
public Vector3 fogOfWarSize {
get { return _fogOfWarSize; }
set {
if (value != _fogOfWarSize) {
if (value.x > 0 && value.z > 0) {
_fogOfWarSize = value;
UpdateMaterialProperties();
isDirty = true;
}
}
}
}
[SerializeField, Range(32, 2048)]
int _fogOfWarTextureSize = 256;
public int fogOfWarTextureSize {
get { return _fogOfWarTextureSize; }
set {
if (value != _fogOfWarTextureSize) {
if (value > 16) {
_fogOfWarTextureSize = value;
FogOfWarUpdateTexture();
UpdateMaterialProperties();
isDirty = true;
}
}
}
}
[SerializeField, Range(0, 100)]
float _fogOfWarRestoreDelay = 0;
public float fogOfWarRestoreDelay {
get { return _fogOfWarRestoreDelay; }
set {
if (value != _fogOfWarRestoreDelay) {
_fogOfWarRestoreDelay = value;
isDirty = true;
}
}
}
[SerializeField, Range(0, 25)]
float _fogOfWarRestoreDuration = 2f;
public float fogOfWarRestoreDuration {
get { return _fogOfWarRestoreDuration; }
set {
if (value != _fogOfWarRestoreDuration) {
_fogOfWarRestoreDuration = value;
isDirty = true;
}
}
}
[SerializeField, Range(0, 1)]
float _fogOfWarSmoothness = 1f;
public float fogOfWarSmoothness {
get { return _fogOfWarSmoothness; }
set {
if (value != _fogOfWarSmoothness) {
_fogOfWarSmoothness = value;
isDirty = true;
}
}
}
[SerializeField]
bool _fogOfWarBlur;
public bool fogOfWarBlur {
get { return _fogOfWarBlur; }
set {
if (value != _fogOfWarBlur) {
_fogOfWarBlur = value;
isDirty = true;
}
}
}
#endregion
#region In-Editor fog of war painter
[SerializeField]
bool _maskEditorEnabled;
public bool maskEditorEnabled {
get { return _maskEditorEnabled; }
set {
if (value != _maskEditorEnabled) {
_maskEditorEnabled = value;
}
}
}
[SerializeField]
MASK_TEXTURE_BRUSH_MODE _maskBrushMode = MASK_TEXTURE_BRUSH_MODE.RemoveFog;
public MASK_TEXTURE_BRUSH_MODE maskBrushMode {
get { return _maskBrushMode; }
set {
if (value != _maskBrushMode) {
_maskBrushMode = value;
}
}
}
[SerializeField, Range(1, 128)]
int _maskBrushWidth = 20;
public int maskBrushWidth {
get { return _maskBrushWidth; }
set {
if (value != _maskBrushWidth) {
_maskBrushWidth = value;
}
}
}
[SerializeField, Range(0, 1)]
float _maskBrushFuzziness = 0.5f;
public float maskBrushFuzziness {
get { return _maskBrushFuzziness; }
set {
if (value != _maskBrushFuzziness) {
_maskBrushFuzziness = value;
}
}
}
[SerializeField, Range(0, 1)]
float _maskBrushOpacity = 0.15f;
public float maskBrushOpacity {
get { return _maskBrushOpacity; }
set {
if (value != _maskBrushOpacity) {
_maskBrushOpacity = value;
}
}
}
#endregion
bool canDestroyFOWTexture;
[SerializeField]
Texture2D _fogOfWarTexture;
public Texture2D fogOfWarTexture {
get { return _fogOfWarTexture; }
set {
if (_fogOfWarTexture != value) {
if (value != null) {
if (value.width != value.height) {
Debug.LogError("Fog of war texture must be square.");
} else {
_fogOfWarTexture = value;
canDestroyFOWTexture = false;
ReloadFogOfWarTexture();
}
}
}
}
}
Color32[] fogOfWarColorBuffer;
struct FogOfWarTransition {
public bool enabled;
public int x, y;
public float startTime, startDelay;
public float duration;
public int initialAlpha;
public int targetAlpha;
}
FogOfWarTransition[] fowTransitionList;
int lastTransitionPos;
Dictionary<int, int> fowTransitionIndices;
bool requiresTextureUpload;
Material fowBlur;
RenderTexture fowBlur1, fowBlur2;
#region Fog Of War
void FogOfWarInit() {
if (fowTransitionList == null || fowTransitionList.Length != MAX_SIMULTANEOUS_TRANSITIONS) {
fowTransitionList = new FogOfWarTransition[MAX_SIMULTANEOUS_TRANSITIONS];
}
if (fowTransitionIndices == null) {
fowTransitionIndices = new Dictionary<int, int>(MAX_SIMULTANEOUS_TRANSITIONS);
} else {
fowTransitionIndices.Clear();
}
lastTransitionPos = -1;
if (_fogOfWarTexture == null) {
FogOfWarUpdateTexture();
} else if (_fogOfWarEnabled && (fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0)) {
ReloadFogOfWarTexture();
}
}
void FogOfWarDestroy() {
if (canDestroyFOWTexture && _fogOfWarTexture != null) {
DestroyImmediate(_fogOfWarTexture);
}
if (fowBlur1!=null) {
fowBlur1.Release();
}
if (fowBlur2 != null) {
fowBlur2.Release();
}
}
/// <summary>
/// Reloads the current contents of the fog of war texture
/// </summary>
public void ReloadFogOfWarTexture() {
if (_fogOfWarTexture == null) return;
_fogOfWarTextureSize = _fogOfWarTexture.width;
fogOfWarColorBuffer = _fogOfWarTexture.GetPixels32();
lastTransitionPos = -1;
fowTransitionIndices.Clear();
isDirty = true;
fogOfWarEnabled = true;
}
void FogOfWarUpdateTexture() {
if (!_fogOfWarEnabled || !Application.isPlaying)
return;
int size = GetScaledSize(_fogOfWarTextureSize, 1.0f);
if (_fogOfWarTexture == null || _fogOfWarTexture.width != size || _fogOfWarTexture.height != size) {
_fogOfWarTexture = new Texture2D(size, size, TextureFormat.Alpha8, false);
_fogOfWarTexture.hideFlags = HideFlags.DontSave;
_fogOfWarTexture.filterMode = FilterMode.Bilinear;
_fogOfWarTexture.wrapMode = TextureWrapMode.Clamp;
canDestroyFOWTexture = true;
ResetFogOfWar();
}
}
/// <summary>
/// Updates fog of war transitions and uploads texture changes to GPU if required
/// </summary>
public void UpdateFogOfWar(bool forceUpload = false) {
if (!_fogOfWarEnabled || _fogOfWarTexture == null)
return;
if (forceUpload) {
requiresTextureUpload = true;
}
int tw = _fogOfWarTexture.width;
for (int k = 0; k <= lastTransitionPos; k++) {
FogOfWarTransition fw = fowTransitionList[k];
if (!fw.enabled)
continue;
float elapsed = Time.time - fw.startTime - fw.startDelay;
if (elapsed > 0) {
float t = fw.duration <= 0 ? 1 : elapsed / fw.duration;
if (t < 0) t = 0; else if (t > 1f) t = 1f;
int alpha = (int)(fw.initialAlpha + (fw.targetAlpha - fw.initialAlpha) * t);
int colorPos = fw.y * tw + fw.x;
fogOfWarColorBuffer[colorPos].a = (byte)alpha;
requiresTextureUpload = true;
if (t >= 1f) {
fowTransitionList[k].enabled = false;
// Add refill slot if needed
if (fw.targetAlpha < 255 && _fogOfWarRestoreDelay > 0) {
AddFogOfWarTransitionSlot(fw.x, fw.y, (byte)fw.targetAlpha, 255, _fogOfWarRestoreDelay, _fogOfWarRestoreDuration);
}
}
}
}
if (requiresTextureUpload) {
requiresTextureUpload = false;
_fogOfWarTexture.SetPixels32(fogOfWarColorBuffer);
_fogOfWarTexture.Apply();
// Smooth texture
if (_fogOfWarBlur) {
SetFowBlurTexture();
}
#if UNITY_EDITOR
if (!Application.isPlaying) {
UnityEditor.EditorUtility.SetDirty(_fogOfWarTexture);
}
#endif
}
}
void SetFowBlurTexture() {
if (fowBlur == null) {
fowBlur = new Material(Shader.Find("VolumetricFogAndMist/FoWBlur"));
fowBlur.hideFlags = HideFlags.DontSave;
}
if (fowBlur == null)
return;
if (fowBlur1 == null || fowBlur1.width != _fogOfWarTexture.width || fowBlur2 == null || fowBlur2.width != _fogOfWarTexture.width) {
CreateFoWBlurRTs();
}
fowBlur1.DiscardContents();
Graphics.Blit(_fogOfWarTexture, fowBlur1, fowBlur, 0);
fowBlur2.DiscardContents();
Graphics.Blit(fowBlur1, fowBlur2, fowBlur, 1);
fogMat.SetTexture("_FogOfWar", fowBlur2);
}
void CreateFoWBlurRTs() {
if (fowBlur1 != null) {
fowBlur1.Release();
}
if (fowBlur2 != null) {
fowBlur2.Release();
}
RenderTextureDescriptor desc = new RenderTextureDescriptor(_fogOfWarTexture.width, _fogOfWarTexture.height, RenderTextureFormat.ARGB32, 0);
fowBlur1 = new RenderTexture(desc);
fowBlur2 = new RenderTexture(desc);
}
/// <summary>
/// Instantly changes the alpha value of the fog of war at world position. It takes into account FogOfWarCenter and FogOfWarSize.
/// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
/// </summary>
/// <param name="worldPosition">in world space coordinates.</param>
/// <param name="radius">radius of application in world units.</param>
public void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha) {
SetFogOfWarAlpha(worldPosition, radius, fogNewAlpha, 1f);
}
/// <summary>
/// Changes the alpha value of the fog of war at world position creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
/// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
/// </summary>
/// <param name="worldPosition">in world space coordinates.</param>
/// <param name="radius">radius of application in world units.</param>
/// <param name="fogNewAlpha">target alpha value.</param>
/// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
public void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha, float duration) {
SetFogOfWarAlpha(worldPosition, radius, fogNewAlpha, true, duration, _fogOfWarSmoothness, _fogOfWarRestoreDelay, _fogOfWarRestoreDuration);
}
/// <summary>
/// Changes the alpha value of the fog of war at world position creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
/// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
/// </summary>
/// <param name="worldPosition">in world space coordinates.</param>
/// <param name="radius">radius of application in world units.</param>
/// <param name="fogNewAlpha">target alpha value.</param>
/// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
/// <param name="smoothness">border smoothness.</param>
public void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha, float duration, float smoothness) {
SetFogOfWarAlpha(worldPosition, radius, fogNewAlpha, true, duration, smoothness, _fogOfWarRestoreDelay, _fogOfWarRestoreDuration);
}
/// <summary>
/// Changes the alpha value of the fog of war at world position creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
/// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
/// </summary>
/// <param name="worldPosition">in world space coordinates.</param>
/// <param name="radius">radius of application in world units.</param>
/// <param name="fogNewAlpha">target alpha value.</param>
/// <param name="blendAlpha">if new alpha is combined with preexisting alpha value or replaced.</param>
/// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
/// <param name="smoothness">border smoothness.</param>
/// <param name="restoreDelay">delay before the fog alpha is restored. Pass 0 to keep change forever.</param>
/// <param name="restoreDuration">restore duration in seconds.</param>
public void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha, bool blendAlpha, float duration, float smoothness, float restoreDelay, float restoreDuration) {
if (_fogOfWarTexture == null || fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0)
return;
float tx = (worldPosition.x - _fogOfWarCenter.x) / _fogOfWarSize.x + 0.5f;
if (tx < 0 || tx > 1f)
return;
float tz = (worldPosition.z - _fogOfWarCenter.z) / _fogOfWarSize.z + 0.5f;
if (tz < 0 || tz > 1f)
return;
int tw = _fogOfWarTexture.width;
int th = _fogOfWarTexture.height;
int px = (int)(tx * tw);
int pz = (int)(tz * th);
float sm = 0.0001f + smoothness;
int colorBufferPos = pz * tw + px;
byte newAlpha8 = (byte)(fogNewAlpha * 255);
float tr = radius / _fogOfWarSize.z;
int delta = (int)(th * tr);
int deltaSqr = delta * delta;
for (int r = pz - delta; r <= pz + delta; r++) {
if (r > 0 && r < th - 1) {
for (int c = px - delta; c <= px + delta; c++) {
if (c > 0 && c < tw - 1) {
int distanceSqr = (pz - r) * (pz - r) + (px - c) * (px - c);
if (distanceSqr <= deltaSqr) {
colorBufferPos = r * tw + c;
Color32 colorBuffer = fogOfWarColorBuffer[colorBufferPos];
if (!blendAlpha) colorBuffer.a = 255;
distanceSqr = deltaSqr - distanceSqr;
float t = (float)distanceSqr / (deltaSqr * sm);
t = 1f - t;
if (t < 0) t = 0; else if (t > 1f) t = 1f;
byte targetAlpha = (byte)(newAlpha8 + (colorBuffer.a - newAlpha8) * t);
if (targetAlpha < 255) {
if (duration > 0) {
AddFogOfWarTransitionSlot(c, r, colorBuffer.a, targetAlpha, 0, duration);
} else {
colorBuffer.a = targetAlpha;
fogOfWarColorBuffer[colorBufferPos] = colorBuffer;
//fogOfWarTexture.SetPixel(c, r, colorBuffer);
requiresTextureUpload = true;
if (restoreDelay > 0) {
AddFogOfWarTransitionSlot(c, r, targetAlpha, 255, restoreDelay, restoreDuration);
}
}
}
}
}
}
}
}
}
/// <summary>
/// Changes the alpha value of the fog of war within bounds creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
/// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
/// </summary>
/// <param name="bounds">in world space coordinates.</param>
/// <param name="fogNewAlpha">target alpha value.</param>
/// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
public void SetFogOfWarAlpha(Bounds bounds, float fogNewAlpha, float duration) {
SetFogOfWarAlpha(bounds, fogNewAlpha, true, duration, _fogOfWarSmoothness, _fogOfWarRestoreDelay, _fogOfWarRestoreDuration);
}
/// <summary>
/// Changes the alpha value of the fog of war within bounds creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
/// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
/// </summary>
/// <param name="bounds">in world space coordinates.</param>
/// <param name="fogNewAlpha">target alpha value.</param>
/// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
/// <param name="smoothness">border smoothness.</param>
public void SetFogOfWarAlpha(Bounds bounds, float fogNewAlpha, float duration, float smoothness) {
SetFogOfWarAlpha(bounds, fogNewAlpha, true, duration, smoothness, _fogOfWarRestoreDelay, _fogOfWarRestoreDuration);
}
/// <summary>
/// Changes the alpha value of the fog of war within bounds creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
/// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
/// </summary>
/// <param name="bounds">in world space coordinates.</param>
/// <param name="fogNewAlpha">target alpha value.</param>
/// <param name="blendAlpha">if new alpha is combined with preexisting alpha value or replaced.</param>
/// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
/// <param name="smoothness">border smoothness.</param>
/// <param name="fuzzyness">randomization of border noise.</param>
/// <param name="restoreDelay">delay before the fog alpha is restored. Pass 0 to keep change forever.</param>
/// <param name="restoreDuration">restore duration in seconds.</param>
public void SetFogOfWarAlpha(Bounds bounds, float fogNewAlpha, bool blendAlpha, float duration, float smoothness, float restoreDelay, float restoreDuration) {
if (_fogOfWarTexture == null || fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0)
return;
Vector3 worldPosition = bounds.center;
float tx = (worldPosition.x - _fogOfWarCenter.x) / _fogOfWarSize.x + 0.5f;
if (tx < 0 || tx > 1f)
return;
float tz = (worldPosition.z - _fogOfWarCenter.z) / _fogOfWarSize.z + 0.5f;
if (tz < 0 || tz > 1f)
return;
int tw = _fogOfWarTexture.width;
int th = _fogOfWarTexture.height;
int px = (int)(tx * tw);
int pz = (int)(tz * th);
int colorBufferPos = pz * tw + px;
byte newAlpha8 = (byte)(fogNewAlpha * 255);
float trz = bounds.extents.z / _fogOfWarSize.z;
float trx = bounds.extents.x / _fogOfWarSize.x;
float aspect1 = trx > trz ? 1f : trz / trx;
float aspect2 = trx > trz ? trx / trz : 1f;
int deltaz = (int)(th * trz);
int deltazSqr = deltaz * deltaz;
int deltax = (int)(tw * trx);
int deltaxSqr = deltax * deltax;
float sm = 0.0001f + smoothness;
for (int r = pz - deltaz; r <= pz + deltaz; r++) {
if (r > 0 && r < th - 1) {
int distancezSqr = (pz - r) * (pz - r);
distancezSqr = deltazSqr - distancezSqr;
float t1 = (float)distancezSqr * aspect1 / (deltazSqr * sm);
for (int c = px - deltax; c <= px + deltax; c++) {
if (c > 0 && c < tw - 1) {
int distancexSqr = (px - c) * (px - c);
colorBufferPos = r * tw + c;
Color32 colorBuffer = fogOfWarColorBuffer[colorBufferPos];
if (!blendAlpha) colorBuffer.a = 255;
distancexSqr = deltaxSqr - distancexSqr;
float t2 = (float)distancexSqr * aspect2 / (deltaxSqr * sm);
float t = t1 < t2 ? t1 : t2;
t = 1f - t;
if (t < 0) t = 0; else if (t > 1f) t = 1f;
byte targetAlpha = (byte)(newAlpha8 + (colorBuffer.a - newAlpha8) * t); // Mathf.Lerp(newAlpha8, colorBuffer.a, t);
if (targetAlpha < 255) {
if (duration > 0) {
AddFogOfWarTransitionSlot(c, r, colorBuffer.a, targetAlpha, 0, duration);
} else {
colorBuffer.a = targetAlpha;
fogOfWarColorBuffer[colorBufferPos] = colorBuffer;
//fogOfWarTexture.SetPixel(c, r, colorBuffer);
requiresTextureUpload = true;
if (restoreDelay > 0) {
AddFogOfWarTransitionSlot(c, r, targetAlpha, 255, restoreDelay, restoreDuration);
}
}
}
}
}
}
}
}
/// <summary>
/// Restores fog of war to full opacity
/// </summary>
/// <param name="worldPosition">World position.</param>
/// <param name="radius">Radius.</param>
public void ResetFogOfWarAlpha(Vector3 worldPosition, float radius) {
if (_fogOfWarTexture == null || fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0)
return;
float tx = (worldPosition.x - _fogOfWarCenter.x) / _fogOfWarSize.x + 0.5f;
if (tx < 0 || tx > 1f)
return;
float tz = (worldPosition.z - _fogOfWarCenter.z) / _fogOfWarSize.z + 0.5f;
if (tz < 0 || tz > 1f)
return;
int tw = _fogOfWarTexture.width;
int th = _fogOfWarTexture.height;
int px = (int)(tx * tw);
int pz = (int)(tz * th);
float tr = radius / _fogOfWarSize.z;
int delta = (int)(th * tr);
int deltaSqr = delta * delta;
for (int r = pz - delta; r <= pz + delta; r++) {
if (r > 0 && r < th - 1) {
for (int c = px - delta; c <= px + delta; c++) {
if (c > 0 && c < tw - 1) {
int distanceSqr = (pz - r) * (pz - r) + (px - c) * (px - c);
if (distanceSqr <= deltaSqr) {
int colorBufferPos = r * tw + c;
Color32 colorBuffer = fogOfWarColorBuffer[colorBufferPos];
colorBuffer.a = 255;
fogOfWarColorBuffer[colorBufferPos] = colorBuffer;
//fogOfWarTexture.SetPixel(c, r, colorBuffer);
requiresTextureUpload = true;
}
}
}
}
}
}
/// <summary>
/// Restores fog of war to full opacity
/// </summary>
public void ResetFogOfWarAlpha(Bounds bounds) {
ResetFogOfWarAlpha(bounds.center, bounds.extents.x, bounds.extents.z);
}
/// <summary>
/// Restores fog of war to full opacity
/// </summary>
public void ResetFogOfWarAlpha(Vector3 position, Vector3 size) {
ResetFogOfWarAlpha(position, size.x * 0.5f, size.z * 0.5f);
}
/// <summary>
/// Restores fog of war to full opacity
/// </summary>
/// <param name="position">Position in world space.</param>
/// <param name="extentsX">Half of the length of the rectangle in X-Axis.</param>
/// <param name="extentsZ">Half of the length of the rectangle in Z-Axis.</param>
public void ResetFogOfWarAlpha(Vector3 position, float extentsX, float extentsZ) {
if (_fogOfWarTexture == null || fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0)
return;
float tx = (position.x - _fogOfWarCenter.x) / _fogOfWarSize.x + 0.5f;
if (tx < 0 || tx > 1f)
return;
float tz = (position.z - _fogOfWarCenter.z) / _fogOfWarSize.z + 0.5f;
if (tz < 0 || tz > 1f)
return;
int tw = _fogOfWarTexture.width;
int th = _fogOfWarTexture.height;
int px = (int)(tx * tw);
int pz = (int)(tz * th);
float trz = extentsZ / _fogOfWarSize.z;
float trx = extentsX / _fogOfWarSize.x;
int deltaz = (int)(th * trz);
int deltax = (int)(tw * trx);
for (int r = pz - deltaz; r <= pz + deltaz; r++) {
if (r > 0 && r < th - 1) {
for (int c = px - deltax; c <= px + deltax; c++) {
if (c > 0 && c < tw - 1) {
int colorBufferPos = r * tw + c;
Color32 colorBuffer = fogOfWarColorBuffer[colorBufferPos];
colorBuffer.a = 255;
fogOfWarColorBuffer[colorBufferPos] = colorBuffer;
//fogOfWarTexture.SetPixel(c, r, colorBuffer);
requiresTextureUpload = true;
}
}
}
}
}
public void ResetFogOfWar(byte alpha = 255) {
if (_fogOfWarTexture == null || !isPartOfScene)
return;
int h = _fogOfWarTexture.height;
int w = _fogOfWarTexture.width;
int newLength = h * w;
if (fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length != newLength) {
fogOfWarColorBuffer = new Color32[newLength];
}
Color32 opaque = new Color32(alpha, alpha, alpha, alpha);
for (int k = 0; k < newLength; k++) {
fogOfWarColorBuffer[k] = opaque;
}
_fogOfWarTexture.SetPixels32(fogOfWarColorBuffer);
_fogOfWarTexture.Apply();
lastTransitionPos = -1;
fowTransitionIndices.Clear();
isDirty = true;
}
/// <summary>
/// Gets or set fog of war state as a Color32 buffer. The alpha channel stores the transparency of the fog at that position (0 = no fog, 1 = opaque).
/// </summary>
public Color32[] fogOfWarTextureData {
get {
return fogOfWarColorBuffer;
}
set {
fogOfWarEnabled = true;
fogOfWarColorBuffer = value;
if (value == null || _fogOfWarTexture == null)
return;
if (value.Length != _fogOfWarTexture.width * _fogOfWarTexture.height)
return;
_fogOfWarTexture.SetPixels32(fogOfWarColorBuffer);
_fogOfWarTexture.Apply();
}
}
void AddFogOfWarTransitionSlot(int x, int y, byte initialAlpha, byte targetAlpha, float delay, float duration) {
// Check if this slot exists
int index;
int key = y * 64000 + x;
if (!fowTransitionIndices.TryGetValue(key, out index)) {
index = -1;
for (int k = 0; k <= lastTransitionPos; k++) {
if (!fowTransitionList[k].enabled) {
index = k;
fowTransitionIndices[key] = index;
break;
}
}
}
if (index >= 0) {
if (fowTransitionList[index].enabled && (fowTransitionList[index].x != x || fowTransitionList[index].y != y)) {
index = -1;
}
}
if (index < 0) {
if (lastTransitionPos >= MAX_SIMULTANEOUS_TRANSITIONS - 1)
return;
index = ++lastTransitionPos;
fowTransitionIndices[key] = index;
}
fowTransitionList[index].x = x;
fowTransitionList[index].y = y;
fowTransitionList[index].duration = duration;
fowTransitionList[index].startTime = Time.time;
fowTransitionList[index].startDelay = delay;
fowTransitionList[index].initialAlpha = initialAlpha;
fowTransitionList[index].targetAlpha = targetAlpha;
fowTransitionList[index].enabled = true;
}
/// <summary>
/// Gets the current alpha value of the Fog of War at a given world position
/// </summary>
/// <returns>The fog of war alpha.</returns>
/// <param name="worldPosition">World position.</param>
public float GetFogOfWarAlpha(Vector3 worldPosition) {
if (fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0 || _fogOfWarTexture == null)
return 1f;
float tx = (worldPosition.x - _fogOfWarCenter.x) / _fogOfWarSize.x + 0.5f;
if (tx < 0 || tx > 1f)
return 1f;
float tz = (worldPosition.z - _fogOfWarCenter.z) / _fogOfWarSize.z + 0.5f;
if (tz < 0 || tz > 1f)
return 1f;
int tw = _fogOfWarTexture.width;
int th = _fogOfWarTexture.height;
int px = (int)(tx * tw);
int pz = (int)(tz * th);
int colorBufferPos = pz * tw + px;
if (colorBufferPos < 0 || colorBufferPos >= fogOfWarColorBuffer.Length)
return 1f;
return fogOfWarColorBuffer[colorBufferPos].a / 255f;
}
#region Gizmos
void ShowFoWGizmo() {
if (_maskEditorEnabled && _fogOfWarEnabled && !Application.isPlaying) {
Vector3 pos = _fogOfWarCenter;
pos.y = -10;
pos.y += _baselineHeight + _height * 0.5f;
Vector3 size = new Vector3(_fogOfWarSize.x, 0.1f, _fogOfWarSize.z);
for (int k = 0; k < 5; k++) {
Gizmos.color = Color.yellow;
Gizmos.DrawWireCube(pos, size);
pos.y += 0.5f;
Gizmos.color = Color.white;
Gizmos.DrawWireCube(pos, size);
pos.y += 0.5f;
}
}
}
#endregion
#endregion
}
} |
using ConcurrentCollections;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using JhinBot.DiscordObjects;
using JhinBot.Services;
using JhinBot.Utils;
using JhinBot.Utils.Exceptions;
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace JhinBot
{
public class CommandHandler : IService
{
public const int GlobalCommandsCooldown = 750;
private readonly Logger _log;
private readonly IOwnerLogger _ownerLogger;
private readonly DiscordSocketClient _client;
private readonly CommandService _commandService;
private readonly IDbService _dbService;
private readonly IPollService _pollService;
private readonly JhinBotInstance _jhinBot;
private IServiceProvider _services;
private readonly IEnumerable<IGuildConfig> _guildConfigs;
private readonly ConversationHandler _conversationHandler;
private readonly CustomCommandHandler _customCommandHandler;
public event Func<IUserMessage, CommandInfo, Task> CommandExecuted = delegate { return Task.CompletedTask; };
public event Func<CommandInfo, ITextChannel, string, Task> CommandErrored = delegate { return Task.CompletedTask; };
public ConcurrentHashSet<ulong> UsersOnShortCooldown { get; } = new ConcurrentHashSet<ulong>();
private readonly Timer _clearUsersOnShortCooldown;
private readonly object errorLogLock = new object();
public CommandHandler(DiscordSocketClient client, CommandService commandService, IDbService dbService,
ConversationHandler conversationHandler, CustomCommandHandler customCommandHandler,
IPollService pollService, JhinBotInstance jhinBot,IEnumerable<IGuildConfig> guildConfigs,
IOwnerLogger ownerLogger)
{
_log = LogManager.GetCurrentClassLogger();
_commandService = commandService;
_client = client;
_dbService = dbService;
_conversationHandler = conversationHandler;
_customCommandHandler = customCommandHandler;
_pollService = pollService;
_jhinBot = jhinBot;
_guildConfigs = guildConfigs;
_ownerLogger = ownerLogger;
}
public void AddServices(IBotServiceProvider services)
{
_services = services;
}
public Task StartHandling()
{
_client.MessageReceived += (msg) => { var _ = Task.Run(() => MessageReceivedHandler(msg)); return Task.CompletedTask; };
return Task.CompletedTask;
}
private async Task MessageReceivedHandler(SocketMessage msg)
{
if (msg.Author.IsBot || !_jhinBot.Ready) //no bots, wait until bot connected and initialized
return;
if (!(msg is SocketUserMessage usrMsg))
return;
if (msg.Content.Length <= 0)
return;
var channel = msg.Channel as ISocketMessageChannel;
var guild = (msg.Channel as SocketTextChannel)?.Guild;
var context = new CommandContext(_client, usrMsg);
try
{
if (await _conversationHandler.TryHandlingConversationForUser(context, usrMsg.Content))
return;
if (await _customCommandHandler.TryToHandleCustomCommand(context, usrMsg.Content, guild.Id))
return;
_pollService.TryAddingNewVote(msg.Content, context);
await TryRunCommand(guild, channel, usrMsg, context);
}
catch (Exception e)
{
await _ownerLogger.LogCommandErrorAsEmbed(new BotException(context, e.TargetSite.ToString(), ToString(), e.Message, e.StackTrace, e.InnerException));
_log.Warn("Error in CommandHandler");
_log.Warn(e);
if (e.InnerException != null)
{
_log.Warn("Inner Exception of the error in CommandHandler");
_log.Warn(e.InnerException);
}
_conversationHandler.DebugReset();
}
}
public async Task TryRunCommand(SocketGuild guild, ISocketMessageChannel channel, IUserMessage usrMsg, ICommandContext context)
{
string messageContent = usrMsg.Content;
var prefix = _jhinBot.BotConfig.Prefix;
if (messageContent.StartsWith(prefix))
{
var result = await ExecuteCommandAsync(context, messageContent, prefix.Length, _services, MultiMatchHandling.Best);
if (result.Success)
{
await CommandExecuted(usrMsg, result.Info).ConfigureAwait(false);
return;
}
else if (result.Error != null)
{
if (guild != null)
await CommandErrored(result.Info, channel as ITextChannel, result.Error);
}
}
}
public Task<(bool Success, string Error, CommandInfo Info)> ExecuteCommandAsync(ICommandContext context, string input, int argPos, IServiceProvider services, MultiMatchHandling multiMatchHandling)
=> ExecuteCommand(context, input.Substring(argPos), services, multiMatchHandling);
public async Task<(bool Success, string Error, CommandInfo Info)> ExecuteCommand(ICommandContext context, string input, IServiceProvider services, MultiMatchHandling multiMatchHandling)
{
var searchResult = _commandService.Search(context, input);
if (!searchResult.IsSuccess)
return (false, null, null);
var commands = searchResult.Commands;
for (int i = commands.Count - 1; i >= 0; i--)
{
var preconditionResult = await commands[i].CheckPreconditionsAsync(context, services);
if (!preconditionResult.IsSuccess)
{
return (false, preconditionResult.ErrorReason, commands[i].Command);
}
var parseResult = await commands[i].ParseAsync(context, searchResult, preconditionResult);
if (!parseResult.IsSuccess)
{
if (parseResult.Error == CommandError.MultipleMatches)
{
TypeReaderValue[] argList, paramList;
switch (multiMatchHandling)
{
case MultiMatchHandling.Best:
argList = parseResult.ArgValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToArray();
paramList = parseResult.ParamValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToArray();
parseResult = ParseResult.FromSuccess(argList, paramList);
break;
}
}
if (!parseResult.IsSuccess)
{
if (commands.Count == 1)
return (false, parseResult.ErrorReason, commands[i].Command);
else
continue;
}
}
var cmd = commands[i].Command;
// Bot will ignore commands which are ran more often than what specified by
// GlobalCommandsCooldown constant (miliseconds)
//if (!UsersOnShortCooldown.Add(context.Message.Author.Id))
// return (false, null, commands[i].Command);
//return SearchResult.FromError(CommandError.Exception, "You are on a global cooldown.");
//var commandName = cmd.Aliases.First();
//foreach (var svc in _services)
//{
// if (svc is ILateBlocker exec &&
// await exec.TryBlockLate(_client, context.Message, context.Guild, context.Channel, context.User, cmd.Module.GetTopLevelModule().Name, commandName).ConfigureAwait(false))
// {
// _log.Info("Late blocking User [{0}] Command: [{1}] in [{2}]", context.User, commandName, svc.GetType().Name);
// return (false, null, commands[i].Command);
// }
//}
var execResult = await commands[i].ExecuteAsync(context, parseResult, services);
if (execResult.Error != null)
{
lock (errorLogLock)
{
var now = DateTime.Now;
File.AppendAllText($"./command_errors_{now:yyyy-MM-dd}.txt",
$"[{now:HH:mm-yyyy-MM-dd}]" + Environment.NewLine
+ execResult.Error.ToString() + "Reason: " + execResult.Error.ToString() + Environment.NewLine
+ "------" + Environment.NewLine);
_log.Warn(execResult.Error);
_log.Warn(execResult.ErrorReason);
}
}
return (true, null, commands[i].Command);
}
return (false, null, null);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerStatsActions : MonoBehaviour
{
private GameObject playerHealthbar;
private GameObject playerStaminabar;
private PlayerBase playerStats;
// Use this for initialization
void Start()
{
playerHealthbar = GameObject.FindGameObjectWithTag(Utilities.PlayerConstants.TagPlayerHealthBar);
playerStaminabar = GameObject.FindGameObjectWithTag(Utilities.PlayerConstants.TagPlayerStaminaBar);
if(playerStaminabar == null || playerHealthbar == null)
{
Debug.LogError("Staminabar or healthbar missing");
}
}
public float TakeDamage(float damage)
{
float healthLeft = playerStats.TakeDamage(damage);
UpdatePlayerStatusBar(playerHealthbar, Utilities.PlayerConstants.PlayerStatusBar.Health);
return healthLeft;
}
public void Heal(float healAmount)
{
playerStats.Heal(healAmount);
UpdatePlayerStatusBar(playerHealthbar, Utilities.PlayerConstants.PlayerStatusBar.Health);
}
public void RecoverStamina(float staminaAmount)
{
playerStats.RecoverStamina(staminaAmount);
UpdatePlayerStatusBar(playerStaminabar, Utilities.PlayerConstants.PlayerStatusBar.Stamina);
}
public float DrainStamina(float staminaAmount)
{
float staminaLeft = playerStats.DrainStamina(staminaAmount);
UpdatePlayerStatusBar(playerStaminabar, Utilities.PlayerConstants.PlayerStatusBar.Stamina);
return staminaLeft;
}
public void SetPlayer(PlayerBase player)
{
playerStats = player;
}
public PlayerBase GetPlayerStats()
{
return playerStats;
}
public float GetPlayerHealthPercent()
{
return playerStats.GetPlayerHpPercent();
}
public float GetPlayerStaminaPercent()
{
return playerStats.GetPlayerStaminaPercent();
}
private void UpdatePlayerStatusBar(GameObject statusBar,
Utilities.PlayerConstants.PlayerStatusBar barType)
{
Vector3 barLocalScale = statusBar.transform.localScale;
if(barType == Utilities.PlayerConstants.PlayerStatusBar.Health)
{
barLocalScale.x = GetPlayerHealthPercent();
playerHealthbar.transform.localScale = barLocalScale;
}
else if(barType == Utilities.PlayerConstants.PlayerStatusBar.Stamina)
{
barLocalScale.x = GetPlayerStaminaPercent();
playerStaminabar.transform.localScale = barLocalScale;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SummoningItem : MonoBehaviour {
public GameObject Item;
public GameObject InfoPanel;
public string Atk, Def, Hp, Type, Name;
public Text NameText;
// Use this for initialization
void Start () {
}
// Update is called once per frame
public void SummonItem(string name)
{
Item.SetActive(true);
Item.GetComponent<Animator>().SetTrigger("Craft");
Item.transform.Find("ImageSummon").GetComponent<Image>().sprite = Resources.Load<Sprite> ("icon_item/" + name);
InfoPanel.SetActive(true);
InfoPanel.transform.Find("HP").GetComponent<Text>().text = Hp;
InfoPanel.transform.Find("Att").GetComponent<Text>().text = Atk;
InfoPanel.transform.Find("Def").GetComponent<Text>().text = Def;
InfoPanel.transform.Find("Type").GetComponent<Text>().text = Type;
NameText.text = Name;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Docller.Core.Models;
namespace Docller.Common
{
public class TransmittalViewModelBinder:DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext,
PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name.Equals("To")
|| propertyDescriptor.Name.Equals("Cc"))
{
string values = controllerContext.HttpContext.Request.Form[propertyDescriptor.Name];
SubscriberItemCollection itemCollection = new SubscriberItemCollection(values);
propertyDescriptor.SetValue(bindingContext.Model, itemCollection);
}else if (propertyDescriptor.Name.Equals("TransmittedFiles"))
{
propertyDescriptor.SetValue(bindingContext.Model, GetFilesValue(controllerContext));
}
else if(propertyDescriptor.Name.Equals("Action"))
{
string action = controllerContext.HttpContext.Request[TransmittalButtons.SaveTransmittal] != null
? TransmittalButtons.SaveTransmittal
: TransmittalButtons.Transmit;
propertyDescriptor.SetValue(bindingContext.Model, action);
}
else
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
private List<TransmittedFile> GetFilesValue(ControllerContext controllerContext)
{
string idValues = controllerContext.HttpContext.Request.Form["FileId"];
List<TransmittedFile> transmittedFiles = new List<TransmittedFile>();
if (!string.IsNullOrEmpty(idValues))
{
string[] ids = idValues.Split(",".ToCharArray());
string[] fileNames = controllerContext.HttpContext.Request.Form["FileName"].Split(",".ToCharArray());
string[] titles = controllerContext.HttpContext.Request.Form["Title"].Split(",".ToCharArray());
string[] revs = controllerContext.HttpContext.Request.Form["Revision"].Split(",".ToCharArray());
//string[] statuses = controllerContext.HttpContext.Request.Form["Status"].Split(",".ToCharArray());
for (int index = 0; index < ids.Length; index++)
{
TransmittedFile tFile = new TransmittedFile
{
FileId = int.Parse(ids[index]),
FileName = fileNames[index],
Title = titles[index],
Revision = revs[index],
//Status = statuses[index]
};
transmittedFiles.Add(tFile);
}
}
return transmittedFiles;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.