text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace CompBase_test1.classes
{
public class UserControl_Call
{
public static void UserControl_Add(Grid grid, UserControl userControl)
{
if (grid.Children.Count > 0)
{
grid.Children.Clear();
grid.Children.Add(userControl);
}
else
{
grid.Children.Add(userControl);
}
}
}
}
|
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace SmartStocksImporter.Models
{
public class Class
{
[JsonPropertyName("p")]
public P p { get; set; }
[JsonPropertyName("c")]
public C c { get; set; }
}
} |
using LoowooTech.Stock.ArcGISTool;
using LoowooTech.Stock.Common;
using LoowooTech.Stock.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LoowooTech.Stock.Rules
{
public class GHYTTDGHDLRule:ArcGISBaseTool,Models.IRule
{
public override string RuleName { get { return "规划用途和土地规划地类逻辑一致性检查"; } }
public override string ID { get { return "3002"; } }
public override CheckProject2 CheckProject { get { return CheckProject2.规划用途数据与土地规划地类数据地类逻辑一致性检查; } }
public bool Space { get { return true; } }
public void Check()
{
if (ExtractGHYT() == false)
{
return;
}
if (ArcExtensions2.ImportFeatureClass(string.Format("{0}\\{1}", ParameterManager2.MDBFilePath, "TDGHDL"), MdbFilePath, "TDGHDL", null) == false)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("导入土地规划地类图层失败")
});
return;
}
if (ArcExtensions2.Select(string.Format("{0}\\{1}",MdbFilePath,"GHYT"),string.Format("{0}\\{1}",MdbFilePath,"GHYT_XG"),"GHYTDM LIKE 'G*' OR GHYTDM LIKE 'X*'") == false)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("提取规划用途层中现状和新增数据失败!")
});
return;
}
var sql = "SELECT MID(GHYTDM,2) FROM GHYT_XG GROUP BY MID(GHYTDM,2)";
var list = Search(MdbFilePath, sql);
if (list.Count == 0)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("执行SQL[{0}]获取结果为空", sql)
});
return;
}
var workspace = MdbFilePath.OpenAccessFileWorkSpace();
if (workspace == null)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("打开ArcGIS 工作空间失败!")
});
return;
}
var ghytFeatureClass = workspace.GetFeatureClass("GHYT_XG");
if (ghytFeatureClass == null)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("获取要素类【GHYT_XG】失败!")
});
return;
}
var tdghdlFeatureClass = workspace.GetFeatureClass("TDGHDL");
if (tdghdlFeatureClass == null)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("获取要素类【TDGHDL】失败!")
});
return;
}
var messages = new List<string>();
foreach(var item in list)
{
var ghytArea = Math.Round(ArcClass.GainArea(ghytFeatureClass, string.Format("GHYTDM = 'X{0}' OR GHYTDM = 'G{0}'", item)), 2);
var tdghdlArea = Math.Round(ArcClass.GainArea(tdghdlFeatureClass, string.Format("GHDLDM = '{0}'", item)), 2);
var abs = Math.Abs(ghytArea - tdghdlArea);
var flag = false;
if (ParameterManager2.Absolute.HasValue)
{
flag = abs < ParameterManager2.Absolute.Value;
}
if (ParameterManager2.Relative.HasValue)
{
var pp = abs / tdghdlArea;
flag = pp < ParameterManager2.Relative.Value;
}
if (flag == false)
{
messages.Add(string.Format("规划用途中规划用途代码为【X{0}】+【G{0}】的面积和与土地规划地类层中地类面积和不相等", item));
}
}
QuestionManager2.AddRange(messages.Select(e => new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = e
}).ToList());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
/// <summary>
/// Summary description for Horario
/// </summary>
[DataContract]
public class cHorario
{
public cHorario()
{
//
// TODO: Add constructor logic here
//
}
[DataMember(IsRequired = true)]
public int HoraioID
{ get; set; }
[DataMember(IsRequired = true)]
public int DiaID
{ get; set; }
[DataMember(IsRequired = true)]
public string DiaStr
{ get; set; }
[DataMember(IsRequired = true)]
public DateTime HoraInicial
{ get; set; }
[DataMember(IsRequired = true)]
public DateTime HoraFinal
{ get; set; }
[DataMember(IsRequired = true)]
public bool Activo
{ get; set; }
[DataMember(IsRequired = true)]
public int SucursalID
{ get; set; }
[DataMember(IsRequired = true)]
public string SucursalStr
{ get; set; }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class MultiplierManager : MonoBehaviour
{
public static MultiplierManager instance;
[SerializeField] private List<MultiplierSegment> multipliers = new List<MultiplierSegment> ();
[Space]
[SerializeField] private List<Image> fillImages;
[SerializeField] private float fillAmountTarget;
[SerializeField] private float fillAmountDamp = 2.5f;
[SerializeField] private float timeCounter = 0.0f;
[Space]
[SerializeField] private float currentSegmentProgress = 0;
[SerializeField] private int currentSegmentIndex = -1;
[Space]
[SerializeField] private TextMeshProUGUI timeText;
[SerializeField] private GameObject newMultiplierTextPrefab;
[SerializeField] private List<Transform> multiplierPositions = new List<Transform> ();
private Dictionary<Transform, bool> multipliersWithGameObjects = new Dictionary<Transform, bool> ();
private int lastUsedMultiplierPositionIndex = -1;
[SerializeField] private UITween parentTween;
[SerializeField] private UITween flameTween;
[SerializeField] private Image multiplierFillImage;
[SerializeField] private Image timeFillImage;
[SerializeField] private TextMeshProUGUI multiplierText;
[SerializeField] private float highestFill = 0.6875f;
private float multiplierFillTarget;
private float timeFillTarget;
public System.Action<int> OnMultiplierChanged;
[NaughtyAttributes.ShowNativeProperty] public int GetCurrentMultiplier
{
get
{
if (currentSegmentIndex == -1) return 1;
else return (int)multipliers[currentSegmentIndex].multiplier;
}
}
private void Awake ()
{
if (instance == null)
instance = this;
else if(instance != this)
{
Destroy ( this.gameObject );
return;
}
for (int i = 0; i < multiplierPositions.Count; i++)
{
multipliersWithGameObjects.Add ( multiplierPositions[i], false );
}
}
private Transform GetEmptyMultiplierPosition (string reason)
{
List<Transform> transformsFound = new List<Transform> ();
for (int i = 0; i < multiplierPositions.Count; i++)
{
if (multipliersWithGameObjects[multiplierPositions[i]] == false)
{
transformsFound.Add ( multiplierPositions[i] );
}
else
{
if (multiplierPositions[i].GetComponentInChildren<TextMeshProUGUI> ().text.Contains ( reason ))
{
return null;
}
}
}
if (transformsFound.Count > 0)
{
if(transformsFound.Count > 1)
{
if(lastUsedMultiplierPositionIndex >= 0 && transformsFound.Contains ( multiplierPositions[lastUsedMultiplierPositionIndex] ))
{
transformsFound.Remove ( multiplierPositions[lastUsedMultiplierPositionIndex] );
}
}
int randIndex = UnityEngine.Random.Range ( 0, transformsFound.Count );
lastUsedMultiplierPositionIndex = multiplierPositions.IndexOf ( transformsFound[randIndex] );
return transformsFound[randIndex];
}
return null;
}
private void Update ()
{
MonitorTime ();
CheckCurrentSegment ();
UpdateFillUI ();
}
public void AddProgress (float amount, string reason)
{
currentSegmentProgress += amount;
currentSegmentProgress = Mathf.Clamp ( currentSegmentProgress, 0.0f, multipliers[multipliers.Count - 1].scoreRequiredForMultiplier + 1);
Transform t = GetEmptyMultiplierPosition (reason);
if (t == null) return;
GameObject go = Instantiate ( newMultiplierTextPrefab );
go.GetComponent<SelfDestruct> ().onDestruct += () => { multipliersWithGameObjects[t] = false; };
multipliersWithGameObjects[t] = true;
go.transform.SetParent ( t );
go.GetComponent<RectTransform> ().anchoredPosition3D = Vector3.zero;
go.transform.localRotation = Quaternion.identity;
string s = "<color=#F8FF53>Score Multiplier!</color>";
s += "\n";
s += "<size=85%>" + reason + "</size>";
go.GetComponent<TextMeshProUGUI> ().text = s;
CheckCurrentSegment ();
}
private void MonitorTime ()
{
if (timeCounter > 0)
{
timeCounter -= Time.deltaTime;
if (timeCounter <= 0)
{
if (currentSegmentIndex == multipliers.Count)
{
FinishMultiplier ();
}
else
{
DecreaseMultiplier ();
}
}
}
}
private void CheckCurrentSegment ()
{
if (currentSegmentIndex + 1 < multipliers.Count)
{
if (currentSegmentProgress >= multipliers[currentSegmentIndex + 1].scoreRequiredForMultiplier)
{
IncreaseMultiplier ();
}
}
}
private void UpdateFillUI ()
{
if (currentSegmentIndex >= 0)
{
float fillX = multipliers[currentSegmentIndex].fillExtents.x;
float fillY = multipliers[currentSegmentIndex].fillExtents.y;
if (currentSegmentIndex != multipliers.Count - 1)
multiplierFillTarget = Mathf.Lerp ( 0, highestFill, Mathf.InverseLerp ( multipliers[currentSegmentIndex].scoreRequiredForMultiplier, multipliers[currentSegmentIndex + 1].scoreRequiredForMultiplier, currentSegmentProgress ) );
else
multiplierFillTarget = 1.0f;
}
else
{
multiplierFillTarget = 0.0f;
}
multiplierFillImage.fillAmount = Mathf.Lerp ( multiplierFillImage.fillAmount, multiplierFillTarget, Time.deltaTime * fillAmountDamp );
timeFillTarget = Mathf.Lerp ( 0, highestFill, Mathf.InverseLerp ( 0.0f, currentSegmentIndex >= 0 ? multipliers[currentSegmentIndex].timeGiven : 0.0f, timeCounter ) );
if (timeFillImage.fillAmount < timeFillTarget)
timeFillImage.fillAmount = Mathf.Lerp ( timeFillImage.fillAmount, timeFillTarget, Time.deltaTime * fillAmountDamp * 5.0f );
else
timeFillImage.fillAmount = Mathf.Lerp ( timeFillImage.fillAmount, timeFillTarget, Time.deltaTime * fillAmountDamp );
}
public void FinishMultiplier ()
{
currentSegmentProgress = 0.0f;
timeCounter = 0;
}
public void IncreaseMultiplier ()
{
currentSegmentIndex++;
currentSegmentIndex = Mathf.Clamp ( currentSegmentIndex, -1, multipliers.Count - 1);
parentTween.FadeIn ( 0.25f );
timeCounter = multipliers[currentSegmentIndex].timeGiven;
multiplierText.text = multipliers[currentSegmentIndex].multiplier.ToString ( "0" ) + "x";
OnMultiplierChanged?.Invoke ( GetCurrentMultiplier );
if (currentSegmentIndex >= multipliers.Count - 1) flameTween.FadeIn (0.5f);
}
public void DecreaseMultiplier ()
{
currentSegmentIndex--;
currentSegmentIndex = Mathf.Clamp ( currentSegmentIndex, -1, multipliers.Count - 1 );
flameTween.FadeOut ( 0.5f );
if (currentSegmentIndex >= 0)
{
timeCounter = multipliers[currentSegmentIndex].timeGiven;
currentSegmentProgress = multipliers[currentSegmentIndex].scoreRequiredForMultiplier;
}
else
{
currentSegmentProgress = 0;
}
OnMultiplierChanged?.Invoke ( GetCurrentMultiplier );
if (currentSegmentIndex <= -1)
{
multiplierText.text = "";
parentTween.FadeOut ( 0.25f );
}
else
{
multiplierText.text = multipliers[currentSegmentIndex].multiplier.ToString ( "0" ) + "x";
}
}
[System.Serializable]
public class MultiplierSegment
{
public float multiplier;
public float timeGiven;
public float scoreRequiredForMultiplier;
public Vector2 fillExtents = new Vector2 ( 0.05f, 0.5f );
public Animator anim;
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace Voluntariat.Data.Migrations
{
public partial class Add_Roles : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "Ongs",
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);
migrationBuilder.InsertData(
table: "AspNetRoles",
columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
values: new object[,]
{
{ "9ada98e1-4054-4d9a-a591-0dfd20d4cea3", "471befb4-f2ec-434f-a195-b3963a502715", "Admin", "Admin" },
{ "731570ea-7c31-462f-bc9c-bcaafba892a1", "471befb4-f2ec-434f-a195-b3963a502717", "Volunteer", "Volunteer" },
{ "c449f071-e14e-469e-affe-1c8b2269cc3f", "471befb4-f2ec-434f-a195-b3963a502718", "Doctor", "Doctor" },
{ "b9aedc08-76f8-4017-9156-27180e377dca", "471befb4-f2ec-434f-a195-b3963a502719", "Beneficiary", "Beneficiary" },
{ "bd0d075f-663a-445f-8902-b555a09b1d2d", "471befb4-f2ec-434f-a195-b3963a502716", "Guest", "Guest" }
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "731570ea-7c31-462f-bc9c-bcaafba892a1");
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "9ada98e1-4054-4d9a-a591-0dfd20d4cea3");
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "b9aedc08-76f8-4017-9156-27180e377dca");
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "bd0d075f-663a-445f-8902-b555a09b1d2d");
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "c449f071-e14e-469e-affe-1c8b2269cc3f");
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "Ongs",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(string));
}
}
}
|
using System;
namespace RandomCards
{
class Program
{
static void Main(string[] args)
{
string[] rank = new string[13] { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };
string[] suit = new string[4] { "Clubs", "Diamonds", "Hearts", "Spades" };
Random rankRandom = new Random();
int newRank = rankRandom.Next(0, 12);
int newSuit = rankRandom.Next(0, 3);
Console.WriteLine(rank[newRank] + " of " + suit[newSuit]);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Commun
{
public class DirtyMaterialPaquet : Paquet
{
private int idTable;
private int quantity;
private string typeMaterial;
public DirtyMaterialPaquet(int idTable, string typeMaterial, int quantity) : base(TypePaquet.DirtyMaterial)
{
this.idTable = idTable;
this.TypeMaterial = typeMaterial;
this.Quantity = quantity;
}
public int IdTable { get => idTable; set => idTable = value; }
public int Quantity { get => quantity; set => quantity = value; }
public string TypeMaterial { get => typeMaterial; set => typeMaterial = value; }
}
}
|
using Ext.Net;
using Ext.Net.MVC;
using MusicaManager.Application.MusicLibrary.SongModule.Services;
using MusicManager.Application.MusicLibrary.DTO.SongModule;
using MusicManager.Presentation.ASPMVC.MusicLibrary.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MusicManager.Presentation.ASPMVC.MusicLibrary.Controllers
{
public class MusicController : Controller
{
readonly ISongService _songService;
//
// GET: /Music/
public MusicController(ISongService songService) {
_songService = songService;
}
public ActionResult Index()
{
return View(PlayListTreeModel.BuildTree());
}
[AcceptVerbs(HttpVerbs.Post)]
public RestResult Create(SongModel song)
{
try
{
var songDTO = _songService.AddNewSong(MaterializeSongDtoFromView(song));
return new RestResult
{
Success = true,
Message = "New song is added",
Data = MaterializeSongViewFromDTO(songDTO)
};
}
catch (Exception e)
{
return new RestResult
{
Success = false,
Message = e.Message
};
}
}
[AcceptVerbs(HttpVerbs.Get)]
public RestResult Read(string list)
{
try
{
List<SongDTO> songs=new List<SongDTO>();
if (String.Compare(list, "Music", true) == 0)
{
songs = _songService.FindSongs();
}
else {
songs = _songService.FindSongByGenere(list);
}
List<SongModel> listSong= new List<SongModel>();
if (songs != null && songs.Any())
{
foreach (var song in songs)
{
listSong.Add(MaterializeSongViewFromDTO(song));
}
}
return new RestResult
{
Success = true,
Data = listSong
};
}
catch (Exception e)
{
return new RestResult
{
Success = false,
Message = e.Message
};
}
}
[AcceptVerbs(HttpVerbs.Put)]
public RestResult Update(SongModel song)
{
try
{
_songService.UpdateSong(MaterializeSongDtoFromView(song));
return new RestResult
{
Success = true,
Message = "Song has been updated"
};
}
catch (Exception e)
{
return new RestResult
{
Success = false,
Message = e.Message
};
}
}
[AcceptVerbs(HttpVerbs.Delete)]
public RestResult Destroy(string id)
{
try
{
_songService.RemoveSong(Guid.Parse(id));
return new RestResult
{
Success = true,
Message = "Song has been deleted"
};
}
catch (Exception e)
{
return new RestResult
{
Success = false,
Message = e.Message
};
}
}
public ActionResult AllSongs(string node)
{
var p = new Ext.Net.MVC.PartialViewResult { ViewName = "AllSongs", ContainerId = "rightPanel", ClearContainer = true, RenderMode = RenderMode.AddTo};
p.ViewBag.List = node;
return p;
}
private SongDTO MaterializeSongDtoFromView(SongModel songModel)
{
SongDTO songDTO = new SongDTO();
songDTO.Id = songModel.Id == null ? Guid.Empty: Guid.Parse(songModel.Id) ;
songDTO.Title = songModel.Title;
songDTO.Genre = songModel.Genre;
songDTO.Author = songModel.Author;
songDTO.Album = songModel.Album;
return songDTO;
}
private SongModel MaterializeSongViewFromDTO(SongDTO songDTO)
{
SongModel songModel = new SongModel();
songModel.Id = songDTO.Id.ToString();
songModel.Title = songDTO.Title;
songModel.Genre = songDTO.Genre;
songModel.Author = songDTO.Author;
songModel.Album = songDTO.Album;
return songModel;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ManageDomain.Models
{
public class TaskVersion
{
public int VersionId { get; set; }
public int TaskId { get; set; }
public string VersionNo { get; set; }
public DateTime CreateTime { get; set; }
public string VersionInfo { get; set; }
public string DownloadUrl { get; set; }
public string Remark { get; set; }
}
}
|
using ClaimDi.DataAccess.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClaimDi.DataAccess.Object.WebConsumer
{
public class VerifyEmailModel
{
public string Message { get; set; }
}
public class ChangePasswordModel
{
public string AccId { get; set; }
public string TokenId { get; set; }
public string Username { get; set; }
public string NewPassword { get; set; }
public string ConfirmNewPassword { get; set; }
public string Message { get; set; }
}
}
|
using SupplianceStore.Domain.Abstract;
using SupplianceStore.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SupplianceStore.Domain.Concrete
{
public class EFProductRepository : IProductRepository , IReviewRepository
{
EFDbContext context = new EFDbContext();
public IEnumerable<Product> Products
{
get { return context.Products; }
}
public void SaveProduct(Product product)
{
if (product.ProductId == 0)
context.Products.Add(product);
else
{
Product dbEntry = context.Products.Find(product.ProductId);
if (dbEntry != null)
{
dbEntry.Name = product.Name;
dbEntry.Description = product.Description;
dbEntry.Price = product.Price;
dbEntry.Category = product.Category;
dbEntry.ImageData = product.ImageData;
dbEntry.ImageMimeType = product.ImageMimeType;
dbEntry.Discount = product.Discount;
}
}
context.SaveChanges();
}
public Product DeleteProduct(int productId)
{
Product dbEntry = context.Products.Find(productId);
if (dbEntry != null)
{
context.Products.Remove(dbEntry);
context.SaveChanges();
}
return dbEntry;
}
public IEnumerable<Review> Reviews { get { return context.Reviews; } }
public Review DeleteReview(int reviewId)
{
Review dbEntry = context.Reviews.Find(reviewId);
if (dbEntry != null)
{
context.Reviews.Remove(dbEntry);
context.SaveChanges();
}
return dbEntry;
}
public void SaveReview(Review review)
{
if (review.Id == 0)
context.Reviews.Add(review);
else
{
Review dbEntry = context.Reviews.Find(review.ProductId);
if (dbEntry != null)
{
dbEntry.Id = review.Id;
dbEntry.ProductId = review.ProductId;
dbEntry.Stars = review.Stars;
dbEntry.Description = review.Description;
dbEntry.Date = review.Date;
}
}
context.SaveChanges();
}
}
}
|
using Infrastructure.Database;
namespace Domain.Entitys
{
public partial class PayOrder : EntityBase
{
public decimal PayAmount { get; set; }
public string PayResult { get; set; }
public string OrderNo { 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 ProyectoBolera
{
public partial class MiniClientesForm : Form
{
public MiniClientesForm()
{
InitializeComponent();
}
private void TxtCedula_KeyPress(object sender, KeyPressEventArgs e)
{
Validacion.soloNumeros(sender, e);
}
private void TxtNombre_KeyPress(object sender, KeyPressEventArgs e)
{
Validacion.soloTexto(sender, e);
}
private void TxtApellido_KeyPress(object sender, KeyPressEventArgs e)
{
Validacion.soloTexto(sender, e);
}
private void TextBox2_KeyPress(object sender, KeyPressEventArgs e)
{
Validacion.soloNumeros(sender, e);
}
private void BtnRegistrar_Click(object sender, EventArgs e)
{
if (txtCedula.Text != "" && txtNombre.Text != "" && txtApellido.Text != "" && dateNacimiento.Text != "" && txtEmail.Text != "" && txtTelefono.Text != "")
{
if (Validacion.emailValid(txtEmail.Text))
{
registrarCliente();
}
else {
MessageBox.Show("Correo no valido");
}
}
else {
MessageBox.Show("Aun hay compos sin completar");
}
}
private void registrarCliente()
{
string queryCount = String.Format($"SELECT COUNT(*) FROM clientes WHERE idcliente = '{txtCedula.Text}'");
if (!Validacion.validarSiExisteRegistro(queryCount))
{
string query = String.Format($"INSERT INTO clientes VALUES ('{txtCedula.Text}','{txtNombre.Text}','{txtApellido.Text}','{dateNacimiento.Value.ToString()}','{txtEmail.Text}',{txtTelefono.Text})");
Conexion.getQuery(query);
MessageBox.Show("Registro Existoso");
limpiarFormulario();
}
else
{
MessageBox.Show("La cedula ya se encuentra registrada en la base de datos");
}
}
private void limpiarFormulario() {
txtCedula.Text = "";
txtNombre.Text = "";
txtApellido.Text = "";
dateNacimiento.Text = "";
txtEmail.Text = "";
txtTelefono.Text = "";
}
}
}
|
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var shops = new SortedDictionary<string, Dictionary<string, decimal>>();
while (true)
{
var line = Console.ReadLine();
if (line == "Revision")
{
break;
}
var productParts = Console.ReadLine().Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
var shop = productParts[0];
var product = productParts[1];
var price = decimal.Parse(productParts[2]);
if (!shops.ContainsKey(shop))
{
shops[shop] = new Dictionary<string, decimal>();
}
var products = shops[shop];
products[product] = price;
//shops[shop][product]=price;
}
foreach (var kvp in shops)
{
var shop = kvp.Key;
var products = kvp.Value;
Console.WriteLine($"{shop}->");
foreach (var productkvp in products)
{
Console.WriteLine($"Product: {productkvp.Key}, Price: {productkvp.Value:F1}");
}
}
}
}
}
|
// <copyright file="IndexDataOfCharStrings.cs" company="WaterTrans">
// © 2020 WaterTrans
// </copyright>
namespace WaterTrans.GlyphLoader.Internal.OpenType.CFF
{
/// <summary>
/// The Compact FontFormat Specification CharStrings INDEX.
/// </summary>
internal class IndexDataOfCharStrings : IndexData
{
/// <summary>
/// Initializes a new instance of the <see cref="IndexDataOfCharStrings"/> class.
/// </summary>
/// <param name="reader">The <see cref="TypefaceReader"/>.</param>
internal IndexDataOfCharStrings(TypefaceReader reader)
: base(reader)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.Favorites.Maps;
using Welic.Dominio.Patterns.Service.Pattern;
namespace Welic.Dominio.Models.Favorites.Services
{
public interface IFavoriteService : IService<FavoriteMaps>
{
}
}
|
using UnityEngine;
using System.Collections;
public class VideoGameManager : MonoBehaviour {
public int togo;
private float time;
// Update is called once per frame
void Start ()
{
time = 0f;
}
void FixedUpdate () {
time += Time.deltaTime;
if (time >= 2f) //Tiempo para iniciar trancisión
GameObject.Find ("Out2").GetComponent<Inventory> ().fadeoff ();
if (time > 24f) //Tiempo para pasar a otra escena
{
GeneralGameManager.advance++;
if (togo == 13)//8 TO DO
GeneralGameManager.advance = 20;
Application.LoadLevel (togo);
}
}
}
|
using System.Collections.Generic;
public class TaskSpec
{
public TaskSpec(string name)
{
this.Name = name;
this.Children = new List<TaskSpec>(0);
this.Args = new Dictionary<string, string>();
}
public string Name { get; }
public IList<TaskSpec> Children { get; }
public IDictionary<string, string> Args { get; }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HotelManagement.DataObject;
using System.Windows.Forms;
using System.Data;
namespace HotelManagement.Controller
{
public class ThietBiControl
{
ThietBiData data = new ThietBiData();
public void HienThi(DataGridView dgv, BindingNavigator bn)
{
BindingSource bs = new BindingSource();
bs.DataSource = data.LayMaThietBi();
dgv.DataSource = bs;
bn.BindingSource = bs;
}
public DataRow NewRow()
{
return this.data.NewRow();
}
public void Add(DataRow row)
{
this.data.Add(row);
}
public bool Save()
{
return this.data.Save();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Foundation : MonoBehaviour, ICell
{
public GameObject highlight;
public int suit;
private List<Card> cards = new List<Card>();
public void DropCardInCell(Card card)
{
cards.Add(card);
card.isFrontCard = true;
card.transform.SetParent(transform);
card.transform.localPosition = Vector3.zero;
StopHighlight();
if (cards.Count == 13)
{
GameManager.inst.CheckIfAllFoundationsComplete();
}
}
public Card GetFrontCard()
{
if (cards.Count > 0)
{
return cards[cards.Count - 1];
}
return null;
}
public void Highlight()
{
highlight.SetActive(true);
}
public void StopHighlight()
{
highlight.SetActive(false);
}
public bool IsInCardDropDistance(Card card)
{
return Vector3.Distance(card.transform.position, transform.position) < Card.DROP_DISTANCE;
}
public bool IsPotentialCardDrop(Card card)
{
if (card.GetSuit() == suit)
{
if (GetFrontCard() == null && card.GetNumber() == 1)
{
return true;
}
else if (GetFrontCard() != null && card.GetNumber() == GetFrontCard().GetNumber()+1)
{
return true;
}
}
return false;
}
public void RemoveFrontCard()
{
cards.RemoveAt(cards.Count - 1);
Card front = GetFrontCard();
if (front != null)
{
front.isFrontCard = true;
}
}
public bool IsComplete()
{
return cards.Count == 13;
}
}
|
using Android.App;
using Android.OS;
using Android.Widget;
using SmartHome.Service.Response;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using SmartHome.Util;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using Android.Content;
using System.IO;
using SmartHome.Service;
using System.Threading;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using SmartHome.Model;
using SmartHome.Droid.Fragments;
namespace SmartHome.Droid.Activities
{
[Activity(Label = "LoginActivity", MainLauncher = true)]
public class LoginActivity : Activity
{
#region Parameter
static CountdownEvent countdown;
static int upCount = 0;
static object lockObj = new object();
bool resolveNames = true, isCheckController = false;
EditText txtUsr, txtPw;
#endregion
protected override async void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.Login);
//Get control
txtUsr = FindViewById<EditText>(Resource.Id.txtUsr);
txtPw = FindViewById<EditText>(Resource.Id.txtPw);
//Set default
txtUsr.Text = "magnetdev";
txtPw.Text = "12345";
string token = "test";
//Search ip của conller
//await IsCheckController();
//Event login
Button btnLogin = FindViewById<Button>(Resource.Id.btnLogin);
btnLogin.Click += BtnLogin_Click;
ImageView imgScan = FindViewById<ImageView>(Resource.Id.imgScan);
imgScan.Click += ImgScan_Click;
}
private void ImgScan_Click(object sender, EventArgs e)
{
FragmentTransaction fragmentTransaction = FragmentManager.BeginTransaction();
Fragment fragmentPrev = FragmentManager.FindFragmentByTag("dialog");
if (fragmentPrev != null)
fragmentTransaction.Remove(fragmentPrev);
fragmentTransaction.AddToBackStack(null);
//create and show the dialog
ScanIPFragment dialogFragment = ScanIPFragment.NewInstance(null);
dialogFragment.Show(fragmentTransaction, "dialog");
}
private async void BtnLogin_Click(object sender, EventArgs e)
{
await GetLoginByUsr(txtUsr.Text, txtPw.Text);
}
private async Task<LoginResponse> GetLoginByUsr(string usr, string pw)
{
LoginResponse loginObject = null;
try
{
//Search ip của conller
// await IsCheckController();
loginObject = await APIManager.GetUserByUsrAndPw(usr, pw);
if (loginObject != null)
{
// start the HomeActivity
StartActivity(new Intent(Application.Context, typeof(HomeActivity)));
//MainPage = new MasterDetailPage
//{
// Master = new MasterPage(),
// Detail = new NavigationPage(new HousePage())
//};
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
return loginObject;
}
private async Task<bool> IsCheckController()
{
//bool result = false;
System.Collections.ArrayList arr = new System.Collections.ArrayList();
System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
for (int i = 1; i <= 253; i++)
{
IAsyncResult iaResult = client.BeginConnect("192.168.0." + i.ToString(), 3000, null, null);
iaResult.AsyncWaitHandle.WaitOne(200, false);
if (client.Connected)
{
isCheckController = await APIManager.GetHello("192.168.0." + i);
if (isCheckController)
{
arr.Add("192.168.0." + i);
}
break;
}
}
return isCheckController;
}
}
} |
using SimplySqlSchema.Query;
namespace SimplySqlSchema.MySql
{
public class MySqlQuerier : SchemaQuerier
{
public override BackendType Backend => BackendType.MySql;
}
}
|
using System.Collections.Generic;
using SelectionCommittee.BLL.DataTransferObject;
namespace SelectionCommittee.WEB.Models
{
public class DisplayHome
{
public IEnumerable<FacultyDTO> FacultiesDTO { set; get; }
}
} |
using System;
namespace EmailChecker
{
class Program
{
public static bool IsEmailAddress(string emailAddress){
int iAt = emailAddress.IndexOf('@'); //@ suchen, ob drin und position und in iAt abspeichern, index von vorne gezählt
int iDot = emailAddress.LastIndexOf('.'); // . suchen, index von hinten gezählt
return (iAt > 0 && iDot > iAt);
}
static void TestIsEmailAddress(string emailAddress, bool expected){
bool result = IsEmailAddress(emailAddress);
if (result == expected){
Console.WriteLine("TEST PASSED - " + emailAddress +" is valid? -> " + expected);
}else{
Console.WriteLine("TEST FAILED - " + emailAddress + " results in: " + result + "; expected: " + expected);
}
}
static void Main(string[] args)
{
/*if (IsEmailAddress("irgendwas@web.de")){
Console.WriteLine("TEST PASSED - irgendwas@web.de is a valid email address.");
}else{
Console.WriteLine("TEST FAILED - irgendwas@web.de is not a valid email address.");
} //wurde zu eigener Methode*/
TestIsEmailAddress("irgwas@web.de", true);
TestIsEmailAddress("@web.de", false);
TestIsEmailAddress("test@eins.zwei.de", true);
TestIsEmailAddress("a.b@eins.zwei.de", true);
TestIsEmailAddress("a@.", false);
/*Console.WriteLine(IsEmailAddress("@web.de"));
Console.WriteLine(IsEmailAddress("@eins.zwei.de"));
Console.WriteLine(IsEmailAddress(".@eins.zwei.de"));
Console.WriteLine(IsEmailAddress("irgwaswas@.de"));
Console.WriteLine(IsEmailAddress("a@.")); //1. Aufrufversuch*/
}
}
}
|
using System;
using KeepTeamAutotests;
using KeepTeamAutotests.Model;
using NUnit.Framework;
using KeepTeamAutotests.AppLogic;
namespace KeepTeamTests
{
[TestFixture()]
public class CandidateScreenTests : ImagePopupTests
{
[SetUp]
public void Login()
{
app.userHelper
.loginAs(app.userHelper.getUserByRole("aCandidatesRW"));
}
[Test()]
public void Compare_Image_Candidate()
{
//клик по кнопке добавления кандидатов
app.userHelper.clickAddCandidateButton();
//Проверка соответствия скриншотов
Assert.IsTrue(app.screenHelper.NewCandidatePopupScreen());
}
[Test()]
public void Compare_Image_Candidate_Resume()
{
//клик по кнопке добавления кандидатов
app.userHelper.clickAddCandidateButton();
//переход на вкладку резюме
app.userHelper.clickTabByName("Резюме");
//Проверка соответствия скриншотов
Assert.IsTrue(app.screenHelper.NewCandidatePopupResumeScreen());
}
[Test()]
public void Compare_Image_Candidate_Comments()
{
//клик по кнопке добавления кандидатов
app.userHelper.clickAddCandidateButton();
//переход на вкладку комментариев
app.userHelper.clickTabByName("Комментарии");
//Проверка соответствия скриншотов
Assert.IsTrue(app.screenHelper.NewCandidatePopupCommentsScreen());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace MGcomponentsWPF.Dialogs
{
interface Dialog
{
}
}
|
using SciVacancies.Domain.Enums;
using SciVacancies.WebApp.ViewModels.Base;
using System.Collections.Generic;
namespace SciVacancies.WebApp.ViewModels
{
public class OrganizationDetailsViewModel : PageViewModelBase
{
public OrganizationDetailsViewModel()
{
Title = "Карточка организации";
}
#region General
/// <summary>
/// Полное наименование
/// </summary>
public string Name { get; set; }
/// <summary>
/// Сокращенное наименование
/// </summary>
public string ShortName { get; set; }
/// <summary>
/// Почтовый адрес
/// </summary>
public string Address { get; set; }
/// <summary>
/// E-mail
/// </summary>
public string Email { get; set; }
/// <summary>
/// ИНН
/// </summary>
public string INN { get; set; }
/// <summary>
/// ОГРН
/// </summary>
public string OGRN { get; set; }
/// <summary>
/// Имя руководителя
/// </summary>
public string HeadFirstName { get; set; }
/// <summary>
/// Фамилия руководителя
/// </summary>
public string HeadSecondName { get; set; }
/// <summary>
/// Отчество руководителя
/// </summary>
public string HeadPatronymic { get; set; }
/// <summary>
/// Логотип организации
/// </summary>
public string ImageName { get; set; }
public long? ImageSize { get; set; }
public string ImageExtension { get; set; }
public string ImageUrl { get; set; }
#endregion
#region Dictionaries
/// <summary>
/// Наименование ФОИВ
/// </summary>
public string Foiv { get; set; }
/// <summary>
/// Идентификатор ФОИВ
/// </summary>
public int FoivId { get; set; }
/// <summary>
/// Наименование организационно-правовой формы
/// </summary>
public string OrgForm { get; set; }
/// <summary>
/// Идентификатор организационно-правовой формы
/// </summary>
public int OrgFormId { get; set; }
/// <summary>
/// Список идентификаторов отраслей науки
/// </summary>
public List<int> ResearchDirectionIds { get; set; }
#endregion
public OrganizationStatus Status { get; set; }
public VacanciesInOrganizationIndexViewModel VacanciesInOrganization { get; set; }
}
}
|
using ISE.Framework.Common.Aspects;
using Router.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace ISE.SM.Service.WindowsHost
{
public class SMWindowsService:ServiceBase
{
ServiceHostDecorator AuthenticationServiceHost ;
ServiceHostDecorator AuthorizationServiceHost ;
ServiceHostDecorator GroupServiceHost ;
ServiceHostDecorator ManagementServiceHost ;
ServiceHostDecorator MembershipProviderServiceHost ;
ServiceHostDecorator PermissionServiceHost ;
ServiceHostDecorator ResourceServiceHost ;
ServiceHostDecorator RoleServiceHost ;
ServiceHostDecorator SecurityUserServiceHost ;
ServiceHostDecorator DataServiceHost ;
ServiceHostDecorator ApplicationDomainServiceHost ;
ServiceHostDecorator OperationServiceHost ;
ServiceHostDecorator SecurityCompanyHost ;
public SMWindowsService()
{
this.InitializeComponent();
}
protected override void OnStart(string[] args)
{
if (AuthenticationServiceHost != null)
{
AuthenticationServiceHost.Close();
}
if (AuthorizationServiceHost != null)
{
AuthorizationServiceHost.Close();
}
if (GroupServiceHost != null)
{
GroupServiceHost.Close();
}
if (ManagementServiceHost != null)
{
ManagementServiceHost.Close();
}
if (MembershipProviderServiceHost != null)
{
MembershipProviderServiceHost.Close();
}
if (PermissionServiceHost != null)
{
PermissionServiceHost.Close();
}
if (ResourceServiceHost != null)
{
ResourceServiceHost.Close();
}
if (RoleServiceHost != null)
{
RoleServiceHost.Close();
}
if (SecurityUserServiceHost != null)
{
SecurityUserServiceHost.Close();
}
if (DataServiceHost != null)
{
DataServiceHost.Close();
}
if (ApplicationDomainServiceHost != null)
{
ApplicationDomainServiceHost.Close();
}
if (OperationServiceHost != null)
{
OperationServiceHost.Close();
}
if (SecurityCompanyHost != null)
{
SecurityCompanyHost.Close();
}
AuthenticationServiceHost = new ServiceHostDecorator(typeof(AuthenticationService));
AuthorizationServiceHost = new ServiceHostDecorator(typeof(AuthorizationService));
GroupServiceHost = new ServiceHostDecorator(typeof(GroupService));
ManagementServiceHost = new ServiceHostDecorator(typeof(ManagementService));
MembershipProviderServiceHost = new ServiceHostDecorator(typeof(MembershipProviderService));
PermissionServiceHost = new ServiceHostDecorator(typeof(PermissionService));
ResourceServiceHost = new ServiceHostDecorator(typeof(ResourceService));
RoleServiceHost = new ServiceHostDecorator(typeof(RoleService));
SecurityUserServiceHost = new ServiceHostDecorator(typeof(SecurityUserService));
DataServiceHost = new ServiceHostDecorator(typeof(DataService));
ApplicationDomainServiceHost = new ServiceHostDecorator(typeof(ApplicationDomainService));
OperationServiceHost = new ServiceHostDecorator(typeof(OperationService));
SecurityCompanyHost = new ServiceHostDecorator(typeof(SecurityCompanyService));
try
{
LogManager.GetLogger().Info("Service Opened.");
RoleServiceHost.Open();
AuthenticationServiceHost.Open();
AuthorizationServiceHost.Open();
GroupServiceHost.Open();
ManagementServiceHost.Open();
MembershipProviderServiceHost.Open();
PermissionServiceHost.Open();
ResourceServiceHost.Open();
SecurityUserServiceHost.Open();
DataServiceHost.Open();
ApplicationDomainServiceHost.Open();
OperationServiceHost.Open();
SecurityCompanyHost.Open();
//******************************************************************
}
catch (Exception ex)
{
// log exception
LogManager.GetLogger().Error(ex);
}
}
protected override void OnStop()
{
if (AuthenticationServiceHost != null)
{
AuthenticationServiceHost.Close();
AuthenticationServiceHost = null;
}
if (AuthorizationServiceHost != null)
{
AuthorizationServiceHost.Close();
AuthorizationServiceHost = null;
}
if (GroupServiceHost != null)
{
GroupServiceHost.Close();
GroupServiceHost = null;
}
if (ManagementServiceHost != null)
{
ManagementServiceHost.Close();
ManagementServiceHost = null;
}
if (MembershipProviderServiceHost != null)
{
MembershipProviderServiceHost.Close();
MembershipProviderServiceHost = null;
}
if (PermissionServiceHost != null)
{
PermissionServiceHost.Close();
PermissionServiceHost = null;
}
if (ResourceServiceHost != null)
{
ResourceServiceHost.Close();
ResourceServiceHost = null;
}
if (RoleServiceHost != null)
{
RoleServiceHost.Close();
RoleServiceHost = null;
}
if (SecurityUserServiceHost != null)
{
SecurityUserServiceHost.Close();
SecurityUserServiceHost = null;
}
if (DataServiceHost != null)
{
DataServiceHost.Close();
DataServiceHost = null;
}
if (ApplicationDomainServiceHost != null)
{
ApplicationDomainServiceHost.Close();
ApplicationDomainServiceHost = null;
}
if (OperationServiceHost != null)
{
OperationServiceHost.Close();
OperationServiceHost = null;
}
if (SecurityCompanyHost != null)
{
SecurityCompanyHost.Close();
SecurityCompanyHost = null;
}
LogManager.GetLogger().Info("Service Closed.");
}
private void InitializeComponent()
{
//
// SMWindowsService
//
this.ServiceName = "SMWindowsService";
}
}
}
|
namespace TeamCityChangeNotifier.Helpers
{
public static class UriPath
{
public static string Combine(string baseUri, string rest)
{
if (string.IsNullOrEmpty(baseUri))
{
return rest;
}
if (string.IsNullOrEmpty(rest))
{
return baseUri;
}
bool baseHasTrailingSlash = baseUri.EndsWith("/");
bool restHasLeadingSlash = rest.StartsWith("/");
if (baseHasTrailingSlash && restHasLeadingSlash)
{
return baseUri.Substring(0, baseUri.Length - 1) + rest;
}
if (baseHasTrailingSlash || restHasLeadingSlash)
{
return baseUri + rest;
}
return baseUri + "/" + rest;
}
public static string Combine(string baseUri, string part1, string part2)
{
return Combine(Combine(baseUri, part1), part2);
}
public static string Combine(string baseUri, string part1, string part2, string part3)
{
return Combine(Combine(baseUri, part1), Combine(part2, part3));
}
}
} |
using gView.Framework.system;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gView.Framework.UI.Dialogs
{
public enum ProgressMode { ProgressBar, ProgressDisk }
/// <summary>
/// Zusammenfassung für FormTaskProgress.
/// </summary>
public class FormTaskProgress : System.Windows.Forms.Form, IProgressTaskDialog
{
private System.Windows.Forms.Label labelMessage;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Label labelProgress;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Timer timer1;
private System.ComponentModel.IContainer components;
private Task _task = null;
private gView.Framework.UI.Controls.ProgressDisk progressDisk1;
private ICancelTracker _cancelTracker = null;
private Panel panelTime;
private Label lblTime;
private Label label1;
private ProgressMode _mode = ProgressMode.ProgressBar;
private DateTime startTime;
public FormTaskProgress()
{
InitializeComponent();
}
public FormTaskProgress(Task task)
{
InitializeComponent();
btnCancel.Visible = false;
_task = task;
}
public FormTaskProgress(IProgressReporter reporter, Task task)
: this(task)
{
_cancelTracker = reporter.CancelTracker;
btnCancel.Visible = (_cancelTracker != null);
if (reporter != null)
{
reporter.ReportProgress += new ProgressReporterEvent(HandleProgressEvent);
}
}
#region IProgressDialog Member
public void ShowProgressDialog(IProgressReporter reporter, Task task)
{
_task = task;
if (_task == null)
{
return;
}
if (reporter != null)
{
_cancelTracker = reporter.CancelTracker;
btnCancel.Visible = (_cancelTracker != null);
reporter.ReportProgress += new ProgressReporterEvent(HandleProgressEvent);
}
this.ShowDialog();
}
public bool UserInteractive
{
get { return SystemInformation.UserInteractive; }
}
#endregion
/// <summary>
/// Die verwendeten Ressourcen bereinigen.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
public ProgressMode Mode
{
get { return _mode; }
set
{
switch (value)
{
case ProgressMode.ProgressBar:
progressBar1.Visible = true;
progressDisk1.Visible = false;
progressDisk1.Stop();
break;
case ProgressMode.ProgressDisk:
progressBar1.Visible = false;
progressDisk1.Visible = true;
progressDisk1.Start(100);
break;
}
_mode = value;
}
}
public void HandleProgressEvent(object report)
{
try
{
if (report is ProgressReport)
{
labelMessage.Text = ((ProgressReport)report).Message;
if (((ProgressReport)report).featureMax != -1)
{
if (_mode == ProgressMode.ProgressBar)
{
if (progressBar1.Visible == false)
{
progressBar1.Visible = true;
}
labelProgress.Text = ((ProgressReport)report).featurePos + "/" + ((ProgressReport)report).featureMax;
if (((ProgressReport)report).featureMax > progressBar1.Value &&
progressBar1.Value != 0)
{
progressBar1.Value = 0;
}
if (((ProgressReport)report).featureMax != progressBar1.Maximum &&
progressBar1.Maximum != ((ProgressReport)report).featureMax)
{
progressBar1.Maximum = ((ProgressReport)report).featureMax;
}
if (progressBar1.Value != ((ProgressReport)report).featurePos)
{
progressBar1.Value = ((ProgressReport)report).featurePos;
}
if (((ProgressReport)report).featureMax > 0)
{
double percent = ((ProgressReport)report).featurePos / (double)((ProgressReport)report).featureMax;
this.Text = ((int)(percent * 100.0)).ToString() + " %";
if (percent > 0.0)
{
if (panelTime.Visible == false)
{
panelTime.Visible = true;
}
TimeSpan ts = DateTime.Now - startTime;
double minutes = ts.TotalMinutes / percent - ts.TotalMinutes;
if (minutes > 60)
{
int h = (int)minutes / 60;
lblTime.Text = h.ToString() + "h " + ((int)minutes - h * 60).ToString() + "min";
}
else
{
lblTime.Text = ((int)minutes).ToString() + "min";
}
}
}
}
else
{
labelProgress.Text = ((ProgressReport)report).featurePos.ToString();
}
}
else
{
progressBar1.Visible = false;
labelProgress.Text = ((ProgressReport)report).featurePos.ToString();
}
}
this.Refresh();
}
catch
{
}
}
#region Vom Windows Form-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormTaskProgress));
this.labelMessage = new System.Windows.Forms.Label();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.labelProgress = new System.Windows.Forms.Label();
this.btnCancel = new System.Windows.Forms.Button();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.progressDisk1 = new gView.Framework.UI.Controls.ProgressDisk();
this.panelTime = new System.Windows.Forms.Panel();
this.lblTime = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.panelTime.SuspendLayout();
this.SuspendLayout();
//
// labelMessage
//
resources.ApplyResources(this.labelMessage, "labelMessage");
this.labelMessage.Name = "labelMessage";
//
// progressBar1
//
resources.ApplyResources(this.progressBar1, "progressBar1");
this.progressBar1.Name = "progressBar1";
this.progressBar1.Step = 1;
//
// labelProgress
//
resources.ApplyResources(this.labelProgress, "labelProgress");
this.labelProgress.Name = "labelProgress";
//
// btnCancel
//
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// progressDisk1
//
resources.ApplyResources(this.progressDisk1, "progressDisk1");
this.progressDisk1.ActiveForeColor1 = System.Drawing.Color.Red;
this.progressDisk1.ActiveForeColor2 = System.Drawing.Color.Coral;
this.progressDisk1.BlockSize = gView.Framework.UI.Controls.BlockSize.Large;
this.progressDisk1.Name = "progressDisk1";
this.progressDisk1.SquareSize = 170;
//
// panelTime
//
resources.ApplyResources(this.panelTime, "panelTime");
this.panelTime.Controls.Add(this.lblTime);
this.panelTime.Controls.Add(this.label1);
this.panelTime.Name = "panelTime";
//
// lblTime
//
resources.ApplyResources(this.lblTime, "lblTime");
this.lblTime.Name = "lblTime";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// FormTaskProgress
//
resources.ApplyResources(this, "$this");
this.ControlBox = false;
this.Controls.Add(this.panelTime);
this.Controls.Add(this.progressDisk1);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.labelProgress);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.labelMessage);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "FormTaskProgress";
this.Shown += new System.EventHandler(this.FormTaskProgress_Shown);
this.panelTime.ResumeLayout(false);
this.panelTime.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private void timer1_Tick(object sender, System.EventArgs e)
{
if (_task == null || _task.IsCompleted)
{
this.Close();
}
}
private void FormTaskProgress_Shown(object sender, EventArgs e)
{
startTime = DateTime.Now;
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
}
private void btnCancel_Click(object sender, EventArgs e)
{
btnCancel.Enabled = false;
if (_cancelTracker == null)
{
return;
}
_cancelTracker.Cancel();
}
}
}
|
using BuiltCodeWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BuiltCodeWeb.Repository.IRepository
{
public interface IDoctorRepository : IRepository<Doctor>
{
}
}
|
using fileCrawlerWPF.Media;
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
namespace fileCrawlerWPF.Controls.model
{
public class FileInformation_ViewModel
: INotifyPropertyChanged
{
private ProbeFile _file;
public event PropertyChangedEventHandler PropertyChanged;
public FileInformation_ViewModel()
{
}
public FileInformation_ViewModel(ProbeFile pf)
=> _file = pf;
public ProbeFile ProbeFile
{
get => _file;
set
{
_file = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Enabled)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FileName)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Resolution)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Directory)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FrameRate)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(VideoCodec)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(AudioCodec)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Size)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Hash)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Image)));
}
}
public async Task CalculateHash()
{
await _file?.ComputeHashAsync();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Hash)));
}
public bool Enabled => _file != null;
public Guid ID => _file.ID;
public string FileName => _file?.Name;
public string Resolution => _file?.Resolution;
public string Directory => _file?.Directory;
public string FrameRate => $"{_file?.FrameRate}";
public string VideoCodec => _file?.VideoCodec;
public string AudioCodec => _file?.AudioCodec;
public string Size => _file?.FileSize;
public string Hash => _file?.HashAsHex;
public BitmapSource Image => _file?.GetThumbnail();
public static bool operator == (FileInformation_ViewModel left, FileInformation_ViewModel right)
=> left?._file == right?._file;
public static bool operator !=(FileInformation_ViewModel left, FileInformation_ViewModel right)
=> left?._file != right?._file;
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
/// Author: Corwin Belser
/// Controller to patrol, chase players, and horde mementos
[RequireComponent(typeof(NavMeshAgent))]
public class EnemyController : MonoBehaviour {
public enum EnemyState
{
Idle,
Patrolling,
TargetingPlayer,
TargetingMemento,
TransportingMemento
}
private EnemyState _enemyState; /* The current state enemy is in */
private EnemyState _previousState; /* Previous state enemy was in. Used to resume a patrol after idling */
/****************************** Player Detection ******************************/
public float FOV_CONE_LENGTH = 10.0f; /* Maximum distance raycast should travel */
public float FOV_CONE_RADIUS = 30.0f; /* Maximum angle between enemy's forward vector and the player */
public float FOV_RADIUS = 3.0f; /* Radius around enemy to detect player */
public Color TARGETING_PLAYER_COLOR; /* Color of the vision light when the enemy is targeting the player */
private Color _neutralColor; /* Color of the vision light by default */
public AudioClip TARGETING_PLAYER_AUDIO; /* Audio clip to play when targeting the player */
private AudioClip _neutralAudio; /* Default audio clip */
private GameObject _player; /* Reference to the player gameObject */
private float _timeOnTargetPlayer; /* Time in seconds since game start that TargetingPlayer state was last entered */
/******************************* Patrol Settings ******************************/
public float MIN_DISTANCE = 0.5f; /* Minimun distance before moving to next patrol point */
public int PATROL_GROUP = 0; /* AI will only follow patrols in the assigned group */
public PatrolPoint PATROL_START; /* Starting Patrol Point */
private PatrolPoint _patrolCurrent; /* The current patrol point */
/******************************* Memento Settings ******************************/
public float SPEED_DEFAULT = 5f;
public float SPEED_TARGETING_PLAYER = 8f;
public Nest NEST; /* Nest to take found mementos to */
private Memento _memento = null; /* Reference to the memento being held, if one exists */
/***************************** Movement Settings ******************************/
public float ENEMY_IDLE_TIME = 2.0f; /* How long enemies should pause after losing track of the player or memento, or reaching a patrol point */
public float MEMENTO_SEARCH_RADIUS = 5.0f; /* Radius around enemy to detect dropped mementos */
public float DELAY_BEFORE_TAKING_FROM_LINKED_NEST = 15.0f; /* Time to wait after a memento enters a linked nest before trying to steal it */
private float _timeOnEnterIdle; /* Time in seconds since game start that Idle state was last entered */
/*************************** GameObject Components ****************************/
private NavMeshAgent _navAgent;
private PatrolManager _patrolManager;
private MementoUtils _mementoUtils;
private GameInfo _gameInfo;
private Animator _animator;
[HideInInspector]
public Light visionLight;
private AudioSource _audioSource;
/// <summary> Initializes required components </summary>
void Start () {
_navAgent = GetComponent<NavMeshAgent>();
_audioSource = GetComponent<AudioSource>();
_animator = GetComponentInChildren<Animator>();
_neutralAudio = _audioSource.clip;
_player = GameObject.FindGameObjectWithTag("Player");
_patrolManager = GameObject.Find("GameManager").GetComponent<PatrolManager>();
_mementoUtils = GameObject.Find("GameManager").GetComponent<MementoUtils>();
_gameInfo = GameObject.Find("GameManager").GetComponent<GameInfo>();
_timeOnEnterIdle = Time.time;
_timeOnTargetPlayer = Time.time;
if (PATROL_START != null) {
/* Initialize patrol start point */
_navAgent.SetDestination(PATROL_START.transform.position);
_patrolCurrent = PATROL_START;
ChangeState(EnemyState.Patrolling);
} else {
Debug.Log("<color=blue>AI Warning: This AI does not have a patrol set! (" + gameObject.name + ")</color>");
}
//Find and store a reference to the vision light
Light[] lights = gameObject.GetComponentsInChildren<Light>();
foreach (Light light in lights)
{
if (light.tag == "EnemyVisionLight")
visionLight = light;
}
if (visionLight != null)
{
visionLight.range = FOV_CONE_LENGTH;
visionLight.spotAngle = FOV_CONE_RADIUS;
_neutralColor = visionLight.color;
}
}
/// <summary> Update is called once per frame </summary>
void Update ()
{
/*
Check for state changes
(Priority) <condition> -> <state to move to>
All States EXCEPT Idle:
(P1) See Player -> Targeting Player
Idle:
(P1) Time passed && See Player -> Targeting Player
(P2) Time passed && Nearby Memento -> Targeting Memento
(P3) Time passed -> Patrolling
Patrolling:
(P2) Pulse Nearby && Memento Point Empty -> Targeting Memento
(P3) Memento Point Empty && Linked Memento Point full -> Targeting Memento
(P3) Destination Reached -> Patrolling (next patrol point)
Targeting Player:
(P2) Destination Reached -> Patrolling
Targeting Memento:
(P2) Collision With Memento -> Transporting Memento
(P3) Destination Reached -> Patrolling
Transporting Memento:
(P2) Collision With Memento Point -> Patrolling
*/
if (CanSeePlayer() && (_enemyState != EnemyState.Idle || Time.time - _timeOnTargetPlayer >= ENEMY_IDLE_TIME))
SetTargetToPlayer();
else
{
switch (_enemyState)
{
case EnemyState.Idle:
if (Time.time - _timeOnEnterIdle >= ENEMY_IDLE_TIME)
{
if (!CheckMemento())
{
if (_previousState == EnemyState.Patrolling)
SetTargetToNextPatrolPoint();
else
SetTargetToNearestPoint();
}
}
break;
case EnemyState.Patrolling:
if (!CheckMemento() && !_navAgent.pathPending && _navAgent.remainingDistance < MIN_DISTANCE)
ChangeState(EnemyState.Idle);
break;
case EnemyState.TransportingMemento:
if (_navAgent.remainingDistance < MIN_DISTANCE)
{
_memento.Release();
_memento = null;
SetTargetToNearestPoint();
}
break;
case EnemyState.TargetingPlayer:
if (!_navAgent.pathPending && _navAgent.remainingDistance < MIN_DISTANCE)
{
ChangeState(EnemyState.Idle);
//Debug.Log("<color=blue>AI: Lost player. Entering Idle</color>");
}
break;
case EnemyState.TargetingMemento:
if (!_navAgent.pathPending && _navAgent.remainingDistance < MIN_DISTANCE)
{
ChangeState(EnemyState.Idle);
}
break;
default:
if (!_navAgent.pathPending && _navAgent.remainingDistance < MIN_DISTANCE)
{
//SetTargetToNearestPoint();
ChangeState(EnemyState.Idle); // CB: Enter idle for a bit after reaching a destination
}
break;
}
}
}
/// <summary>
/// Handles state changes related to mementos
///
/// If this enemy's nest is empty, it checks nearby for any abandoned mementos.
/// If a memento is found, it changes the enemy state to TrackingMemento and
/// sets the navAgent's destination
/// If this enemy's nest is empty, and it's linked to another nest that does
/// have a memento, it changes the enemy state to TargetingMemento and sets
/// the navAgent's destination
/// </summary>
/// <return> true if the enemy state was changed, false otherwise </return>
/// <thoughts>
/// This method is called Check, but it does more than that, and it shouldn't.
/// TODO: Break the contents of this function into two pieces:
/// AttemptStateChange()
/// ProcessStateChange()
/// </thoughts>
private bool CheckMemento()
{
if (NEST != null && NEST.MEMENTO == null)
{
//Check for any memento's out of Nests
GameObject memento = _mementoUtils.GetClosestMemento (transform.position);
Memento mc = memento.GetComponent<Memento> ();
if (mc != null && Vector3.Distance(mc.transform.position, transform.position) <= MEMENTO_SEARCH_RADIUS && mc.GetHeldBy () == Memento.HeldBy.None && !mc.IN_NEST)
{
//Debug.Log("<color=blue>AI Debug: State Change: Patrolling -> TargetingMemento (nearby)</color>");
ChangeState(EnemyState.TargetingMemento);
_navAgent.SetDestination (memento.transform.position);
return true;
}
else if (NEST != null && NEST.NEST_TO_TAKE_FROM != null && NEST.NEST_TO_TAKE_FROM.MEMENTO != null && Time.time - NEST.TIME_MEMENTO_ENTERED >= DELAY_BEFORE_TAKING_FROM_LINKED_NEST)
{
//Debug.Log("<color=blue>AI Debug: State Change: Patrolling -> TargetingMemento (other nest)</color>");
ChangeState(EnemyState.TargetingMemento);
_navAgent.SetDestination(NEST.NEST_TO_TAKE_FROM.MEMENTO.transform.position);
return true;
}
}
return false;
}
/// <summary>
/// Handles the collision check with the memento, picking it up and
/// changing the enemy state to TransportingMemento
/// </summary>
/// <param name="collider"> Collider: collider that is now colliding with this enemy</param>
void OnTriggerEnter(Collider collider)
{
/* This code feels dirty.
Memento's trigger collider is on the child object, so we need
to access its parent through its transform
*/
Transform parent = collider.gameObject.transform.parent;
if (parent != null && parent.tag == "Memento" && NEST != null && NEST.MEMENTO == null
&& (_enemyState != EnemyState.TargetingPlayer
&& _enemyState != EnemyState.TransportingMemento))
{
_memento = parent.gameObject.GetComponent<Memento>();
_memento.Bind(this.gameObject);
ChangeState(EnemyState.TransportingMemento);
_navAgent.SetDestination(NEST.transform.position);
}
}
/// <summary> Helper function for checking player detection </summary>
/// <return> true if the player is within visible range, false otherwise </return>
public bool CanSeePlayer()
{
RaycastHit hit;
Physics.Raycast (transform.position, _player.transform.position - transform.position, out hit, FOV_CONE_LENGTH);
if (hit.collider != null && hit.collider.gameObject != null && hit.collider.gameObject.CompareTag ("Player"))
{
if (Vector3.Distance(transform.position, _player.transform.position) <= FOV_RADIUS
|| Vector3.Angle(_player.transform.position - transform.position, transform.forward) <= FOV_CONE_RADIUS)
return true;
}
return false;
}
/// <summary>
/// Helper function to target the player.
/// Drops the memento if it is held.
/// Changes enemy state to TargetingPlayer.
/// Sets the navAgent's destination.
/// </summary>
public void SetTargetToPlayer()
{
//If we have the memento, drop it
if (_memento != null)
{
//Debug.Log("<color=blue>AI: Dropping Memento</color>");
_memento.Release();
_memento = null;
}
// Only set the audio if we are entering this state for the first time
if (_enemyState != EnemyState.TargetingPlayer)
ChangeState(EnemyState.TargetingPlayer);
_navAgent.SetDestination(_player.transform.position);
_timeOnTargetPlayer = Time.time;
}
/// <summary>
/// Helper function to change the navAgent's destination to the next
/// patrol point.
/// If there is no next patrol point, go back to the initial point
/// Otherwise, move to the next point
///</summary>
public void SetTargetToNextPatrolPoint()
{
if (_patrolCurrent.NEXT != null)
{
_patrolCurrent = _patrolCurrent.NEXT; // Move to next point
ChangeState(EnemyState.Patrolling);
//Debug.Log("<color=blue>AI: Setting Target to Next Patrol Point " + _patrolCurrent.name + "</color>");
_navAgent.SetDestination (_patrolCurrent.transform.position);
}
else if (_patrolCurrent != PATROL_START) // Return to initial patrol point (unless we only have one)
{
_patrolCurrent = PATROL_START; // Restart the patrol
ChangeState(EnemyState.Patrolling);
//Debug.Log("<color=blue>AI: Setting Target to Next Patrol Point " + _patrolCurrent.name + "</color>");
_navAgent.SetDestination (_patrolCurrent.transform.position);
}
}
/// <summary>
/// Helper function to change the navAgent's destination to the
/// closest patrol point in the patrol group.
/// Utilizes the PatrolManager to find all patrol points in the
/// group.
/// ***If no points are returned, the function exits.***
/// Determines the closest point, setting the navAgent's
/// destination
/// Changes enemy state to Patrolling
/// </summary>
public void SetTargetToNearestPoint()
{
List<PatrolPoint> possible_points = _patrolManager.GetPatrolPointsByGroupID(PATROL_GROUP);
if(possible_points.Count == 0) {
//Debug.Log("<color=blue>AI Warning:</color>Found no patrol points belonging to this AI's Patrol Group!"
//+ "Did you remember to assign a group to this AI, as well as the patrol points you want it tied to?", gameObject);
return;
}
PatrolPoint closest = possible_points[0];
float min_distance = Vector3.Distance(transform.position, closest.transform.position);
foreach (PatrolPoint p in possible_points) {
float d = Vector3.Distance(transform.position, p.transform.position);
if(d < min_distance) {
closest = p;
min_distance = d;
}
}
_patrolCurrent = closest;
PATROL_START = _patrolCurrent;
//Debug.Log("<color=blue>AI: Setting Target to Patrol Point " + _patrolCurrent.name + "</color>");
ChangeState(EnemyState.Patrolling);
_navAgent.SetDestination(_patrolCurrent.transform.position);
}
/// <summary>
/// Called from Memento class to tell this enemy a memento has pulsed nearby.
///
/// If this enemy's state is not TargetingPlayer or TransportingMemento, the
/// state is changed to TargetingMemento and the navAgent's destination
/// is set to the location of the memento
/// </summary>
/// <param name="memento"> GameObject: game object of the memento that pulsed</param>
public void OnMementoPulse(GameObject memento)
{
if (_enemyState != EnemyState.TargetingPlayer && _enemyState != EnemyState.TransportingMemento)
{
ChangeState(EnemyState.TargetingMemento);
_navAgent.SetDestination(memento.transform.position);
}
}
/// <summary>
/// Helper method to handle state change events like audio and animation
/// </summary>
/// <param name="newState">The new state to transition to</param>
public void ChangeState(EnemyState newState)
{
_previousState = _enemyState;
switch (newState)
{
case EnemyState.Idle:
_enemyState = EnemyState.Idle;
_timeOnEnterIdle = Time.time;
visionLight.color = _neutralColor; // Return the vision light to its original color
_audioSource.clip = _neutralAudio;
_audioSource.Play();
_animator.SetBool("isTargetingPlayer", false);
_animator.SetBool("isIdle", true);
_navAgent.speed = SPEED_DEFAULT; // CB: Change the movement speed to match the state
break;
case EnemyState.Patrolling:
_enemyState = EnemyState.Patrolling;
_animator.SetBool("isIdle", false);
_navAgent.speed = SPEED_DEFAULT; // CB: Change the movement speed to match the state
break;
case EnemyState.TargetingMemento:
_enemyState = EnemyState.TargetingMemento;
_animator.SetBool("isIdle", false);
_navAgent.speed = SPEED_DEFAULT; // CB: Change the movement speed to match the state
break;
case EnemyState.TargetingPlayer:
_enemyState = EnemyState.TargetingPlayer;
visionLight.color = TARGETING_PLAYER_COLOR; // Change the color of the vision light
_audioSource.clip = TARGETING_PLAYER_AUDIO;
_audioSource.Play();
_animator.SetBool("isTargetingPlayer", true);
_animator.SetBool("isIdle", false);
_navAgent.speed = SPEED_TARGETING_PLAYER; // CB: Change the movement speed to match the state
break;
case EnemyState.TransportingMemento:
_enemyState = EnemyState.TransportingMemento;
_animator.SetBool("isIdle", false);
_navAgent.speed = SPEED_DEFAULT; // CB: Change the movement speed to match the state
break;
}
}
}
|
using UnityEngine;
using System.Collections;
public class Fireball : MonoBehaviour
{
public float timeToLive = 10.0f;
public float speed = 5.0f;
private float timeElapsed = 0f;
// Update is called once per frame
void Update ()
{
timeElapsed += Time.deltaTime;
if (timeElapsed > timeToLive)
{
Destroy( gameObject );
}
transform.position += transform.forward * speed * Time.deltaTime;
}
public void OnCollisionEnter( Collision collision )
{
Debug.Log( "Fireball hit: " + collision.transform.gameObject.name );
// TODO: Explosion
if ( collision.transform.CompareTag( tag ) )
{
// Hit another projectile; do nothing. Possible when playing is running forward and fireballing
return;
}
collision.transform.SendMessage( "OnFireballCollision", SendMessageOptions.DontRequireReceiver );
Destroy( gameObject );
}
}
|
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace Witsml.ServiceReference
{
public static class EnumMemberToString
{
public static string GetEnumMemberValue<T>(this T value) where T : Enum
{
return typeof(T)
.GetTypeInfo()
.DeclaredMembers
.SingleOrDefault(x => x.Name == value.ToString())
?.GetCustomAttribute<EnumMemberAttribute>(false)
?.Value;
}
}
public static class EnumParser<T> where T : Enum
{
public static T GetEnum(string enumMemberValue)
{
var stringValue = typeof(T)
.GetTypeInfo()
.DeclaredMembers
.Where(member => member.GetCustomAttribute<EnumMemberAttribute>(false)?.Value == enumMemberValue)
.Select(f => f.Name)
.FirstOrDefault();
if (!string.IsNullOrEmpty(stringValue))
return (T) Enum.Parse(typeof(T), stringValue);
throw new ArgumentException($"No members of {typeof(T).Name} has a specified EnumMember value of '{enumMemberValue}'");
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Configuration;
using CEMAPI.BAL;
using CEMAPI.Models;
using CEMAPI.Controllers;
using doc = DMSUploadDownload;
namespace CEMAPI.DAL
{
public class TEApplicantMgntDAL
{
public TETechuvaDBContext context = new TETechuvaDBContext();
RecordExceptions excepton = new RecordExceptions();
NotificationHistoryBAL notBAL = new NotificationHistoryBAL();
string FugueEmail = WebConfigurationManager.AppSettings["Fugue"];
public TEApplicantMgntDAL()
{
context.Configuration.ProxyCreationEnabled = false;
}
public List <Res_ListOfApplicants> ListOfOrderApplicants(REQ_ListOfApplicants Data, int authuser)
{
List<Res_ListOfApplicants> Result = new List<Res_ListOfApplicants>();
try
{
Result = (from t1 in context.TEOrderApplicants
join t2Temp in context.TEApplicantIdentityDetails on t1.ApplicantID equals t2Temp.ApplicantID into t2Final
from t2 in t2Final.DefaultIfEmpty()
join t3Temp in context.TEApplicantBasicDetails on t1.ApplicantID equals t3Temp.ApplicantID into t3Final
from t3 in t3Final.DefaultIfEmpty()
where t1.ContextID == Data.OrderID && t1.ISDeleted == false
select new Res_ListOfApplicants
{
ApplicantID = t1.ApplicantID,
ContextID = t1.ContextID,
ContactID = t1.ContactID,
ApplicantName = t3.FirstName+" "+t3.MiddleName+" "+t3.LastName,
FatherName = t3.FatherName,
DateOfBirth = t3.DateOfBirth,
PanNumber = t2.PanNumber,
TypeofApplicant = t1.TypeofApplicant,
Status = t1.Status,
DeclarationSigned = t1.DeclarationSigned,
Mobile = (context.TEApplicantMobileDetails.Where(a=>a.ApplicantID==t1.ApplicantID && a.Type.Equals("Primary") && a.IsDeleted==false).Select(a=>a.Mobile).FirstOrDefault()),
IsAFSGenerated = false
}).ToList();
return Result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
return Result;
}
}
public SuccessInfo AddNewApplicants(List<int> ApplicantIDs,int OrderID, int authuser)
{
SuccessInfo Result = new SuccessInfo { errorcode = 1, errormessage = "Failed", listcount = 0 };
try
{
List<int> Errors = new List<int>();
foreach (var ContactID in ApplicantIDs) {
int CountOfApplicant = context.TEOrderApplicants.Where(a => a.ContactID == ContactID && a.ContextID == OrderID && a.ISDeleted == false).Count();
if (CountOfApplicant <= 0) {
TEContact BasicDet = new TEContact();
BasicDet = context.TEContacts.Where(a => a.Uniqueid == ContactID && a.IsDeleted == false).FirstOrDefault();
if (BasicDet == null) Errors.Add(ContactID);
else
{
//Creating Applicant in Main Table Starts
TEOrderApplicant AppDetails = new TEOrderApplicant();
AppDetails.ContactID = ContactID;
AppDetails.ContextID = OrderID;
AppDetails.DeclarationSigned = false;
AppDetails.ISDeleted = false;
AppDetails.LastModifiedBy = authuser;
AppDetails.LastModifiedOn = DateTime.Now;
AppDetails.OTP = 0;
AppDetails.Status = false;
AppDetails.TypeofApplicant = "CoApplicant";
context.TEOrderApplicants.Add(AppDetails);
context.SaveChanges();
//Creating Applicant in Main Table Ends
if (AppDetails.ApplicantID <= 0) Errors.Add(ContactID);
else
{
//Creating Basic Information Starts
TEApplicantBasicDetail BasicDetail = new TEApplicantBasicDetail();
BasicDetail.AnniversaryDate = BasicDet.DOM;
BasicDetail.ApplicantID = AppDetails.ApplicantID;
BasicDetail.ContactCategory = BasicDet.Category;
BasicDetail.ContactID = ContactID;
BasicDetail.Country = null;
BasicDetail.DateOfBirth = BasicDet.DOB;
BasicDetail.FatherName = null;
BasicDetail.FirstName = BasicDet.FirstName;
BasicDetail.GSTClassification = null;
BasicDetail.GSTNumber = null;
BasicDetail.IsDeleted = false;
BasicDetail.IsExistingCustomer = false;
BasicDetail.LastModifiedBy = authuser;
BasicDetail.LastModifiedOn = DateTime.Now;
BasicDetail.LastName = BasicDet.LastName;
BasicDetail.MiddleName = BasicDet.MiddleName;
BasicDetail.Nationality = BasicDet.Nationality;
BasicDetail.Title = BasicDet.Salutation;
context.TEApplicantBasicDetails.Add(BasicDetail);
context.SaveChanges();
//Creating Basic Information Ends
//Creating Mobile Information Starts
List<TEContactMobile> ApplicantMobileDet = new List<TEContactMobile>();
ApplicantMobileDet = context.TEContactMobiles.Where(a => a.TEContact == ContactID && a.IsDeleted == false).ToList();
foreach (TEContactMobile Data in ApplicantMobileDet)
{
TEApplicantMobileDetail Mdata = new TEApplicantMobileDetail();
Mdata.ApplicantID = AppDetails.ApplicantID;
Mdata.ContactID = ContactID;
Mdata.CountryCode = Data.CountryCode;
Mdata.IsDeleted = false;
Mdata.LastModifiedBy = authuser;
Mdata.LastModifiedOn = DateTime.Now;
Mdata.Mobile = Data.Mobile;
Mdata.Type = Data.Type;
context.TEApplicantMobileDetails.Add(Mdata);
context.SaveChanges();
}
//Creating Mobile Information Ends
//Creating Email Information Starts
List<TEContactEmail> ApplicantEmailDet = new List<TEContactEmail>();
ApplicantEmailDet = context.TEContactEmails.Where(a => a.TEContact == ContactID && a.IsDeleted == false).ToList();
foreach (TEContactEmail Data in ApplicantEmailDet)
{
TEApplicantEmailDetail Edata = new TEApplicantEmailDetail();
Edata.ApplicantID = AppDetails.ApplicantID;
Edata.ContactID = ContactID;
Edata.EmailID = Data.Emailid;
Edata.IsDeleted = false;
Edata.LastModifiedBy = authuser;
Edata.LastModifiedOn = DateTime.Now;
Edata.Type = Data.Type;
context.TEApplicantEmailDetails.Add(Edata);
context.SaveChanges();
}
//Creating Email Information Ends
//Creating Address Information Starts
List<TEContactAddress> ApplicantAddressDet = new List<TEContactAddress>();
ApplicantAddressDet = context.TEContactAddresses.Where(a => a.TEContact == ContactID && a.IsDeleted == false).ToList();
foreach (TEContactAddress Data in ApplicantAddressDet)
{
TEApplicantAddressDetail Adddata = new TEApplicantAddressDetail();
Adddata.ApplicantID = AppDetails.ApplicantID;
Adddata.ContactID = ContactID;
Adddata.AddressLine1 = Data.Street1;
Adddata.AddressLine2 = Data.Street2;
Adddata.City = Data.City;
Adddata.Country = Data.Country;
Adddata.PinCode = Data.Pincode;
Adddata.State = Data.State;
Adddata.Type = Data.TypeOfAddress;
Adddata.IsDeleted = false;
Adddata.LastModifiedBy = authuser;
Adddata.LastModifiedOn = DateTime.Now;
context.TEApplicantAddressDetails.Add(Adddata);
context.SaveChanges();
}
//Creating Address Information Ends
//Creating Identity Information Starts
TEContactProfession ProData = new TEContactProfession();
ProData = context.TEContactProfessions.Where(a => a.TEContact == ContactID && a.IsDeleted == false).OrderByDescending(a => a.Uniqueid).FirstOrDefault();
if (ProData != null)
{
TEApplicantIdentityDetail IdentityDetails = new TEApplicantIdentityDetail();
IdentityDetails.ApplicantID = AppDetails.ApplicantID;
IdentityDetails.Company = ProData.Organisation;
IdentityDetails.ContactID = ContactID;
IdentityDetails.Designation = ProData.Profession;
IdentityDetails.Industry = ProData.Industry;
IdentityDetails.Profession = ProData.Profession;
IdentityDetails.IsDeleted = false;
IdentityDetails.LastModifiedBy = authuser;
IdentityDetails.LastModifiedOn = DateTime.Now;
context.TEApplicantIdentityDetails.Add(IdentityDetails);
context.SaveChanges();
}
//Creating Identity Information Ends
}
}
if (Errors.Count > 0)
{
Result.errorcode = 1;
Result.errormessage = "Few Applicants are not Created";
}
else
{
Result.errorcode = 0;
Result.errormessage = "Selected Applicants are Created to the Order";
}
}
}
return Result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
Result.errorcode = 1;
Result.errormessage = "Failed: Something Went Wrong";
Result.exceptionMessage = "Exception: " + ex.Message;
return Result;
}
}
public SuccessInfo UpdateTheMainApplicant(int ApplicantID, int authuser)
{
SuccessInfo Result = new SuccessInfo { errorcode = 0, errormessage = "Successfully updated the Main Applicant", listcount = 0 };
try
{
TEOrderApplicant CurrentApplicant = new TEOrderApplicant();
CurrentApplicant = context.TEOrderApplicants.Where(a => a.ApplicantID == ApplicantID && a.ISDeleted == false).FirstOrDefault();
if (CurrentApplicant == null)
{
Result.errorcode = 1;
Result.errormessage = "Failed: Could Not Find Applicant Details";
return Result;
}
List<TEOrderApplicant> AppList = new List<TEOrderApplicant>();
AppList = context.TEOrderApplicants.Where(a => a.ContextID == CurrentApplicant.ContextID).ToList();
foreach(TEOrderApplicant Data in AppList)
{
Data.TypeofApplicant = "CoApplicant";
Data.LastModifiedBy = authuser;
Data.LastModifiedOn = DateTime.Now;
context.Entry(Data).CurrentValues.SetValues(Data);
context.SaveChanges();
}
CurrentApplicant.TypeofApplicant = "Main Applicant";
CurrentApplicant.LastModifiedBy = authuser;
CurrentApplicant.LastModifiedOn = DateTime.Now;
context.Entry(CurrentApplicant).CurrentValues.SetValues(CurrentApplicant);
context.SaveChanges();
return Result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
Result.errorcode = 1;
Result.errormessage = "Failed: Something Went Wrong";
Result.exceptionMessage = "Exception: " + ex.Message;
return Result;
}
}
public SuccessInfo ActiveInvativeApplicant(int ApplicantID, int authuser)
{
SuccessInfo Result = new SuccessInfo { errorcode = 0, errormessage = "Successfully updated the Applicant", listcount = 0 };
try
{
TEOrderApplicant CurrentApplicant = new TEOrderApplicant();
CurrentApplicant = context.TEOrderApplicants.Where(a => a.ApplicantID == ApplicantID && a.ISDeleted == false).FirstOrDefault();
if (CurrentApplicant == null)
{
Result.errorcode = 1;
Result.errormessage = "Failed: Could Not Find Applicant Details";
return Result;
}
CurrentApplicant.Status = !CurrentApplicant.Status;
CurrentApplicant.LastModifiedBy = authuser;
CurrentApplicant.LastModifiedOn = DateTime.Now;
context.Entry(CurrentApplicant).CurrentValues.SetValues(CurrentApplicant);
context.SaveChanges();
return Result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
Result.errorcode = 1;
Result.errormessage = "Failed: Something Went Wrong";
Result.exceptionMessage = "Exception: " + ex.Message;
return Result;
}
}
public TEApplicantBasicDetail GetApplicantBasicDetails(int ApplicantID, int authuser)
{
TEApplicantBasicDetail Result = new TEApplicantBasicDetail();
try
{
Result = context.TEApplicantBasicDetails.Where(a => a.ApplicantID == ApplicantID && a.IsDeleted == false).FirstOrDefault();
return Result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
return Result;
}
}
public SuccessInfo UpdateApplicantBasicDetails(Res_ApplicantBasicDetails Details, int authuser)
{
SuccessInfo Result = new SuccessInfo { errorcode = 0, errormessage = "Successfully updated the Applicant's Basic Details", listcount = 0 };
try
{
TEOrderApplicant CurrentApplicant = new TEOrderApplicant();
CurrentApplicant = context.TEOrderApplicants.Where(a => a.ApplicantID == Details.ApplicantID && a.ISDeleted == false).FirstOrDefault();
if (CurrentApplicant == null)
{
Result.errorcode = 1;
Result.errormessage = "Failed: Could not find Applicant Details";
return Result;
}
TEApplicantBasicDetail BasicDetails = new TEApplicantBasicDetail();
BasicDetails = context.TEApplicantBasicDetails.Where(a => a.ApplicantID == Details.ApplicantID && a.IsDeleted == false).FirstOrDefault();
if (BasicDetails == null)
{
BasicDetails.ApplicantID = CurrentApplicant.ApplicantID;
BasicDetails.ContactID = CurrentApplicant.ContactID;
BasicDetails.Title = Details.Title;
BasicDetails.FirstName = Details.FirstName;
BasicDetails.MiddleName = Details.MiddleName;
BasicDetails.LastName = Details.LastName;
BasicDetails.FatherName = Details.FatherName;
BasicDetails.DateOfBirth = Details.DateOfBirth;
BasicDetails.AnniversaryDate = Details.AnniversaryDate;
BasicDetails.Nationality = Details.Nationality;
BasicDetails.Country = Details.Country;
BasicDetails.ContactCategory = Details.ContactCategory;
BasicDetails.GSTClassification = Details.GSTClassification;
BasicDetails.GSTNumber = Details.GSTNumber;
BasicDetails.IsExistingCustomer = Details.IsExistingCustomer;
BasicDetails.LastModifiedBy = authuser;
BasicDetails.LastModifiedOn = DateTime.Now;
context.TEApplicantBasicDetails.Add(BasicDetails);
context.SaveChanges();
}
else
{
BasicDetails.Title = Details.Title;
BasicDetails.FirstName = Details.FirstName;
BasicDetails.MiddleName = Details.MiddleName;
BasicDetails.LastName = Details.LastName;
BasicDetails.FatherName = Details.FatherName;
BasicDetails.DateOfBirth = Details.DateOfBirth;
BasicDetails.AnniversaryDate = Details.AnniversaryDate;
BasicDetails.Nationality = Details.Nationality;
BasicDetails.Country = Details.Country;
BasicDetails.ContactCategory = Details.ContactCategory;
BasicDetails.GSTClassification = Details.GSTClassification;
BasicDetails.GSTNumber = Details.GSTNumber;
BasicDetails.IsExistingCustomer = Details.IsExistingCustomer;
BasicDetails.LastModifiedBy = authuser;
BasicDetails.LastModifiedOn = DateTime.Now;
context.Entry(BasicDetails).CurrentValues.SetValues(BasicDetails);
context.SaveChanges();
}
return Result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
Result.errorcode = 1;
Result.errormessage = "Failed: Something Went Wrong";
Result.exceptionMessage = "Exception: " + ex.Message;
return Result;
}
}
public TEApplicantIdentityDetail GetApplicantIdentityDetails(int ApplicantID, int authuser)
{
TEApplicantIdentityDetail Result = new TEApplicantIdentityDetail();
try
{
Result = context.TEApplicantIdentityDetails.Where(a => a.ApplicantID == ApplicantID && a.IsDeleted == false).FirstOrDefault();
return Result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
return Result;
}
}
public SuccessInfo UpdateApplicantIdentityDetails(Req_ApplicantIdentityDetails Details, int authuser)
{
SuccessInfo Result = new SuccessInfo { errorcode = 0, errormessage = "Successfully updated the Applicant's Basic Details", listcount = 0 };
string tempMessage = string.Empty;
try
{
TEOrderApplicant CurrentApplicant = new TEOrderApplicant();
CurrentApplicant = context.TEOrderApplicants.Where(a => a.ApplicantID == Details.ApplicantID && a.ISDeleted == false).FirstOrDefault();
if (CurrentApplicant == null)
{
Result.errorcode = 1;
Result.errormessage = "Failed: Could not find Applicant Details";
return Result;
}
SuccessInfo IDProofRes = new SuccessInfo { errorcode = 0, errormessage = "Successfully", listcount = 0 };
SuccessInfo AddProofRes = new SuccessInfo { errorcode = 0, errormessage = "Successfully", listcount = 0 };
SuccessInfo PANProofRes = new SuccessInfo { errorcode = 0, errormessage = "Successfully", listcount = 0 };
SuccessInfo AadharProofRes = new SuccessInfo { errorcode = 0, errormessage = "Successfully", listcount = 0 };
if (Details.IdentityProfAttachment != null)
{
IDProofRes = UploadFilesToDMS(CurrentApplicant.ApplicantID, "IDProof", Details.IdentityProfAttachment, Details.IdentityProfAttachment_Type, authuser);
if (IDProofRes.errorcode != 0)
tempMessage += "<br>Id Proof is not uploaded";
}
if (Details.AddressProfAttachment != null)
{
AddProofRes = UploadFilesToDMS(CurrentApplicant.ApplicantID, "IDProof", Details.AddressProfAttachment, Details.AddressProfAttachment_Type, authuser);
if (AddProofRes.errorcode != 0)
tempMessage += "<br>Address Proof is not uploaded";
}
if (Details.PanAttachment != null)
{
PANProofRes = UploadFilesToDMS(CurrentApplicant.ApplicantID, "IDProof", Details.PanAttachment, Details.PanAttachment_Type, authuser);
if (PANProofRes.errorcode != 0)
tempMessage += "<br>PAN Proof is not uploaded";
}
if (Details.AadharAttachment != null)
{
AadharProofRes = UploadFilesToDMS(CurrentApplicant.ApplicantID, "IDProof", Details.AadharAttachment, Details.AadharAttachment_Type, authuser);
if (AadharProofRes.errorcode != 0)
tempMessage += "<br>Aadhar Proof is not uploaded";
}
TEApplicantIdentityDetail IdentityDetails = new TEApplicantIdentityDetail();
IdentityDetails = context.TEApplicantIdentityDetails.Where(a => a.ApplicantID == Details.ApplicantID && a.IsDeleted == false).FirstOrDefault();
if (IdentityDetails == null)
{
IdentityDetails.ApplicantID = CurrentApplicant.ApplicantID;
IdentityDetails.ContactID = CurrentApplicant.ContactID;
IdentityDetails.Profession = Details.Profession;
IdentityDetails.Industry = Details.Industry;
IdentityDetails.Company = Details.Company;
IdentityDetails.Designation = Details.Designation;
IdentityDetails.IdentityProfType = Details.IdentityProfType;
IdentityDetails.IndentityProfNumber = Details.IndentityProfNumber;
IdentityDetails.DateOfIssue = Details.DateOfIssue;
IdentityDetails.AddressProfType = Details.AddressProfType;
IdentityDetails.PanNumber = Details.PanNumber;
IdentityDetails.AadharNumber = Details.AadharNumber;
IdentityDetails.AadharIsssueDate = Details.AadharIsssueDate;
IdentityDetails.AadharValidityDate = Details.AadharValidityDate;
IdentityDetails.IdentityProfAttachment = Convert.ToInt32(Details.IdentityProfAttachment);
IdentityDetails.AddressProfAttachment = Convert.ToInt32(Details.AddressProfAttachment);
IdentityDetails.PanAttachment = Convert.ToInt32(Details.PanAttachment);
IdentityDetails.AadharAttachment = Convert.ToInt32(Details.AadharAttachment);
IdentityDetails.LastModifiedBy = authuser;
IdentityDetails.LastModifiedOn = DateTime.Now;
IdentityDetails.IsDeleted = false;
context.TEApplicantIdentityDetails.Add(IdentityDetails);
context.SaveChanges();
}
else
{
IdentityDetails.Profession = Details.Profession;
IdentityDetails.Industry = Details.Industry;
IdentityDetails.Company = Details.Company;
IdentityDetails.Designation = Details.Designation;
IdentityDetails.IdentityProfType = Details.IdentityProfType;
IdentityDetails.IndentityProfNumber = Details.IndentityProfNumber;
IdentityDetails.DateOfIssue = Details.DateOfIssue;
IdentityDetails.AddressProfType = Details.AddressProfType;
IdentityDetails.PanNumber = Details.PanNumber;
IdentityDetails.AadharNumber = Details.AadharNumber;
IdentityDetails.AadharIsssueDate = Details.AadharIsssueDate;
IdentityDetails.AadharValidityDate = Details.AadharValidityDate;
IdentityDetails.LastModifiedBy = authuser;
IdentityDetails.LastModifiedOn = DateTime.Now;
if (Convert.ToInt32(Details.IdentityProfAttachment) != 0) IdentityDetails.IdentityProfAttachment = Convert.ToInt32(Details.IdentityProfAttachment);
if (Convert.ToInt32(Details.IdentityProfAttachment) != 0) IdentityDetails.AddressProfAttachment = Convert.ToInt32(Details.AddressProfAttachment);
if (Convert.ToInt32(Details.IdentityProfAttachment) != 0) IdentityDetails.PanAttachment = Convert.ToInt32(Details.PanAttachment);
if (Convert.ToInt32(Details.IdentityProfAttachment) != 0) IdentityDetails.AadharAttachment = Convert.ToInt32(Details.AadharAttachment);
context.Entry(IdentityDetails).CurrentValues.SetValues(IdentityDetails);
context.SaveChanges();
}
Result.errormessage = Result.errormessage + tempMessage;
return Result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
Result.errorcode = 1;
Result.errormessage = "Failed: Something Went Wrong";
Result.exceptionMessage = "Exception: " + ex.Message;
return Result;
}
}
public TEApplicantFundingDetail GetApplicantFundingDetailsDAL(int applicantId, int authUser)
{
TEApplicantFundingDetail result = new TEApplicantFundingDetail();
try
{
result = context.TEApplicantFundingDetails.Where(x => x.ApplicantID == applicantId && x.IsDeleted == false).FirstOrDefault();
return result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
return result;
}
}
public SuccessInfo UpdateApplicantFundingDetailsDAL(Req_ApplicantIFundingDetails Details, int authuser)
{
SuccessInfo Result = new SuccessInfo { errorcode = 0, errormessage = "Successfully updated the Applicant's Basic Details", listcount = 0 };
try
{
TEOrderApplicant CurrentApplicant = new TEOrderApplicant();
CurrentApplicant = context.TEOrderApplicants.Where(a => a.ApplicantID == Details.ApplicantID && a.ISDeleted == false).FirstOrDefault();
if (CurrentApplicant == null)
{
Result.errorcode = 1;
Result.errormessage = "Failed: Could not find Applicant Details";
return Result;
}
TEApplicantFundingDetail BasicDetails = new TEApplicantFundingDetail();
BasicDetails = context.TEApplicantFundingDetails.Where(a => a.ApplicantID == Details.ApplicantID && a.IsDeleted == false).FirstOrDefault();
if (BasicDetails == null)
{
BasicDetails.ApplicantID = CurrentApplicant.ApplicantID;
BasicDetails.ContactID = CurrentApplicant.ContactID;
BasicDetails.TypeOfFunding = Details.TypeOfFunding;
BasicDetails.FundingAmount = Details.FundingAmount;
BasicDetails.PreApproveLoan = Details.PreApproveLoan;
BasicDetails.PreferredBankForLoan = Details.PreferredBankForLoan;
BasicDetails.LoanAccountNumber = Details.LoanAccountNumber;
BasicDetails.ApprovedAmount = Details.ApprovedAmount;
BasicDetails.BankContactPerson = Details.BankContactPerson;
BasicDetails.BankContactNumber = Details.BankContactNumber;
BasicDetails.BankEmailID = Details.BankEmailID;
BasicDetails.BankAddress = Details.BankAddress;
BasicDetails.Branch = Details.Branch;
BasicDetails.BranchCode = Details.BranchCode;
BasicDetails.AccountHolder = Details.AccountHolder;
BasicDetails.AccountNumber = Details.AccountNumber;
BasicDetails.TypeOfAccount = Details.TypeOfAccount;
BasicDetails.LastModifiedBy = authuser;
BasicDetails.LastModifiedOn = DateTime.Now;
context.TEApplicantFundingDetails.Add(BasicDetails);
context.SaveChanges();
}
else
{
BasicDetails.TypeOfFunding = Details.TypeOfFunding;
BasicDetails.FundingAmount = Details.FundingAmount;
BasicDetails.PreApproveLoan = Details.PreApproveLoan;
BasicDetails.PreferredBankForLoan = Details.PreferredBankForLoan;
BasicDetails.LoanAccountNumber = Details.LoanAccountNumber;
BasicDetails.ApprovedAmount = Details.ApprovedAmount;
BasicDetails.BankContactPerson = Details.BankContactPerson;
BasicDetails.BankContactNumber = Details.BankContactNumber;
BasicDetails.BankEmailID = Details.BankEmailID;
BasicDetails.BankAddress = Details.BankAddress;
BasicDetails.Branch = Details.Branch;
BasicDetails.BranchCode = Details.BranchCode;
BasicDetails.AccountHolder = Details.AccountHolder;
BasicDetails.AccountNumber = Details.AccountNumber;
BasicDetails.TypeOfAccount = Details.TypeOfAccount;
BasicDetails.LastModifiedBy = authuser;
BasicDetails.LastModifiedOn = DateTime.Now;
context.Entry(BasicDetails).CurrentValues.SetValues(BasicDetails);
context.SaveChanges();
}
return Result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
Result.errorcode = 1;
Result.errormessage = "Failed: Something Went Wrong";
Result.exceptionMessage = "Exception: " + ex.Message;
return Result;
}
}
public TEApplicantComAddress GetApplicantCorrespondingAddressDAL(int applicantId, int authUser)
{
TEApplicantComAddress result = new TEApplicantComAddress();
try
{
result = context.TEApplicantComAddresses.Where(x => x.ApplicantID == applicantId && x.IsDeleted == false).FirstOrDefault();
return result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
return result;
}
}
public SuccessInfo UpdateApplicantCorrespondingDetailsDAL(Req_ApplicantICorrespondingDetails Details, int authuser)
{
SuccessInfo Result = new SuccessInfo { errorcode = 0, errormessage = "Successfully updated the Applicant's Basic Details", listcount = 0 };
try
{
TEOrderApplicant CurrentApplicant = new TEOrderApplicant();
CurrentApplicant = context.TEOrderApplicants.Where(a => a.ApplicantID == Details.ApplicantID && a.ISDeleted == false).FirstOrDefault();
if (CurrentApplicant == null)
{
Result.errorcode = 1;
Result.errormessage = "Failed: Could not find Applicant Details";
return Result;
}
TEApplicantComAddress BasicDetails = new TEApplicantComAddress();
BasicDetails = context.TEApplicantComAddresses.Where(a => a.ApplicantID == Details.ApplicantID && a.IsDeleted == false).FirstOrDefault();
if (BasicDetails == null)
{
BasicDetails.ApplicantID = CurrentApplicant.ApplicantID;
BasicDetails.ContactID = CurrentApplicant.ContactID;
BasicDetails.Title = Details.Title;
BasicDetails.FirstName = Details.FirstName;
BasicDetails.LastName = Details.LastName;
BasicDetails.RelationshipWithApplicant = Details.RelationshipWithApplicant;
BasicDetails.AddressLine1 = Details.AddressLine1;
BasicDetails.AddressLine2 = Details.AddressLine2;
BasicDetails.City = Details.City;
BasicDetails.State = Details.State;
BasicDetails.Country = Details.Country;
BasicDetails.PinCode = Details.PinCode;
BasicDetails.Mobile = Details.Mobile;
BasicDetails.Email = Details.Email;
BasicDetails.Fax = Details.Fax;
BasicDetails.LastModifiedBy = authuser;
BasicDetails.LastModifiedOn = DateTime.Now;
context.TEApplicantComAddresses.Add(BasicDetails);
context.SaveChanges();
}
else
{
BasicDetails.Title = Details.Title;
BasicDetails.FirstName = Details.FirstName;
BasicDetails.LastName = Details.LastName;
BasicDetails.RelationshipWithApplicant = Details.RelationshipWithApplicant;
BasicDetails.AddressLine1 = Details.AddressLine1;
BasicDetails.AddressLine2 = Details.AddressLine2;
BasicDetails.City = Details.City;
BasicDetails.State = Details.State;
BasicDetails.Country = Details.Country;
BasicDetails.PinCode = Details.PinCode;
BasicDetails.Mobile = Details.Mobile;
BasicDetails.Email = Details.Email;
BasicDetails.Fax = Details.Fax;
BasicDetails.LastModifiedBy = authuser;
BasicDetails.LastModifiedOn = DateTime.Now;
context.Entry(BasicDetails).CurrentValues.SetValues(BasicDetails);
context.SaveChanges();
}
return Result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
Result.errorcode = 1;
Result.errormessage = "Failed: Something Went Wrong";
Result.exceptionMessage = "Exception: " + ex.Message;
return Result;
}
}
public TEApplicantGPADetail GetApplicantGPADetailDAL(int applicantId, int authUser)
{
TEApplicantGPADetail result = new TEApplicantGPADetail();
try
{
result = context.TEApplicantGPADetails.Where(x => x.ApplicantID == applicantId && x.ISDeleted == false).FirstOrDefault();
return result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
return result;
}
}
public SuccessInfo UpdateApplicantGPADAL(Req_ApplicantIGAPDetails Details, int authuser)
{
SuccessInfo Result = new SuccessInfo { errorcode = 0, errormessage = "Successfully updated the Applicant's Basic Details", listcount = 0 };
try
{
TEOrderApplicant CurrentApplicant = new TEOrderApplicant();
CurrentApplicant = context.TEOrderApplicants.Where(a => a.ApplicantID == Details.ApplicantID && a.ISDeleted == false).FirstOrDefault();
if (CurrentApplicant == null)
{
Result.errorcode = 1;
Result.errormessage = "Failed: Could not find Applicant Details";
return Result;
}
TEApplicantGPADetail BasicDetails = new TEApplicantGPADetail();
BasicDetails = context.TEApplicantGPADetails.Where(a => a.ApplicantID == Details.ApplicantID && a.ISDeleted == false).FirstOrDefault();
if (BasicDetails == null)
{
BasicDetails.ApplicantID = CurrentApplicant.ApplicantID;
BasicDetails.ContactID = CurrentApplicant.ContactID;
BasicDetails.Title = Details.Title;
BasicDetails.FirstName = Details.FirstName;
BasicDetails.LastName = Details.LastName;
BasicDetails.RelationWithAboveApplicant = Details.RelationWithAboveApplicant;
BasicDetails.RelationWithMainApplicant = Details.RelationWithMainApplicant;
BasicDetails.AddressLine1 = Details.AddressLine1;
BasicDetails.AddressLine2 = Details.AddressLine2;
BasicDetails.City = Details.City;
BasicDetails.State = Details.State;
BasicDetails.Country = Details.Country;
BasicDetails.PinCode = Details.PinCode;
BasicDetails.Mobile = Details.Mobile;
BasicDetails.Email = Details.Email;
BasicDetails.LastModifiedBy = authuser;
BasicDetails.LastModifiedOn = DateTime.Now;
context.TEApplicantGPADetails.Add(BasicDetails);
context.SaveChanges();
}
else
{
BasicDetails.Title = Details.Title;
BasicDetails.FirstName = Details.FirstName;
BasicDetails.LastName = Details.LastName;
BasicDetails.RelationWithAboveApplicant = Details.RelationWithAboveApplicant;
BasicDetails.RelationWithMainApplicant = Details.RelationWithMainApplicant;
BasicDetails.AddressLine1 = Details.AddressLine1;
BasicDetails.AddressLine2 = Details.AddressLine2;
BasicDetails.City = Details.City;
BasicDetails.State = Details.State;
BasicDetails.Country = Details.Country;
BasicDetails.PinCode = Details.PinCode;
BasicDetails.Mobile = Details.Mobile;
BasicDetails.Email = Details.Email;
BasicDetails.LastModifiedBy = authuser;
BasicDetails.LastModifiedOn = DateTime.Now;
context.Entry(BasicDetails).CurrentValues.SetValues(BasicDetails);
context.SaveChanges();
}
return Result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
Result.errorcode = 1;
Result.errormessage = "Failed: Something Went Wrong";
Result.exceptionMessage = "Exception: " + ex.Message;
return Result;
}
}
public SuccessInfo UploadFilesToDMS(int ApplicantID, string docName, string imagePath, string imageType, int authuser)
{
SuccessInfo Result = new SuccessInfo();
try
{
TEOrderApplicant CurrentApplicant = new TEOrderApplicant();
CurrentApplicant = context.TEOrderApplicants.Where(a => a.ApplicantID == ApplicantID && a.ISDeleted == false).FirstOrDefault();
if (CurrentApplicant == null) {
Result.listcount = 0;
Result.errorcode = 1;
Result.errormessage = "Failed: Aplicant Details not Found";
return Result;
}
var RefData = (from t1 in context.TEOffers
join t2 in context.TEProjects on t1.ProjectID equals t2.ProjectID
join t3 in context.TEUnits on t1.UnitID equals t3.UnitID
where t1.OfferID == CurrentApplicant.ContextID
select new
{
OfferID = t1.OfferID,
SAPCustomerID = t1.SAPCustomerID,
CustomerName = t1.OfferCustomerName,
ProjectID = t2.ProjectID,
ProjectName = t2.ProjectName,
UnitID = t3.UnitID,
UnitNumber = t3.UnitNumber,
}).FirstOrDefault();
if (RefData == null)
{
Result.listcount = 0;
Result.errorcode = 1;
Result.errormessage = "Failed: Aplicant Basic Details not Found";
return Result;
}
string siteUrl = WebConfigurationManager.AppSettings["DMSSiteUrl"];
string libraryName = WebConfigurationManager.AppSettings["DMSLibrary"];
string userName = WebConfigurationManager.AppSettings["DMSUserId"];
string passWord = WebConfigurationManager.AppSettings["DMSPassword"];
string documentName = RefData.SAPCustomerID + "_" + docName + "_CustomerDataSheet_" + DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString();
string documentImageType = imageType;
string baseformat = imagePath;
bool overwrite = true;
doc.ResultDocumentDetails res = new doc.ResultDocumentDetails();
doc.CustLibMetadataInfo metainfo = new doc.CustLibMetadataInfo();
metainfo.ContentType = "KYC Proofs";
metainfo.ProjectName = RefData.ProjectName;
metainfo.Customer = RefData.CustomerName;
metainfo.Unit = RefData.UnitNumber;
metainfo.IsPhysicalDocumentStored = "No";
doc.FileUploadAndDownload upload = new doc.FileUploadAndDownload();
res = upload.UploadDocumentToSharePointServer(siteUrl, libraryName, documentName, documentImageType, baseformat, userName, passWord, overwrite, metainfo);
if (res == null)
{
Result.listcount = 0;
Result.errorcode = 1;
Result.errormessage = "Failed: File Could not Upload to DMS";
return Result;
}
if (res.status == true)
{
TEDMSDocument dmsDoc = new TEDMSDocument();
dmsDoc.DMSID = res.documentID;
dmsDoc.DMSURL = res.documentURL;
dmsDoc.DocumentName = res.tiltle;
dmsDoc.DocumentType = "CustomerDataSheet";
dmsDoc.KeyID = CurrentApplicant.ContactID;
dmsDoc.SAPCustomerID = RefData.SAPCustomerID;
dmsDoc.UploadedBy = Convert.ToInt32(authuser);
dmsDoc.UploadedOn = DateTime.Now;
dmsDoc.DMSDocumentID = res.ID;
dmsDoc.DMSDocumentUniqueID = res.uniqueID;
context.TEDMSDocuments.Add(dmsDoc);
context.SaveChanges();
if (dmsDoc.UniqueID != 0) {
Result.listcount = dmsDoc.UniqueID;
Result.errorcode = 0;
Result.errormessage = "Successful";
return Result;
}
else
{
Result.listcount = 0;
Result.errorcode = 1;
Result.errormessage = "Failed: File Could not Upload to DMS";
return Result;
}
}
else
{
Result.listcount = 0;
Result.errorcode = 1;
Result.errormessage = "Failed: File Could not Upload to DMS";
return Result;
}
}
catch (Exception ex) {
excepton.RecordUnHandledException(ex);
Result.listcount = 0;
Result.errorcode = 1;
Result.errormessage = "Failed: Something Went Wrong";
Result.exceptionMessage = "Exception: " + ex.Message;
return Result;
}
}
public List<DailyInvoiceResult> SAPReceiptsGet(int authuser, DateTime Today)
{
List<DailyInvoiceResult> Result = new List<DailyInvoiceResult>();
try
{
List<TESAPReceipt> FullSAPReceipts = new List<TESAPReceipt>();
List<TESAPReceipt> List1 = new List<TESAPReceipt>();
List<TESAPReceipt> List2 = new List<TESAPReceipt>();
List<TESAPReceipt> List3 = new List<TESAPReceipt>();
if(Today==null) Today = DateTime.Now;
FullSAPReceipts = context.TESAPReceipts.Where(a =>a.PostingDate >= Today && a.PostingDate <= Today).ToList();
List1 = FullSAPReceipts.Where(a => !a.Status.Equals("SAP Receipt")).ToList();
foreach (TESAPReceipt Data in List1)
{
TECollection CollectionData = new TECollection();
CollectionData = context.TECollections.Where(a => a.ReceiptID == Data.AccountingDocumentNumber && a.SAPCustomerID == Data.CustomerNumber && a.IsDeleted == false).FirstOrDefault();
if(CollectionData != null)
{
DailyInvoiceResult SubResult = new DailyInvoiceResult();
SubResult.SAPReceiptID = Data.ID;
SubResult.CollectionsID = CollectionData.CollectionsID;
SubResult.ContextID = CollectionData.ContextID;
SubResult.ProjectID = CollectionData.ProjectID;
SubResult.UnitID = CollectionData.UnitID;
SubResult.SAPCustomerID = CollectionData.SAPCustomerID;
SubResult.PaymentMode = CollectionData.PaymentMode;
SubResult.ReceiptID = CollectionData.ReceiptID;
SubResult.DraweeBank = CollectionData.DraweeBank;
SubResult.SAPBankCode = CollectionData.SAPBankCode;
SubResult.InstrumentNumber = CollectionData.InstrumentNumber;
SubResult.InstrumentDate = CollectionData.InstrumentDate;
SubResult.Amount = CollectionData.Amount;
SubResult.ReceivedOn = CollectionData.ReceivedOn;
SubResult.ReceivedBy = CollectionData.ReceivedBy;
SubResult.PayeeBank = CollectionData.PayeeBank;
SubResult.PayeeName = CollectionData.PayeeName;
SubResult.PaidBy = CollectionData.PaidBy;
SubResult.ISTDS = CollectionData.ISTDS;
SubResult.ReceiptDocumentID = CollectionData.ReceiptDocumentID;
SubResult.ClearedBy = CollectionData.ClearedBy;
SubResult.ClearedOn = CollectionData.ClearedOn;
SubResult.Status = CollectionData.Status;
SubResult.ReversedOn = CollectionData.ReversedOn;
SubResult.Comments = CollectionData.Comments;
SubResult.LastModifiedOn = CollectionData.LastModifiedOn;
SubResult.LastModifiedBy_Id = CollectionData.LastModifiedBy_Id;
SubResult.PANNo = CollectionData.PANNo;
SubResult.LeadID = CollectionData.OTCLead;
SubResult.OTCFlag = CollectionData.OTCFLAG;
var UserData = context.UserProfiles.Where(a => a.UserId == CollectionData.LastModifiedBy_Id && a.IsDeleted == false).FirstOrDefault();
if (UserData != null)
{
SubResult.UserName = UserData.UserName;
SubResult.email = UserData.email;
}
var ProjectData = context.TEProjects.Where(a => a.ProjectID == CollectionData.ProjectID && a.IsDeleted==false).FirstOrDefault();
if (ProjectData != null)
{
SubResult.ProjectShortName = ProjectData.ProjectShortName;
SubResult.ProjectName = ProjectData.ProjectName;
SubResult.ProjectColor = ProjectData.ProjectColor;
SubResult.Logo = ProjectData.Logo;
var CompanyDetails = context.TECompanies.Where(a => a.Uniqueid == ProjectData.CompanyID && a.IsDeleted == false).FirstOrDefault();
if (CompanyDetails != null)
{
SubResult.CompanyAddress = CompanyDetails.Address;
SubResult.CompanyPAN = CompanyDetails.PAN;
SubResult.CompanyCIN = CompanyDetails.CIN;
SubResult.CompanyName = CompanyDetails.Name;
}
}
if (CollectionData.UnitID!=null) SubResult.UnitNumber = context.TEUnits.Where(a => a.UnitID == CollectionData.UnitID && a.IsDeleted == false).Select(a=>a.UnitNumber).FirstOrDefault(); ;
if (CollectionData.OTCFLAG == true)
{
var LeadData = context.TELeads.Where(a => a.LeadID == CollectionData.OTCLead).FirstOrDefault();
if (LeadData != null)
{
SubResult.OfferTitleName = "OTC";
SubResult.OfferCustomerName = LeadData.CallName;
SubResult.CustomerEmailId = context.TEContactEmails.Where(a => a.TEContact == LeadData.ContactID && a.IsDeleted==false).Select(a=>a.Emailid).FirstOrDefault();
}
}
else
{
var LeadData = context.TEOffers.Where(a => a.SAPCustomerID == CollectionData.SAPCustomerID && a.isOrderInUse==true && a.IsDeleted==false).FirstOrDefault();
if (LeadData != null)
{
SubResult.OfferTitleName = LeadData.OfferTitleName;
SubResult.OfferCustomerName = LeadData.OfferCustomerName;
var email = (from ld in context.TELeads
join contemail in context.TEContactEmails on ld.ContactID equals contemail.TEContact
where ld.LeadID == LeadData.LeadID && contemail.IsDeleted == false
select contemail.Emailid).FirstOrDefault();
SubResult.CustomerEmailId = email;
}
}
Result.Add(SubResult);
}
}
List2 = FullSAPReceipts.Where(a => a.Status.Equals("SAP Receipt")).ToList();
foreach (TESAPReceipt Data in List2)
{
DailyInvoiceResult SubResult = new DailyInvoiceResult();
SubResult.SAPReceiptID = Data.ID;
SubResult.SAPCustomerID = Data.CustomerNumber;
SubResult.ReceiptID = Data.AccountingDocumentNumber;
SubResult.Amount = Data.Amount;
SubResult.ReceivedOn = Data.PostingDate;
if(Data.Amount < 0)
{
SubResult.Status = "Reversed";
}
else
{
SubResult.Status = "Cleared";
}
SubResult.PaymentMode = Data.PaymentMethod;
var ProjectData = context.TEProjects.Where(a => a.SAPCUSTOMERID == Data.CustomerNumber && a.IsDeleted == false).FirstOrDefault();
if (ProjectData != null)
{
SubResult.ProjectID = ProjectData.ProjectID;
SubResult.ProjectShortName = ProjectData.ProjectShortName;
SubResult.ProjectName = ProjectData.ProjectName;
SubResult.ProjectColor = ProjectData.ProjectColor;
SubResult.Logo = ProjectData.Logo;
SubResult.UnitID = null;
var CompanyDetails = context.TECompanies.Where(a => a.Uniqueid == ProjectData.CompanyID && a.IsDeleted == false).FirstOrDefault();
if (CompanyDetails != null)
{
SubResult.CompanyAddress = CompanyDetails.Address;
SubResult.CompanyPAN = CompanyDetails.PAN;
SubResult.CompanyCIN = CompanyDetails.CIN;
SubResult.CompanyName = CompanyDetails.Name;
}
SubResult.OfferTitleName = "OTC";
SubResult.OfferCustomerName = ProjectData.ProjectName;
SubResult.CustomerEmailId = null;
SubResult.OTCFlag = true;
}
else
{
var LeadData = context.TEOffers.Where(a => a.SAPCustomerID == Data.CustomerNumber && a.isOrderInUse == true && a.IsDeleted == false).FirstOrDefault();
if (LeadData != null)
{
SubResult.OfferTitleName = LeadData.OfferTitleName;
SubResult.OfferCustomerName = LeadData.OfferCustomerName;
var email = (from ld in context.TELeads
join contemail in context.TEContactEmails on ld.ContactID equals contemail.TEContact
where ld.LeadID == LeadData.LeadID && contemail.IsDeleted == false
select contemail.Emailid).FirstOrDefault();
SubResult.CustomerEmailId = email;
var ProjectDataa = context.TEProjects.Where(a => a.ProjectID == LeadData.ProjectID && a.IsDeleted == false).FirstOrDefault();
if (ProjectDataa != null)
{
SubResult.ProjectID = ProjectDataa.ProjectID;
SubResult.ProjectShortName = ProjectDataa.ProjectShortName;
SubResult.ProjectName = ProjectDataa.ProjectName;
SubResult.ProjectColor = ProjectDataa.ProjectColor;
SubResult.Logo = ProjectDataa.Logo;
var CompanyDetails = context.TECompanies.Where(a => a.Uniqueid == ProjectDataa.CompanyID && a.IsDeleted == false).FirstOrDefault();
if (CompanyDetails != null)
{
SubResult.CompanyAddress = CompanyDetails.Address;
SubResult.CompanyPAN = CompanyDetails.PAN;
SubResult.CompanyCIN = CompanyDetails.CIN;
SubResult.CompanyName = CompanyDetails.Name;
}
SubResult.ContextID = LeadData.OfferID;
SubResult.OTCFlag = false;
SubResult.OfferTitleName = LeadData.OfferTitleName;
SubResult.OfferCustomerName = LeadData.OfferCustomerName;
SubResult.CustomerEmailId = null;
}
if (LeadData.UnitID != null) SubResult.UnitNumber = context.TEUnits.Where(a => a.UnitID == LeadData.UnitID && a.IsDeleted == false).Select(a => a.UnitNumber).FirstOrDefault(); ;
}
}
Result.Add(SubResult);
}
Result=Result.OrderBy(a => a.SAPReceiptID).ToList(); ;
return Result;
}
catch (Exception ex)
{
excepton.RecordUnHandledException(ex);
return Result;
}
}
public string monthToDtLst(DateTime Today)
{
string Res = string.Empty;
DateTime? firstDayOfMonth = new DateTime(Today.Year, Today.Month, 1);
var monthToDtLst = (from collctn in context.TESAPReceipts
where (collctn.PostingDate >= firstDayOfMonth && collctn.PostingDate <= Today
)
select new
{
collctn.Amount
}).ToList();
decimal? totalAmntMonthTodate = 0;
if (monthToDtLst.Count > 0)
{
totalAmntMonthTodate = monthToDtLst.Sum(a => a.Amount);
Res = String.Format("{0:F2}", totalAmntMonthTodate);
}
return Res;
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class StartGame : MonoBehaviour
{
public static bool isMute = false;
public Button speakerButton;
public Sprite[] speakerImages;
private float dispalyHeight, displayWidth;
// Start is called before the first frame update
void Start()
{
dispalyHeight = 0.85f * Screen.height;
displayWidth = 0.85f * Screen.width;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0)) {
if(Input.mousePosition.y > dispalyHeight && Input.mousePosition.x > displayWidth) {
OnClickMuteButton();
}
else {
SceneManager.LoadScene("Main");
}
}
}
private void OnClickMuteButton() {
if(!isMute) {
AudioListener.volume = 0;
speakerButton.image.sprite = speakerImages[1];
isMute = true;
}
else {
AudioListener.volume = 1;
speakerButton.image.sprite = speakerImages[0];
isMute = false;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Bomb_Timer : MonoBehaviour
{
public Text timerText;
// Update is called once per frame
void Update()
{
if(gameObject.activeSelf)
{
timerText.text = World.currentWorld.bombTimer.ToString("0");
GetComponent<Text>().color = Color.Lerp(Color.yellow, Color.red, Mathf.PingPong(Time.time, 1));
}
}
}
|
using gView.Server.Services.Hosting;
using gView.Server.Services.Logging;
using gView.Server.Services.MapServer;
using gView.Server.Services.Security;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace gView.Server.Extensions.DependencyInjection
{
static public class ServiceCollectionExtensions
{
static public IServiceCollection AddMapServerService(this IServiceCollection services,
Action<MapServerManagerOptions> configAction)
{
services.Configure<MapServerManagerOptions>(configAction);
services.AddSingleton<MapServiceManager>();
services.AddSingleton<EncryptionCertificateService>();
services.AddSingleton<MapServiceDeploymentManager>();
services.AddTransient<UrlHelperService>();
services.AddTransient<LoginManager>();
services.AddTransient<AccessControlService>();
services.AddTransient<MapServicesEventLogger>();
return services;
}
static public IServiceCollection AddAccessTokenAuthService(this IServiceCollection services,
Action<AccessTokenAuthServiceOptions> configAction)
{
services.Configure<AccessTokenAuthServiceOptions>(configAction);
return services.AddTransient<AccessTokenAuthService>();
}
static public IServiceCollection AddPerformanceLoggerService(this IServiceCollection services,
Action<PerformanceLoggerServiceOptions> configAction)
{
services.Configure<PerformanceLoggerServiceOptions>(configAction);
return services.AddSingleton<PerformanceLoggerService>();
}
}
}
|
using System;
public class EventDetails
{
// timeUntil
// scene
private int timeUntil;
private string scene;
public EventDetails(int timeUntil, string scene)
{
this.timeUntil = timeUntil;
this.scene = scene;
}
public string GetScene()
{
return scene;
}
public int GetTimeUntil()
{
return timeUntil;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Conarte.Conarte
{
public partial class Aplicacion
{
private int ? _Id;
public int ? Id
{
get {
return _Id;
}
set {
_Id = value;
}
}
private string _NombreAplicacion;
public string NombreAplicacion
{
get {
return _NombreAplicacion;
}
set {
_NombreAplicacion = value;
}
}
private int ? _NumeroMaximoIntentosFallidos;
public int ? NumeroMaximoIntentosFallidos
{
get {
return _NumeroMaximoIntentosFallidos;
}
set {
_NumeroMaximoIntentosFallidos = value;
}
}
private int ? _TiempoEsperaBloqueo;
public int ? TiempoEsperaBloqueo
{
get {
return _TiempoEsperaBloqueo;
}
set {
_TiempoEsperaBloqueo = value;
}
}
private string _URL;
public string URL
{
get {
return _URL;
}
set {
_URL = value;
}
}
private string _CuentaCorreoPredeterminada;
public string CuentaCorreoPredeterminada
{
get {
return _CuentaCorreoPredeterminada;
}
set {
_CuentaCorreoPredeterminada = value;
}
}
}
}
|
/***********************************************************************
* Module: Renovation.cs
* Author: LukaRA252017
* Purpose: Definition of the Class Manager.Renovation
***********************************************************************/
using System;
namespace Model.Manager
{
public class RenovationPeriod
{
public Room room { get; set; }
public DateTime BeginDate { get; set; }
public DateTime EndDate { get; set; }
public RenovationPeriod()
{
}
public RenovationPeriod(Room room,DateTime begin,DateTime end)
{
if (room == null)
{
this.room = new Room();
}
else
{
this.room = new Room(room);
}
BeginDate = begin;
EndDate = end;
}
public RenovationPeriod(RenovationPeriod renovationPeriod)
{
if (renovationPeriod.room == null)
{
room = new Room();
}
else
{
room = new Room(renovationPeriod.room);
}
room = new Room(renovationPeriod.room);
BeginDate = renovationPeriod.BeginDate;
EndDate = renovationPeriod.EndDate;
}
}
}
|
using System;
using OptionalTypes.JsonConverters.Tests.TestDtos;
using Xunit;
namespace OptionalTypes.JsonConverters.Tests.Unit.Read
{
public static class EnumTests
{
[Fact]
public static void Convert_GivenGuid_ShouldSetValue()
{
//Arrange
var json = @"{""Value"": ""70B1B6FD-11E8-4334-B157-5E1CD60ADE03""}";
//Act
var dto = SerialisationUtils.Deserialize<GuidDto>(json);
//Assert
Assert.Equal(dto.Value.Value, new Guid("70B1B6FD-11E8-4334-B157-5E1CD60ADE03"));
}
[Fact]
public static void Convert_GivenNotAValidGuid_ShouldThrowMeaningfulException()
{
//Arrange
var json = @"{""Value"": ""YouWillNotFindMe""}";
//Act
Assert.Throws<CannotCreateGuidException>(() => SerialisationUtils.Deserialize<GuidDto>(json));
}
}
} |
using Welic.App.Models.Schedule;
using Welic.App.ViewModels;
using Welic.App.ViewModels.Base;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Welic.App.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ListEventsPage : ContentPage
{
public ListEventsPage ()
{
InitializeComponent ();
BindingContext = ViewModelLocator.Resolve<ListEventsViewModel>();
}
private void ListViewStart_OnItemTapped(object sender, ItemTappedEventArgs e)
{
var item = (ScheduleDto)e.Item;
if (item != null)
(BindingContext as ListEventsViewModel)?.OpenSchedule(item);
}
}
} |
using System;
using System.Diagnostics;
using ProgFrog.Core.TaskRunning.Runners;
using ProgFrog.Interface.TaskRunning;
using ProgFrog.Interface.TaskRunning.Runners;
namespace ProgFrog.Core.TaskRunning
{
public class StandardOutputStreamReader : IOutputReader
{
public IProcess Process { get; private set; }
public StandardOutputStreamReader(IProcess process)
{
Process = process;
}
public StandardOutputStreamReader()
{
}
public string Read()
{
if (Process.RedirectStandardOutput == false || Process.UseShellExecute != false)
{
throw new ApplicationException("Cannot read from this process std output");
}
return Process.StandardOutput.ReadToEnd();
}
public void Configure(IProcessTaskRunner runner)
{
Process = runner.Process;
}
}
}
|
using BencodeNET.Torrents;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TorrentDotNet.Util
{
public static class Insertion
{
public static void InsertInDataGrid(DataGridView grid, SingleFileInfo torrent, MultiFileInfoList torrents = null)
{
var column = ((DataGridViewComboBoxColumn)grid.Columns[2]);
grid.Rows.Add(new object[] { torrent.FileName, Formatter.BytesToEnglish(torrent.FileSize), "Normal"});
var cell = (DataGridViewComboBoxCell)grid.Rows[0].Cells[2];
// var test = grid;
//column.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
//column.Items.AddRange(new string[] { "Normal", "High", "Maximum" });
//column.MaxDropDownItems = 3;
/*
grid.DefaultCellStyle.SelectionBackColor = Color.White;
grid.DefaultCellStyle.SelectionForeColor = Color.Black;
*/
}
}
}
|
namespace RosPurcell.Web.Controllers.Pages
{
using System.Web.Mvc;
using RosPurcell.Web.Constants.Caching;
using RosPurcell.Web.Controllers.Pages.Base;
using RosPurcell.Web.ViewModels.Pages;
public class ContentPageController : BasePageController
{
[OutputCache(CacheProfile = CacheKeys.ShortTime)]
public ActionResult ContentPage()
{
var vm = ViewModelBuilder.BuildPage<ContentPageViewModel>(CurrentPage);
return View(vm);
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using Castle.Components.DictionaryAdapter;
#nullable disable
namespace Models.FicheModel
{
public partial class Sort
{
//public int IdSort { get; set; }
public int IdFiche { get; set; }
public byte NiveauSort { get; set; }
public string NomSort { get; set; }
public string DescriptionSort { get; set; }
public virtual Fiche IdFicheNavigation { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper.DBContext;
using EBS.Domain.Entity;
using EBS.Infrastructure.Extension;
namespace EBS.Domain.Service
{
public class StoreService
{
IDBContext _db;
public StoreService(IDBContext dbContext)
{
this._db = dbContext;
}
public void Create(Store model)
{
if (_db.Table.Exists<Store>(n => n.Name == model.Name))
{
throw new Exception("名称重复!");
}
// 生成门店编码
var firstAreaId = model.AreaId.Substring(0,2);
var result= _db.Table.FindAll<Store>(n => n.AreaId.Like(firstAreaId + "%"));
var maxAreaIdNumber = 0;
if(result.Count()>0)
{
maxAreaIdNumber = result.Max(n=>n.Number);
}
model.GenerateNewCode(maxAreaIdNumber);
_db.Insert(model);
}
public void Update(Store model,string oldAreaId)
{
if (_db.Table.Exists<Store>(n => n.Name == model.Name && n.Id != model.Id))
{
throw new Exception("名称重复!");
}
if (model.AreaId != oldAreaId)
{
//如果区域发生改变,重新生成新的 code
var firstAreaId = model.AreaId.Substring(0, 2);
var result = _db.Table.FindAll<Store>(n => n.AreaId.Like(firstAreaId + "%"));
var maxAreaIdNumber = 0;
if (result.Count() > 0)
{
maxAreaIdNumber = result.Max(n => n.Number);
}
model.GenerateNewCode(maxAreaIdNumber);
}
_db.Update(model);
}
public void Delete(string ids)
{
if (string.IsNullOrEmpty(ids))
{
throw new Exception("id 参数为空");
}
var arrIds = ids.Split(',').ToIntArray();
_db.Delete<Store>(arrIds);
_db.SaveChange();
//删除权限
}
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace Xamarin.Android.Prepare
{
class Step_PrepareLocal : Step
{
public Step_PrepareLocal ()
: base ("Preparing local components")
{}
protected override async Task<bool> Execute(Context context)
{
var msbuild = new MSBuildRunner (context);
string xfTestPath = Path.Combine (BuildPaths.XamarinAndroidSourceRoot, "tests", "Xamarin.Forms-Performance-Integration", "Xamarin.Forms.Performance.Integration.csproj");
if (!await msbuild.Restore (projectPath: xfTestPath, logTag: "xfperf", binlogName: "prepare-local"))
return false;
// The Xamarin.Forms PackageReference version varies based on the value of $(BundleAssemblies)
return await msbuild.Restore (
projectPath: xfTestPath,
logTag: "xfperfbundle",
arguments: new List<string> { "-p:BundleAssemblies=true" },
binlogName: "prepare-local-bundle"
);
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
public class Vernietigbaar : MonoBehaviour
{
// base components
[HideInInspector] public Transform myTransform;
[HideInInspector] public GameObject myGameObject;
// references
[Header("references")]
public FlameableScript myFlameableScript;
// settings
[Header("settings")]
public float radius;
public int coinDropCount;
public Vector3 hitOffset;
public float whiteOrbScale;
// drop type
public enum DropType { Coin, Tear, Key, Dust, Donut };
[System.Serializable]
public struct DropData
{
public DropType dropType;
public int weight;
}
public List<DropData> possibleDropDatas;
[HideInInspector] public DropType myDropType;
// audio
public enum Type { Wood, Clay, Stone, Metal, Bone };
[Header("audio")]
public Type myType;
public float pitchMin;
public float pitchMax;
public float volumeMin;
public float volumeMax;
void Start ()
{
myTransform = transform;
myGameObject = gameObject;
// define drop type
WeightedRandomBag<DropType> possibleDropTypes = new WeightedRandomBag<DropType>();
for ( int i = 0; i < possibleDropDatas.Count; i ++ )
{
DropData curDropData = possibleDropDatas[i];
possibleDropTypes.AddEntry(curDropData.dropType,curDropData.weight);
}
if (SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.Hungry) && (TommieRandom.instance.RandomValue(1f) <= .1f) )
{
possibleDropTypes.AddEntry(DropType.Donut,4);
}
myDropType = possibleDropTypes.Choose();
// lucky blessing
if ( myDropType == DropType.Coin && (SetupManager.instance != null && SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.Lucky)) )
{
if ( TommieRandom.instance.RandomValue(1f) <= .33f )
{
coinDropCount++;
}
}
// store
Store();
}
void Store ()
{
GameManager.instance.allVernietigbaarScripts.Add(this);
}
public void Destroy ()
{
// waar gaan die dingen droppen
switch (myDropType)
{
case DropType.Coin:
for (int i = 0; i < coinDropCount; i++)
{
GameObject coinO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.coinPrefab[0], myTransform.position + hitOffset, Quaternion.identity, 1f);
Stuiterbaar stuiterbaarScript = coinO.GetComponent<Stuiterbaar>();
if (stuiterbaarScript != null)
{
float spawnSideForceOffMax = .05f;
float spawnUpForceOffMax = .075f;
float xDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f));
float zDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f));
float xAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax);
float zAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax);
stuiterbaarScript.forceCur.x += (xAdd * xDir);
stuiterbaarScript.forceCur.y += TommieRandom.instance.RandomRange(spawnUpForceOffMax * .5f, spawnUpForceOffMax);
stuiterbaarScript.forceCur.z += (zAdd * zDir);
}
}
break;
case DropType.Key:
for (int i = 0; i < 1; i++)
{
GameObject keyO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.keyPrefab[0], myTransform.position + hitOffset, Quaternion.identity, 1f);
Stuiterbaar stuiterbaarScript = keyO.GetComponent<Stuiterbaar>();
if (stuiterbaarScript != null)
{
float spawnSideForceOffMax = .05f;
float spawnUpForceOffMax = .075f;
float xDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f));
float zDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f));
float xAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax);
float zAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax);
stuiterbaarScript.forceCur.x += (xAdd * xDir);
stuiterbaarScript.forceCur.y += TommieRandom.instance.RandomRange(spawnUpForceOffMax * .5f, spawnUpForceOffMax);
stuiterbaarScript.forceCur.z += (zAdd * zDir);
}
}
break;
case DropType.Dust:
PrefabManager.instance.SpawnPrefab(PrefabManager.instance.dustImpactParticlesPrefab[0], myTransform.position + hitOffset, Quaternion.identity, 1f);
AudioManager.instance.PlaySoundAtPosition(myTransform.position + hitOffset,BasicFunctions.PickRandomAudioClipFromArray(AudioManager.instance.fireMagicImpactClips),.6f,.9f,.2f,.225f);
break;
case DropType.Donut:
int donutCount = 1;
for (int i = 0; i < donutCount; i++)
{
GameObject donutO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.donutPrefab[0], myTransform.position + hitOffset, Quaternion.identity, 1f);
Stuiterbaar stuiterbaarScript = donutO.GetComponent<Stuiterbaar>();
if (stuiterbaarScript != null)
{
float spawnSideForceOffMax = .05f;
float spawnUpForceOffMax = .075f;
float xDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f));
float zDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f));
float xAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax);
float zAdd = TommieRandom.instance.RandomRange(spawnSideForceOffMax * .25f, spawnSideForceOffMax);
stuiterbaarScript.forceCur.x += (xAdd * xDir);
stuiterbaarScript.forceCur.y += TommieRandom.instance.RandomRange(spawnUpForceOffMax * .5f, spawnUpForceOffMax);
stuiterbaarScript.forceCur.z += (zAdd * zDir);
}
}
break;
}
// particles
PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab, myTransform.position + hitOffset, Quaternion.identity, whiteOrbScale);
PrefabManager.instance.SpawnPrefab(PrefabManager.instance.magicImpactParticlesPrefab[2], myTransform.position + hitOffset, Quaternion.identity, 1f * whiteOrbScale);
// audio
AudioClip[] clipsUse = null;
switch ( myType )
{
case Type.Wood: clipsUse = AudioManager.instance.woodBreakClips; break;
case Type.Clay: clipsUse = AudioManager.instance.clayBreakClips; break;
case Type.Stone: clipsUse = AudioManager.instance.stoneBreakClips; break;
case Type.Metal: clipsUse = AudioManager.instance.metalBreakClips; break;
}
AudioManager.instance.PlaySoundAtPosition(myTransform.position, BasicFunctions.PickRandomAudioClipFromArray(clipsUse),pitchMin,pitchMax,volumeMin,volumeMax);
// clear fire?
if ( myFlameableScript != null && myFlameableScript.myFireScript != null )
{
myFlameableScript.myFireScript.Clear();
}
// doei druif
if ( myGameObject != null )
{
Destroy(myGameObject);
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.cyan;
Gizmos.DrawWireSphere(transform.position + hitOffset,radius);
}
}
|
using System;
using System.ComponentModel;
using System.Xml.Serialization;
namespace KartObjects.Entities.Documents
{
/// <summary>
/// Документ
/// </summary>
public class Document:BaseDocument
{
public Document(): base()
{
IsNew = false;
}
public long? IdSupplier { get; set; }
/// <summary>
/// Сумма с наценкой\скидкой
/// </summary>
public virtual decimal MarginSumDoc
{
get;
set;
}
/// <summary>
/// Статус накладной (оприходована 1, разоприходована 0)
/// </summary>
[DisplayName("Статус")]
public int Status
{
get;
set;
}
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
[XmlIgnore]
public bool IsAccept
{
get
{
return Status == 1;
}
}
/// <summary>
/// Дата внешнего основания
/// </summary>
//[DisplayName("Дата внешнего основания")]
public DateTime? ExtDate
{
get;
set;
}
/// <summary>
/// Признак того что документ новый
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
[XmlIgnore]
public bool IsNew
{
get;
set;
}
public virtual Document GetDocumentInstance()
{
return this;
}
/// <summary>
/// Организация
/// </summary>
public long? IdOrganization
{
get;
set;
}
/// <summary>
/// Пользователь
/// </summary>
public long IdUser
{
get;
set;
}
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
[XmlIgnore]
public virtual decimal SumNDS
{
get
{
return Sum10NDS+Sum18NDS;
}
}
public virtual decimal Sum10NDS
{
get;
set;
}
public virtual decimal Sum18NDS
{
get;
set;
}
public decimal TotalWeight { get; set; }
/// <summary>
/// Дата изменения документа
/// </summary>
[DBIgnoreAutoGenerateParam]
public DateTime ModificationTime
{
get;
set;
}
[DBIgnoreAutoGenerateParam]
public Guid? guid
{
get;
set;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using com.Sconit.Entity.MD;
using com.Sconit.Entity.MRP.MD;
//TODO: Add other using statements here
namespace com.Sconit.Entity.MRP.TRANS
{
public partial class RccpMiPlan
{
public double CheQty
{
get { return TotalQty / CheRateQty; }
}
public double TotalQty
{
get { return Qty + SubQty; }
}
//计划工时
public double RequireTime
{
get { return (this.TotalQty / this.CheRateQty) * this.WorkHour; }
}
//负荷率
public double Load
{
get { return RequireTime / UpTime; }
}
//RequireTime/UpTime
//不考虑同一物料有多条委外供应商
public MrpFlowDetail SubFlowDetail { get; set; }
}
}
|
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace ProyectoSCA_Navigation.Clases
{
public class AportacionObligatoria : Aportacion
{
int idMonto_;
public int IdMonto
{
get { return idMonto_; }
set { idMonto_ = value; }
}
montoAportacionObligatoria monto;
public montoAportacionObligatoria MontoAportacionObligatoria
{
get { return monto; }
set { monto = value; }
}
String fechaPlazo_;
public String FechaPlazo
{
get { return fechaPlazo_; }
set { fechaPlazo_ = value; }
}
}
}
|
using UnityEditor;
using UnityEngine;
namespace AtomosZ.OhBehave.EditorTools
{
public class InverterNodeWindow : NodeWindow, IParentNodeWindow
{
public InverterNodeWindow(NodeEditorObject nodeObj) : base(nodeObj) { }
public override bool ProcessEvents(Event e)
{
inPoint.ProcessEvents(e);
outPoint.ProcessEvents(e);
bool saveNeeded = false;
switch (e.type)
{
case EventType.MouseDown:
if (e.button == 0)
{
LeftClick(e);
}
else if (e.button == 1)
{
RightClick(e);
}
break;
case EventType.MouseUp:
if (isDragged)
{
saveNeeded = true;
e.Use();
}
isDragged = false;
break;
case EventType.MouseDrag:
if (e.button == 0 && isDragged)
{
Drag(e.delta);
e.Use();
}
break;
case EventType.KeyDown:
if (isSelected && e.keyCode == KeyCode.Delete)
{
treeBlueprint.DeleteNode(nodeObject);
}
break;
}
return saveNeeded;
}
public override void OnGUI()
{
if (refreshConnection)
{
RefreshConnection();
}
Color clr = GUI.backgroundColor;
if (isSelected)
GUI.backgroundColor = bgColor;
var content = new GUIContent("Name: " + nodeName, nodeObject.description);
GUILayout.BeginArea(GetRect(), content, currentStyle);
{
CreateTitleBar();
NodeType newType = (NodeType)EditorGUILayout.EnumPopup(nodeObject.nodeType);
if (newType != nodeObject.nodeType)
{
nodeObject.ChangeNodeType(newType);
}
if (nodeObject.HasChildren() && nodeObject.GetChildren().Count == 1)
GUILayout.Label("NOT " + treeBlueprint.GetNodeObjectByIndex(nodeObject.GetChildren()[0]).displayName);
else
GUILayout.Label("Dangeling Inverter");
if (Event.current.type == EventType.Repaint)
{
Rect lastrect = GUILayoutUtility.GetLastRect();
nodeObject.windowRect.height = lastrect.yMax + 10;
}
}
GUILayout.EndArea();
GUI.backgroundColor = clr;
inPoint.OnGUI();
outPoint.OnGUI();
outPoint.DrawConnectionTo(GetChildren(), out int[] newChildOrder); // inverter can only have one child so we could simplify this
}
public override void UpdateChildrenList()
{
// I don't think anything special needs to be done
}
public void CreateChildConnection(NodeWindow newChild)
{
newChild.SetParentWindow(this);
}
}
} |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
namespace ConsoleApi
{
class Program
{
public static string lastError = "";
public static string banks = "";
static void Main(string[] args)
{
GetBanksInfoSync();
Console.WriteLine("Sync data load: " + lastError);
if (banks != "")
{
Banks currentBank = JsonConvert.DeserializeObject<Banks>(banks);
Console.WriteLine(currentBank.КодБанку);
foreach (Ліцензії item in currentBank.Ліцензії)
{
Console.WriteLine("НомерБланка: " + item.БанківськаЛіцензія.НомерБланка);
foreach (Дозволи itemd in item.Дозволи)
{
foreach (KeyValuePair<string,string> itemPo in itemd.ПерелікОпераційДозвола)
{
Console.WriteLine(itemPo.Key + " : "+itemPo.Value);
}
Console.WriteLine("---");
}
Console.WriteLine("-----");
}
}
else
{
Console.WriteLine("No bank data available");
}
Console.ReadLine();
}
private static void GetBanksInfoSync()
{
lastError = "";
WebClient client = new WebClient();
try
{
using (Stream stream = client.OpenRead("https://raw.githubusercontent.com/dchaplinsky/nbu.rocks/master/www/jsons/307123.json"))
{
using (StreamReader reader = new StreamReader(stream))
{
banks = reader.ReadToEnd();
}
}
lastError = "successfuly";
}
catch (Exception e)
{
lastError = e.Message;
}
}
}
}
|
namespace IconCreator.Core.Domain.Enums
{
public enum ImageStyles
{
Flat,
Classic
}
}
|
using UnityEngine;
namespace Common
{
public static class RectUtility
{
public static Rect With(this Rect r, float? x = null, float? y = null, float? width = null, float? height = null) =>
new Rect((x ?? r.x), (y ?? r.y), (width ?? r.width), (height ?? r.height));
public static Rect Expand(this Rect r, float? x = null, float? y = null, float? width = null, float? height = null) =>
new Rect((r.x - (x ?? 0)), (r.y - (y ?? 0)), (r.width + (width ?? 0)), (r.height + (height ?? 0)));
public static Rect Shrink(this Rect r, float? x = null, float? y = null, float? width = null, float? height = null) =>
new Rect((r.x + (x ?? 0)), (r.y + (y ?? 0)), (r.width - (width ?? 0)), (r.height - (height ?? 0)));
/// <summary>Takes a region from the specified sides.</summary>
public static Rect Take(this Rect r, float? left, float? top, float? right, float? bottom)
{
Rect r2 = new Rect();
if (left.HasValue) r2.xMax = r.xMin + left.Value;
if (right.HasValue) r2.xMin = r.xMin + r.width - right.Value;
if (top.HasValue) r2.xMin = r.yMin + r.height - top.Value;
if (bottom.HasValue) r2.xMax = r.yMin + bottom.Value;
return r2;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Serialization.Tests.Entities
{
public class Opcional
{
public virtual int CodOpcional { get; set; }
public virtual string Name { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyHeroKill.Model.Skills
{
public class BudaoSkill : BaseSkill
{
public BudaoSkill()
{
this.Name = "补刀";
this.AddAttackDistance = 0;
this.AddDamage = 0;
this.AddLife = 0;
this.AddAttackCount = 0;
this.CanProvideJuedou = false;
this.CanProvideSha = false;
this.CanProvideShan = false;
this.CanProvideWuxiekeji = false;
this.CanProvideYao = false;
this.SkillType = Enums.ESkillType.MainSkill;
}
public override void OnAskSha()
{
//在询问杀的时候,如果被攻击者在攻击范围内,则可以进行补刀
Console.WriteLine("在询问杀的时候,如果被攻击者在攻击范围内,则可以进行补刀");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Data.Common;
namespace DALBase
{
public abstract class SqlExecutorBase<TParameter, TConnection, TCommand, TAdapter> : IDBExecutor<TParameter, TConnection>, IDisposable
where TParameter : IDataParameter
where TConnection : DbConnection, new()
where TCommand : DbCommand, new()
where TAdapter : DbDataAdapter, new()
{
#region 释放资源-自动关闭数据库连接
// 保证只释放一次
private bool _isDisposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
// .. 占着释放托管资源
}
if (_connection != null)
this._connection.Dispose();
this._isDisposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~SqlExecutorBase()
{
Dispose(false);
}
#endregion
protected TConnection _connection;
protected SqlExecutorBase(string connectionStr)
{
_connection = new TConnection();
_connection.ConnectionString = connectionStr;
}
protected virtual void openConnection()
{
if (_connection.State != ConnectionState.Open)
_connection.Open();
}
protected virtual TCommand createReadyCommand(string cmdText, CommandType type, IEnumerable<TParameter> cmdParams)
{
openConnection();
TCommand cmd = new TCommand();
cmd.Connection = _connection;
cmd.CommandType = type;
cmd.CommandText = cmdText;
if (cmdParams != null)
{
foreach (var item in cmdParams)
{
cmd.Parameters.Add(item);
}
}
return cmd;
}
protected virtual TAdapter createReadySelectAdapter(string text, CommandType type, IEnumerable<TParameter> cmdParams)
{
TAdapter adapter = new TAdapter();
adapter.SelectCommand = createReadyCommand(text, type, cmdParams);
return adapter;
}
/// <summary>
/// 数据库连接
/// </summary>
public TConnection Connection
{
get { return _connection; }
}
/// <summary>
/// 执行命令,返回DataReader
/// </summary>
/// <param name="procName"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public virtual DbDataReader ExecDataReader(string text, CommandType type, IEnumerable<TParameter> cmdParams)
{
return createReadyCommand(text, type, cmdParams)
.ExecuteReader();
}
/// <summary>
/// 执行命令,返回受影响行数
/// </summary>
/// <param name="procName"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public virtual int ExecNonQuery(string text, CommandType type, IEnumerable<TParameter> cmdParams)
{
return createReadyCommand(text, type, cmdParams)
.ExecuteNonQuery();
}
/// <summary>
/// 执行命令,返回第一个值
/// </summary>
/// <param name="procName"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public virtual object ExecScalar(string text, CommandType type, IEnumerable<TParameter> cmdParams)
{
return createReadyCommand(text, type, cmdParams)
.ExecuteScalar();
}
/// <summary>
/// 执行命令,返回DataSet
/// </summary>
/// <param name="procName"></param>
/// <param name="type"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public virtual DataSet ExecDataSet(string text, CommandType type, IEnumerable<TParameter> cmdParams)
{
DataSet ds = new DataSet();
createReadySelectAdapter(text, type, cmdParams)
.Fill(ds);
return ds;
}
/// <summary>
/// 执行命令,返回DataTable
/// </summary>
/// <param name="text"></param>
/// <param name="type"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public virtual DataTable ExecDataTable(string text, CommandType type, IEnumerable<TParameter> cmdParams)
{
DataTable dt = new DataTable();
createReadySelectAdapter(text, type, cmdParams)
.Fill(dt);
return dt;
}
/// <summary>
/// 执行命令,返回实体集合(如果没有数据,则返回一个空列表,而不是NULL)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="text"></param>
/// <param name="type"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public virtual List<T> ExecEntities<T>(string text, CommandType type, IEnumerable<TParameter> cmdParams) where T : new()
{
return createReadyCommand(text, type, cmdParams)
.ExecuteReader()
.ReadAsEntities<T>();
}
#region 重载版本
/// <summary>
/// 执行SQL,返回DataReader
/// </summary>
/// <param name="cmdText"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public DbDataReader TextDataReader(string cmdText, params TParameter[] cmdParams)
{
return ExecDataReader(cmdText, CommandType.Text, cmdParams);
}
/// <summary>
/// 执行SQL,返回受影响函数
/// </summary>
/// <param name="cmdText"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public int TextNonQuery(string cmdText, params TParameter[] cmdParams)
{
return ExecNonQuery(cmdText, CommandType.Text, cmdParams);
}
/// <summary>
/// 执行SQL,返回第一个值
/// </summary>
/// <param name="cmdText"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public object TextScalar(string cmdText, params TParameter[] cmdParams)
{
return ExecScalar(cmdText, CommandType.Text, cmdParams);
}
/// <summary>
/// 执行SQL,返回DataSet
/// </summary>
/// <param name="cmdText"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public DataSet TextDataSet(string cmdText, params TParameter[] cmdParams)
{
return ExecDataSet(cmdText, CommandType.Text, cmdParams);
}
/// <summary>
/// 执行SQL,返回DataTable
/// </summary>
/// <param name="cmdText"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public DataTable TextDataTable(string cmdText, params TParameter[] cmdParams)
{
return ExecDataTable(cmdText, CommandType.Text, cmdParams);
}
/// <summary>
/// 执行SQL,返回实体集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cmdText"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public List<T> TextEntities<T>(string cmdText, params TParameter[] cmdParams) where T : new()
{
return ExecEntities<T>(cmdText, CommandType.Text, cmdParams);
}
/// <summary>
/// 执行存储过程,返回DataReader
/// </summary>
/// <param name="procName"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public DbDataReader ProcDataReader(string procName, params TParameter[] cmdParams)
{
return ExecDataReader(procName, CommandType.StoredProcedure, cmdParams);
}
/// <summary>
/// 执行存储过程,返回受影响行数
/// </summary>
/// <param name="procName"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public int ProcNonQuery(string procName, params TParameter[] cmdParams)
{
return ExecNonQuery(procName, CommandType.StoredProcedure, cmdParams);
}
/// <summary>
/// 执行储存过程,返回第一个值
/// </summary>
/// <param name="procName"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public object ProcScalar(string procName, params TParameter[] cmdParams)
{
return ExecScalar(procName, CommandType.StoredProcedure, cmdParams);
}
/// <summary>
/// 执行存储过程,返回DataSet
/// </summary>
/// <param name="procName"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public DataSet ProcDataSet(string procName, params TParameter[] cmdParams)
{
return ExecDataSet(procName, CommandType.StoredProcedure, cmdParams);
}
/// <summary>
/// 执行存储过程,返回DataTable
/// </summary>
/// <param name="procName"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public DataTable ProcDataTable(string procName, params TParameter[] cmdParams)
{
return ExecDataTable(procName, CommandType.StoredProcedure, cmdParams);
}
/// <summary>
/// 执行存储过程,返回实体集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="procName"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public List<T> ProcEntities<T>(string procName, params TParameter[] cmdParams) where T : new()
{
return ExecEntities<T>(procName, CommandType.StoredProcedure, cmdParams);
}
#endregion
/// <summary>
/// 执行Sql,并返回受影响的行数
/// - 如果发生错误则返回-1,并且事务会自动回滚
/// 该方法只适用于简单的Inset,Delete,Update操作
/// </summary>
/// <param name="cmdText">Sql语句,如果有多条,需自行拼接</param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public virtual int TextNonQueryWithTrans(string cmdText, params TParameter[] cmdParams)
{
openConnection();
DbTransaction trans = _connection.BeginTransaction();
TCommand cmd = createReadyCommand(cmdText, CommandType.Text, cmdParams);
cmd.Transaction = trans;
int success = 0;
try
{
success = cmd.ExecuteNonQuery();
trans.Commit();
}
catch(Exception ex)
{
DbExceptionLog.WriteLine(ex.ToString());
trans.Rollback();
success = -1;
}
return success;
}
}
}
|
using Banco.Contas;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Banco.Relatorios
{
class RelatorioSimples : TemplateRelatorio
{
protected override string Cabecalho()
{
return "Banco Ficticio \t Telefone: 123123123";
}
protected override void Corpo(IList<Conta> contas)
{
foreach (var conta in contas)
{
var str = string.Format("Titular: {0} Saldo: {1}", conta.Titular, Convert.ToString(conta.Saldo));
Console.WriteLine(str);
}
}
protected override string Rodape()
{
return "Banco Ficticio \t Telefone: 123123123";
}
}
}
|
// holds General Functions for the site
public class General {
//gets the caluulation of the tax base on
public static string calculateTax(int intCountryID, int intProvinceID, string strSubTotal, bool boolGetTaxTotalOnly = false) {
string strStateTaxTotal = "0.0";//holds what the tax total for the state will be
string strCurrentStateTaxRate = "0";//holds the current tax rate of the state
//checks if this the counrtry is canada
if (intCountryID == 1)
{
//choose which country the user belongs to
switch (intProvinceID)
{
case 1: //ON
case 8: //NB
case 9: //NL
strCurrentStateTaxRate = "0.13";
break;
case 2: //QC
case 3: //BC
case 4: //AB
case 5: //MB
case 6: //SK
case 11: //NT
case 12: //YT
case 13: //NU
strCurrentStateTaxRate = "0.05";
break;
case 10: //PE
strCurrentStateTaxRate = "0.14";
break;
case 7: //NS
strCurrentStateTaxRate = "0.15";
break;
}//end of switch
}//end of if
//checks if this the counrtry is US
else if (intCountryID == 2)
{
//choose which country the user belongs to
switch (intProvinceID)
{
default:
strCurrentStateTaxRate = "0";
break;
}//end of switch
}//end of else
//calculates the tax for the state base on strSubTotal
strStateTaxTotal = (Convert.ToDecimal(strSubTotal) * Convert.ToDecimal(strCurrentStateTaxRate)).ToString();
//checks if boolGetTaxRate is true if so then just send the the tax rate
if(boolGetTaxTotalOnly == true)
return strStateTaxTotal;
else
return (Convert.ToDecimal(strSubTotal) + Convert.ToDecimal(strStateTaxTotal)).ToString() + "*" + strStateTaxTotal;
}//end of calculateTax()
//checks if the user's email already exist in the databasee
public static bool checkIfEmailExist(string strEmail) {
DataTable dtUserDetails = DAL.getRow("", "Where = '" + DAL.safeSql(strEmail.Trim()) + "'");//holds the users details
//checks if there is any rows found if so then the email does exist
if (dtUserDetails.Rows.Count > 0)
return true;
else
return false;
}//end of checkIfEmailExist()
//crreates a new user with just a first, last name, email
public static int createNewUser(string strFName, string strLName, string strEmail, bool boolNewsletter, bool boolSendEmailToUser, string strEmailTemplateFile = "~/EmailTemplate/thankYouIndividualSignUp.html")
{
string strUserPassword = General.genPassword();//holds the random password that will be sent to the user
string strEmailTemplate = string.Format(File.ReadAllText(HttpContext.Current.Server.MapPath(strEmailTemplateFile)), strFName, strLName, strEmail, strUserPassword);//holds the email tempalte that will be sent to the user
int intUserID = DAL.addUpdateUsers(0, strFName, strLName, "", "", "", "", "", "1", "1", "", "", strEmail, PasswordHash.passwordHashtable.createHash(strUserPassword), "", 2, false, boolNewsletter);//holds the new users id just in case they want to create a Funeral Home
//checks if a email needs to be sent to the user
if(boolSendEmailToUser == true)
//sends the user an email that the have been add to the database
//this is so wrong and needs to change however this is what the client whats
General.sendHTMLMail(strEmail, "Complete Your Registration", strEmailTemplate);
return intUserID;
}//end of createNewUser()
//crreates a new user with just a first, last name, email
public static int createObituaryCoOwner(string strFName, string strLName, string strEmail, bool boolNewsletter, bool boolSendEmailToUser, string strEmailTemplateFile, string obituaryName)
{
string strUserPassword = General.genPassword();//holds the random password that will be sent to the user
string strEmailTemplate = string.Format(File.ReadAllText(HttpContext.Current.Server.MapPath(strEmailTemplateFile)), strFName, strLName, strEmail, strUserPassword, obituaryName);//holds the email tempalte that will be sent to the user
int intUserID = DAL.addUpdateUsers(0, strFName, strLName, "", "", "", "", "", "1", "1", "", "", strEmail, PasswordHash.passwordHashtable.createHash(strUserPassword), "", 2, false, boolNewsletter);//holds the new users id just in case they want to create a Funeral Home
//checks if a email needs to be sent to the user
if (boolSendEmailToUser == true)
//sends the user an email that the have been add to the database
//this is so wrong and needs to change however this is what the client whats
General.sendHTMLMail(strEmail, "Administrative Access to Record", strEmailTemplate);
return intUserID;
}// end of createObituaryCoOwner()
//randomly create a password to be sent an save for the user
public static string genPassword()
{
System.Random ranNumber = new System.Random();//holds the object that will random gen
string strPassword = "";//holds the string that will have the password
char chRandom;//holds the random char
//goes around for getting 7 random chars
for(int intIndex = 0; intIndex < 7; intIndex++)
{
//randomly choose a random char
chRandom = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * ranNumber.NextDouble() + 65)));
//adds to the password
strPassword += chRandom;
}//end of for loop
return strPassword;
}//end of genPassword()
//resizes a image
public static SD.Image resizeImage(SD.Image imgBigImage, int ingMaxWidth, int ingMaxHeight)
{
int intNewWidth = 0;//holds the new width of the new image
int intNewHeight = 0;//holds the new height of the new image
int intCurrentWidth = imgBigImage.Width;//holds the current width of the image
int intCurrentHeight = imgBigImage.Height;//holds the current height of the image
//checks if the width is larger then the heigth if so then
//floors the width and set the height to be apporenit to the width
if ((intCurrentWidth / (double)ingMaxWidth) > (intCurrentHeight / (double)ingMaxHeight))
{
//adjuest the height to be apporent now and floors the width
intNewWidth = ingMaxWidth;
intNewHeight = Convert.ToInt32(intCurrentHeight * (ingMaxWidth / (double)intCurrentWidth));
//checks if the new height is not bigger then the max
if (intNewHeight > ingMaxHeight)
{
//adjuest the width to be apporent now and floors the height
intNewWidth = Convert.ToInt32(ingMaxWidth * (ingMaxHeight / (double)intNewHeight));
intNewHeight = ingMaxHeight;
}//end of if
}//end of if
//else floors the height and set the width to be apporenit to the height
else
{
//adjuest the width to be apporent now and floors the height
intNewWidth = Convert.ToInt32(intCurrentWidth * (ingMaxHeight / (double)intCurrentHeight));
intNewHeight = ingMaxHeight;
//checks if the new width is not bigger then the max
if (intNewWidth > ingMaxWidth)
{
//adjuest the height to be apporent now and floors the width
intNewWidth = ingMaxWidth;
intNewHeight = Convert.ToInt32(ingMaxHeight * (ingMaxWidth / (double)intNewWidth));
}//end of if
}//end of else
SD.Bitmap bitNewImage = new SD.Bitmap(intNewWidth, intNewHeight);//holds the new bitmap of the image
//web resolution;
bitNewImage.SetResolution(72, 72);
SD.Graphics grImage = SD.Graphics.FromImage(bitNewImage);//holds the graphics object
grImage.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
//creates a new holder of where the new image will be drawen to
grImage.FillRectangle(new SD.SolidBrush(SD.Color.White), 0, 0, bitNewImage.Width, bitNewImage.Height);
//Re-draw the image to the specified height and width
grImage.DrawImage(imgBigImage, 0, 0, bitNewImage.Width, bitNewImage.Height);
return bitNewImage;
}//end of resizeImage()
//search for City with the same provance if it is found then add to intNumberOf to display currently
public static int searchCityNumberOf(string strProvName, string strCityName, List<CitySearchItem> listCitySearchItem) {
try {
CitySearchItem csiResult = listCitySearchItem.Find(
delegate(CitySearchItem csi) {
return csi.SearchProvince == strProvName && csi.SearchCity == strCityName;
}//end of delegate
);//holds the results of the search in listCitySearchItem
//checks if thre is any items with the city with the same provance is found
if (csiResult != null)
//add to intNumberOf
csiResult.NumberOf++;
else
return 0;
return csiResult.NumberOf;
}//end of try
catch (Exception ex) {
throw ex;
}//end of catch
}//end of searchCityNumberOf()
//search for provance if it is found then add to intNumberOf to display currently
public static int searchProvNumberOf(string strProvName, List<CitySearchItem> listCitySearchItem) {
try {
CitySearchItem csiResult = listCitySearchItem.Find(
delegate(CitySearchItem csi)
{
return csi.SearchProvince == strProvName;
}//end of delegate
);//holds the results of the search in listCitySearchItem
//checks if thre is any items with the city with the same provance is found
if (csiResult != null)
//add to intNumberOf
csiResult.NumberOf++;
else
return 0;
return csiResult.NumberOf;
}//end of try
catch (Exception ex)
{
throw ex;
}//end of catch
}//end of searchProvNumberOf()
//sends out emails to the user
public static string sendHTMLMail(string strToAddress, string strSubject, string strBody, string strBCC = "", string strCC = "", string strFromAddress = "", string strFromName = "theObituaries")
{
try
{
RestClient client = new RestClient();//holds if the API from mailgun
RestRequest request = new RestRequest();//holds the request to the API
//sets the authenthiozion to using the mailgun API
client.BaseUrl = "https://api.mailgun.net/v2";
//checks if this is on live or on staging/dev
if (HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString() == "theobituaries.ca" || HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString() == "www.theobituaries.ca")
{
//sets the API Key
client.Authenticator = new HttpBasicAuthenticator("api","");
//sets the domain to sent the message to which in turn will send it out to strToAddress
request.AddParameter("domain", "theobituaries.ca", ParameterType.UrlSegment);
}//end of if
else {
// send the email throw mailgun
//sets the API Key
client.Authenticator = new HttpBasicAuthenticator("api","");
//sets the domain to sent the message to which in turn will send it out to strToAddress
request.AddParameter("domain", "", ParameterType.UrlSegment);
}//end of else
request.Resource = "{domain}/messages";
//sets the from and to address
request.AddParameter("from", strFromName + " <" + strFromAddress + ">");
request.AddParameter("to", strToAddress);
//checks if there is a cc to use if so then add it to mmSentMessage
if(!string.IsNullOrEmpty(strCC))
request.AddParameter("cc", strCC);
//checks if there is a bcc to use if so then add it to mmSentMessage
if(!string.IsNullOrEmpty(strBCC))
request.AddParameter("bcc", strBCC);
//sets the basic items that will be send to the user
request.AddParameter("subject", strSubject);
request.AddParameter("html", strBody);
request.Method = Method.POST;
//sends out to the user
client.Execute(request);
}//end of try
catch (System.Exception e)
{
// return the text of unknown error
return e.ToString();
}//end of catch
return "0";
}//end of sendHTMLMail()
//send email with attachment
public static string sendHTMLMailWithAttachment(string strToAddress, string strSubject, string strBody, string attachmentFilePath, string strFromAddress = "", string strFromName = "theObituaries")
{
try
{
RestClient client = new RestClient();//holds if the API from mailgun
RestRequest request = new RestRequest();//holds the request to the API
//sets the authenthiozion to using the mailgun API
client.BaseUrl = "https://api.mailgun.net/v2";
client.Authenticator = new HttpBasicAuthenticator("api", "");
//sets the domain to sent the message to which in turn will send it out to strToAddress
request.AddParameter("domain", "", ParameterType.UrlSegment);
request.Resource = "{domain}/messages";
//sets the from and to address
request.AddParameter("from", strFromName + " <" + strFromAddress + ">");
request.AddParameter("to", strToAddress);
//sets the basic items that will be send to the user
request.AddParameter("subject", strSubject);
request.AddParameter("html", strBody);
request.AddFile("attachment", attachmentFilePath);
request.Method = Method.POST;
//sends out to the user
client.Execute(request);
}//end of try
catch (System.Exception e)
{
// return the text of unknown error
return e.ToString();
}//end of catch
return "0";
}//end of sendHTMLMailWithAttachment()
//sets the session and cookies for user when they login
public static void setSession(DataTable dtUserDetails, bool usingCookies) {
//sets the session valuable to tell the that the user has been loged in
HttpContext.Current.Session["MemberLogin"] = dtUserDetails.Rows[0][""].ToString();
}//end of setSession()
public static string stripHtml(string strWithHTML) {
//checks if there is any text to strWithHTML to remove
if (string.IsNullOrEmpty(strWithHTML))
return strWithHTML;
else
//strips out the HTML
return System.Text.RegularExpressions.Regex.Replace(strWithHTML, "<[^>]*>", "");
}//end of stripHtml()
//uploads the Image to the server
public static string uploadImage(string strSavePath,HttpPostedFile myFile, int intMaxThumbnailWidth = 0, int intMaxThumbnailHeight = 0)
{
// Check file size (mustn't be 0)
int intFileLen = myFile.ContentLength;
string strImageFileExtension = System.IO.Path.GetExtension(myFile.FileName);//holds the file extension
if (intFileLen == 0)
return "ERROR! File Length is zero for " + myFile.FileName;
// Check file extension that it is the internet images .jpg/.gif/.png
if (strImageFileExtension.ToLower() != ".jpg" && strImageFileExtension.ToLower() != ".png" && strImageFileExtension.ToLower() != ".gif")
return "ERROR! The Image file must have an extension of either JPG, PNG or GIF: for " + myFile.FileName;
//checks if the file size is above 8MB
if(intFileLen > 8000000)
return "ERROR! The Image file most be below 8MB";
// Read file into a data stream
byte[] bytData = new Byte[intFileLen];
myFile.InputStream.Read(bytData,0,intFileLen);
// Make sure a duplicate file doesn't exist. If it does, keep on appending an
// incremental numeric until it is unique
string strImageFileName = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
//checks if the the file name is loarger then 200 char without the extension
if((strImageFileName.Replace(strImageFileExtension,"")).Length > 200)
//shorts the file name to fit into the database
strImageFileName = (strImageFileName.Replace(strImageFileExtension,"")).Substring(0,200) + strImageFileExtension;
while (System.IO.File.Exists(HttpContext.Current.Server.MapPath(strSavePath + strImageFileName)))
{
file_append++;
strImageFileName = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + strImageFileExtension.ToLower();
}//end of while loop
// Save the stream to disk
System.IO.FileStream newFile = new System.IO.FileStream(HttpContext.Current.Server.MapPath(strSavePath + strImageFileName.Replace("'","")), System.IO.FileMode.Create);
newFile.Write(bytData, 0, bytData.Length);
newFile.Close();
//checks if this image needs to be a thumbnail as there will be times that a Thumbnail is needed
if(intMaxThumbnailWidth > 0 && intMaxThumbnailHeight > 0)
{
//ues a memory stream of the image
using (MemoryStream ms = new MemoryStream(bytData, 0, bytData.Length))
{
//writes to memory stream using the bytes from the image
ms.Write(bytData, 0, bytData.Length);
//uses a image from the memory stream to recreate the image as a file
using(SD.Image sdimgCroppedImage = SD.Image.FromStream(ms, true))
{
//uses the image from the uploading to make different version of them
//to use in different areas of the site
using(SD.Image imgCurrent = SD.Image.FromFile(HttpContext.Current.Server.MapPath(strSavePath + strImageFileName.Replace("'",""))))
{
SD.Image imgThumb = resizeImage(imgCurrent, intMaxThumbnailWidth, intMaxThumbnailHeight);//holds the image as a thumbnail for later use
//saves the image to server again this time in a thumbnail of what was just upload
imgThumb.Save(HttpContext.Current.Server.MapPath(strSavePath + strImageFileName).Replace(".","_upload_thumbnail."), sdimgCroppedImage.RawFormat);
}//end of using
}//end of using
}//end of using
}//end of if
return strSavePath + strImageFileName.Replace("'","");
}//end of uploadImage()
}//end of class General |
using UnityEngine;
namespace QuestSystem
{
//public class LocationObjective : IQuestGoal
//{
// private string title;
// private string description;
// private string verb;
// private bool isComplete;
// private bool isSecondary; // If a branching path for the quest is required
// private int collectionAmount; //Required for completion
// private int currentAmount;
// private GameObject itemToCollect;
// public string Title
// {
// get
// {
// return title;
// }
// }
// public string Description
// {
// get
// {
// return description;
// }
// }
// public int CurrentAmount
// {
// get
// {
// return currentAmount;
// }
// }
// public int CollectionAmount
// {
// get
// {
// return collectionAmount;
// }
// }
// public GameObject ItemToCollect
// {
// get
// {
// return itemToCollect;
// }
// }
// public bool IsComplete
// {
// get
// {
// return isSecondary;
// }
// }
// public bool IsSecondary
// {
// get
// {
// return isSecondary;
// }
// }
// public void CheckProgress()
// {
// throw new System.NotImplementedException();
// }
// public void UpdateProgress()
// {
// if (currentAmount >= collectionAmount)
// {
// isComplete = true;
// }
// else
// {
// isComplete = false;
// }
// }
//}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class EnemyDB : MonoBehaviour
{
public List<BaseEnemyDBEntry> enemies = new List<BaseEnemyDBEntry>();
#region Singleton
public static EnemyDB instance; //call instance to get the single active EnemyDB for the game
private void Awake()
{
if (instance != null)
{
//Debug.LogWarning("More than one instance of EnemyDB found!");
return;
}
instance = this;
}
#endregion
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightingBook.Tests.Api.Product.Dto.CarSelection.Request
{
public class Car
{
public Supplier Supplier { get; set; }
public Vehicle Vehicle { get; set; }
public string RateCode { get; set; }
public string CurrencyCode { get; set; }
public PickUp PickUp { get; set; }
public DropOff DropOff { get; set; }
public string SearchIdentifier { get; set; }
public double Amount { get; set; }
public int TaxAmount { get; set; }
public object SpecialRequests { get; set; }
public object LostSavingsAmount { get; set; }
public object Policy { get; set; }
public static implicit operator List<object>(Car v)
{
throw new NotImplementedException();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Hacker : MonoBehaviour {
const string menuHint = "Type 'menu' to return.";
// Game config
string[] level1Passwords = { "books", "aisle", "shelf", "password", "font", "borrow" };
string[] level2Passwords = { "shotgun", "handcuffs", "badge", "uniform", "law", "order" };
string[] level3Passwords = { "space", "elon", "rocketship", "spaceman", "starman", "spidersfrommars" };
// Game state
string username = Environment.UserName;
int level;
string password;
enum Screen { MainMenu, Password, Win};
Screen currentScreen;
// Use this for initialization
void Start () {
ShowMainMenu(username);
}
void ShowMainMenu(string user) {
currentScreen = Screen.MainMenu;
Terminal.ClearScreen();
Terminal.WriteLine("Hello " + user + "\n" +
"Press 1 for Library\n" +
"Press 2 for Police Station\n" +
"Press 3 for NASA\n" +
"Enter the number of your selection:");
}
void OnUserInput(string input) {
if (input == "menu") {
ShowMainMenu(username);
}
else if (currentScreen == Screen.MainMenu) {
RunMainMenu(input);
}
else if (currentScreen == Screen.Password) {
CheckPassword(input);
}
}
void CheckPassword(string input) {
if (input == password) {
DisplayWinScreen();
}
else {
StartGame();
Terminal.WriteLine("Try Again");
}
}
void StartGame() {
currentScreen = Screen.Password;
Terminal.ClearScreen();
SetRandomPassword();
Terminal.WriteLine("Enter password, hint: " + password.Anagram());
Terminal.WriteLine(menuHint);
}
void SetRandomPassword() {
switch (level) {
case 1:
password = level1Passwords[UnityEngine.Random.Range(0, level1Passwords.Length)];
break;
case 2:
password = level2Passwords[UnityEngine.Random.Range(0, level2Passwords.Length)];
break;
case 3:
password = level3Passwords[UnityEngine.Random.Range(0, level3Passwords.Length)];
break;
default:
Debug.LogError("Invalid level number");
break;
}
}
void DisplayWinScreen() {
currentScreen = Screen.Win;
Terminal.ClearScreen();
ShowLevelReward();
Terminal.WriteLine(menuHint);
}
void ShowLevelReward() {
switch (level) {
case 1:
Terminal.WriteLine("Have a book...");
Terminal.WriteLine(@"
__ __
/\ \ /\ \
/ \ \ / \ \
/ /\ \ \ / /\ \ \
/ / /\ \ \/ / /\ \ \
/ / /__\_\/ / /__\_\ \
/ / /______\/ /________\
\/_____________________/
");
break;
case 2:
Terminal.WriteLine("Get out of jail ...");
Terminal.WriteLine(@"
ooo, .---.
o` o / |\________________
o` 'oooo() | ________ _ _)
`oo o` \ |/ | | | |
`ooo' `---' |_| |_|
");
break;
case 3:
Terminal.WriteLine("Tickets to Mars!");
Terminal.WriteLine(@"
_ __ __ _ ___ __ _
| '_ \ / _` / __|/ _` |
| | | | (_| \__ \ (_| |
|_| |_|\__,_|___/\__,_|
");
break;
default:
Debug.LogError("You should not be geting this error.");
break;
}
}
void RunMainMenu(string input) {
bool isValidLevelNumber = (input == "1" || input == "2" || input == "3");
if (isValidLevelNumber) {
level = int.Parse(input);
StartGame();
}
else {
Terminal.WriteLine("Invalid input");
}
}
// Update is called once per frame
void Update() {
}
}
|
using System.Data.Entity;
namespace LINQ101MVC.Models
{
public partial class ApplicationDbContext : DbContext
{
public static ApplicationDbContext Create() => new ApplicationDbContext();
public ApplicationDbContext() : base("name=DefaultConnection") { }
public virtual DbSet<Department> Departments { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Person> People { get; set; }
public virtual DbSet<CreditCard> CreditCards { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<SalesOrderDetail> SalesOrderDetails { get; set; }
public virtual DbSet<SalesOrderHeader> SalesOrderHeaders { get; set; }
public virtual DbSet<SalesPerson> SalesPersons { get; set; }
// Last moment added entities.
public virtual DbSet<ProductCategory> ProductCategories { get; set; }
public virtual DbSet<ProductSubcategory> ProductSubcategories { get; set; }
public virtual DbSet<Product> Products { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.Property(e => e.MaritalStatus)
.IsFixedLength();
modelBuilder.Entity<Employee>()
.Property(e => e.Gender)
.IsFixedLength();
modelBuilder.Entity<Employee>()
.HasOptional(e => e.SalesPerson)
.WithRequired(e => e.Employee);
modelBuilder.Entity<Person>()
.Property(e => e.PersonType)
.IsFixedLength();
modelBuilder.Entity<Person>()
.HasOptional(e => e.Employee)
.WithRequired(e => e.Person);
modelBuilder.Entity<Person>()
.HasMany(e => e.Customers)
.WithOptional(e => e.Person)
.HasForeignKey(e => e.PersonID);
modelBuilder.Entity<Customer>()
.Property(e => e.AccountNumber)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.HasMany(e => e.SalesOrderHeaders)
.WithRequired(e => e.Customer)
.WillCascadeOnDelete(false);
modelBuilder.Entity<SalesOrderDetail>()
.Property(e => e.UnitPrice)
.HasPrecision(19, 4);
modelBuilder.Entity<SalesOrderDetail>()
.Property(e => e.UnitPriceDiscount)
.HasPrecision(19, 4);
modelBuilder.Entity<SalesOrderDetail>()
.Property(e => e.LineTotal)
.HasPrecision(38, 6);
modelBuilder.Entity<SalesOrderHeader>()
.Property(e => e.CreditCardApprovalCode)
.IsUnicode(false);
modelBuilder.Entity<SalesOrderHeader>()
.Property(e => e.SubTotal)
.HasPrecision(19, 4);
modelBuilder.Entity<SalesOrderHeader>()
.Property(e => e.TaxAmt)
.HasPrecision(19, 4);
modelBuilder.Entity<SalesOrderHeader>()
.Property(e => e.Freight)
.HasPrecision(19, 4);
modelBuilder.Entity<SalesOrderHeader>()
.Property(e => e.TotalDue)
.HasPrecision(19, 4);
modelBuilder.Entity<SalesPerson>()
.Property(e => e.SalesQuota)
.HasPrecision(19, 4);
modelBuilder.Entity<SalesPerson>()
.Property(e => e.Bonus)
.HasPrecision(19, 4);
modelBuilder.Entity<SalesPerson>()
.Property(e => e.CommissionPct)
.HasPrecision(10, 4);
modelBuilder.Entity<SalesPerson>()
.Property(e => e.SalesYTD)
.HasPrecision(19, 4);
modelBuilder.Entity<SalesPerson>()
.Property(e => e.SalesLastYear)
.HasPrecision(19, 4);
modelBuilder.Entity<SalesPerson>()
.HasMany(e => e.SalesOrderHeaders)
.WithOptional(e => e.SalesPerson)
.HasForeignKey(e => e.SalesPersonID);
modelBuilder.Entity<Product>()
.Property(e => e.StandardCost)
.HasPrecision(19, 4);
// Last added section.
// Not to map a model property to a datacolumn in the database.
modelBuilder.Entity<Product>().Ignore(e => e.IsDeletable);
modelBuilder.Entity<Product>()
.Property(e => e.ListPrice)
.HasPrecision(19, 4);
modelBuilder.Entity<Product>()
.Property(e => e.SizeUnitMeasureCode)
.IsFixedLength();
modelBuilder.Entity<Product>()
.Property(e => e.WeightUnitMeasureCode)
.IsFixedLength();
modelBuilder.Entity<Product>()
.Property(e => e.Weight)
.HasPrecision(8, 2);
modelBuilder.Entity<Product>()
.Property(e => e.ProductLine)
.IsFixedLength();
modelBuilder.Entity<Product>()
.Property(e => e.Class)
.IsFixedLength();
modelBuilder.Entity<Product>()
.Property(e => e.Style)
.IsFixedLength();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PlatformStatusTracker.Core.Enum;
using System.ComponentModel;
namespace PlatformStatusTracker.Core.Data
{
public class PlatformStatuses
{
public static IePlatformStatus[] DeserializeForIeStatus(string jsonValue)
{
return JsonConvert.DeserializeObject<IePlatformStatus[]>(jsonValue);
}
public static ChromiumPlatformStatus[] DeserializeForChromiumStatus(string jsonValue)
{
return JsonConvert.DeserializeObject<ChromiumPlatformStatus[]>(jsonValue);
}
public static WebKitPlatformStatus[] DeserializeForWebKitStatus(string jsonValue)
{
var statuses = JsonConvert.DeserializeObject<WebKitPlatformStatuses>(jsonValue);
return statuses.Features/*.Concat(statuses.Specification)*/.Where(x => x.Status != null).ToArray();
}
public static MozillaPlatformStatus[] DeserializeForMozillaStatus(string jsonValue)
{
var statuses = JsonConvert.DeserializeObject<MozillaPlatformStatuses>(jsonValue);
if (statuses.Features != null)
{
return statuses.Features;
}
return JsonConvert.DeserializeObject<Dictionary<string, MozillaPlatformStatus>>(jsonValue).Values.ToArray();
}
public DateTime Date { get; private set; }
public IPlatformStatus[] Statuses { get; private set; }
public PlatformStatuses(DateTime date, IPlatformStatus[] statuses)
{
Date = date;
Statuses = statuses;
}
public static IPlatformStatus[] Deserialize(StatusDataType dataType, string jsonValue)
{
switch (dataType)
{
case StatusDataType.Chromium: return DeserializeForChromiumStatus(jsonValue);
case StatusDataType.InternetExplorer: return DeserializeForIeStatus(jsonValue);
case StatusDataType.WebKitWebCore: return DeserializeForWebKitStatus(jsonValue);
case StatusDataType.WebKitJavaScriptCore: return DeserializeForWebKitStatus(jsonValue);
case StatusDataType.Mozilla: return DeserializeForMozillaStatus(jsonValue);
default: throw new NotSupportedException();
}
}
}
public interface IPlatformStatus
{
string Name { get; }
long? Id { get; }
bool CompareStatus(IPlatformStatus status);
}
public class PlatformStatus : IPlatformStatus
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("category")]
public string Category { get; set; }
[JsonProperty("summary")]
public string Summary { get; set; }
[JsonProperty("id")]
public long? Id { get; set; }
[JsonProperty("impl_status_chrome")]
public string ImplStatusChrome { get; set; }
[JsonProperty("ff_views")]
public ViewsStatus FfViews { get; set; }
[JsonProperty("safari_views")]
public ViewsStatus SafariViews { get; set; }
public virtual bool CompareStatus(IPlatformStatus status)
{
return false;
}
}
[DebuggerDisplay("IePlatformStatus: {Name}")]
public class IePlatformStatus : PlatformStatus
{
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("summary")]
public string StandardStatus { get; set; }
[JsonProperty("msdn")]
public string Msdn { get; set; }
[JsonProperty("wpd")]
public string Wpd { get; set; }
[JsonProperty("demo")]
public string Demo { get; set; }
[JsonProperty("opera_views")]
public ViewsStatus OperaViews { get; set; }
[JsonProperty("ieStatus")]
public IeStatus IeStatus { get; set; }
public override bool CompareStatus(IPlatformStatus status)
{
var ieStatus = status as IePlatformStatus;
return this.IeStatus.IePrefixed == ieStatus.IeStatus.IePrefixed &&
this.IeStatus.IeUnprefixed == ieStatus.IeStatus.IeUnprefixed &&
this.IeStatus.Text == ieStatus.IeStatus.Text &&
this.IeStatus.Flag == ieStatus.IeStatus.Flag &&
this.IeStatus.Priority == ieStatus.IeStatus.Priority;
}
}
[DebuggerDisplay("ChromiumPlatformStatus: {Name}")]
public class ChromiumPlatformStatus : PlatformStatus
{
[JsonProperty("bug_url")]
public string BugUrl { get; set; }
[JsonProperty("ff_views_link")]
public string FfViewsLink { get; set; }
[JsonProperty("ie_views")]
public ViewsStatus IeViews { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete]
[JsonProperty("prefixed")]
public bool _Prefixed { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete]
[JsonProperty("shipped_android_milestone")]
public int? ShippedAndroidMilestone { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete]
[JsonProperty("shipped_ios_milestone")]
public int? ShippedIosMilestone { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete]
[JsonProperty("shipped_milestone")]
public int? ShippedMilestone { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete]
[JsonProperty("shipped_opera_android_milestone")]
public int? ShippedOperaAndroidMilestone { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete]
[JsonProperty("shipped_opera_milestone")]
public int? ShippedOperaMilestone { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete]
[JsonProperty("shipped_webview_milestone")]
public int? ShippedWebViewMilestone { get; set; }
[JsonProperty("spec_link")]
public string SpecLink { get; set; }
[JsonProperty("standardization")]
public ViewsStatus Standardization { get; set; }
[JsonProperty("web_dev_views")]
public ViewsStatus WebDevViews { get; set; }
// 2017-06-14
[JsonProperty("browsers")]
public BrowserStatus Browsers { get; set; }
public override bool CompareStatus(IPlatformStatus status)
{
var chStatus = status as ChromiumPlatformStatus;
if (chStatus == null) return false;
return this.Prefixed == chStatus.Prefixed &&
this.Flag == chStatus.Flag &&
this.Status == chStatus.Status &&
this.Android == chStatus.Android &&
this.Ios == chStatus.Ios &&
this.Desktop == chStatus.Desktop
;
}
#pragma warning disable CS0612 // Type or member is obsolete
public bool Flag => Browsers?.Chrome?.Flag ?? false;
public bool Prefixed => Browsers?.Chrome?.Prefixed ?? _Prefixed;
public string Status => Browsers?.Chrome?.Status?.Text ?? ImplStatusChrome;
public int? Android => Browsers?.Chrome?.Android ?? ShippedAndroidMilestone;
public int? Ios => Browsers?.Chrome?.Ios ?? ShippedIosMilestone;
public int? Desktop => Browsers?.Chrome?.Desktop ?? ShippedMilestone;
#pragma warning restore CS0612 // Type or member is obsolete
public class BrowserStatus
{
[JsonProperty("chrome")]
public ChromeStatus Chrome { get; set; }
}
public class ChromeStatus
{
[JsonProperty("status")]
public ChromeStatusStatus Status { get; set; }
[JsonProperty("prefixed")]
public bool? Prefixed { get; set; }
[JsonProperty("flag")]
public bool? Flag { get; set; }
[JsonProperty("bug")]
public string Bug { get; set; }
[JsonProperty("android")]
public int? Android { get; set; }
[JsonProperty("desktop")]
public int? Desktop { get; set; }
[JsonProperty("ios")]
public int? Ios { get; set; }
}
public class ChromeStatusStatus
{
[JsonProperty("text")]
public string Text { get; set; }
}
}
public class WebKitPlatformStatuses
{
[JsonProperty("specification")]
public WebKitPlatformStatus[] Specification { get; set; }
[JsonProperty("features")]
public WebKitPlatformStatus[] Features { get; set; }
}
[DebuggerDisplay("WebKitPlatformStatus: {Name}")]
public class WebKitPlatformStatus : PlatformStatus
{
[JsonProperty("status")]
public WebKitStatus Status { get; set; }
[JsonProperty("webkit-url")]
public string WebKitUrl { get; set; }
public override bool CompareStatus(IPlatformStatus status)
{
var webkitStatus = status as WebKitPlatformStatus;
if (webkitStatus == null) return false;
return this.Status.Status == webkitStatus.Status.Status &&
this.Status.EnabledByDefault == webkitStatus.Status.EnabledByDefault
;
}
}
public class MozillaPlatformStatuses
{
[JsonProperty("features")]
public MozillaPlatformStatus[] Features { get; set; }
}
[DebuggerDisplay("MozillaPlatformStatus: {Name}")]
public class MozillaPlatformStatus : IPlatformStatus
{
public long? Id { get; set; }
[JsonProperty("title")]
public string Name { get; set; }
[JsonProperty("summary")]
public string Summary { get; set; }
[JsonProperty("bugzilla")]
public string Bugzilla { get; set; }
[JsonProperty("firefox_status")]
public string Status { get; set; }
[JsonProperty("firefox_version")]
public string Version { get; set; }
[JsonProperty("firefox_channel")]
public string Channel { get; set; }
[JsonProperty("slug")]
public string Slug { get; set; }
public virtual bool CompareStatus(IPlatformStatus status)
{
var status2 = status as MozillaPlatformStatus;
if (status2 == null) return false;
return this.Status == status2.Status &&
this.Version == status2.Version &&
this.Channel == status2.Channel
;
}
}
public class IeStatus
{
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("iePrefixed")]
public string IePrefixed { get; set; }
[JsonProperty("ieUnprefixed")]
public string IeUnprefixed { get; set; }
[JsonProperty("flag")]
public bool? Flag { get; set; }
[JsonProperty("priority")]
public string Priority { get; set; }
}
public class ViewsStatus
{
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("value")]
public int Value { get; set; }
}
public class WebKitStatus
{
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("enabled-by-default")]
public string EnabledByDefault { get; set; }
}
}
|
using System;
using Gtk;
public partial class MainWindow: Gtk.Window
{
public MainWindow (): base (Gtk.WindowType.Toplevel)
{
Build ();
}
protected void OnDeleteEvent (object sender, DeleteEventArgs a)
{
Application.Quit ();
a.RetVal = true;
}
protected void OnBtnfactClicked (object sender, EventArgs e)
{
double p1= double.Parse (this.txt1.Text);
double p2= double.Parse (this.txt2.Text);
double p3= double.Parse (this.txt3.Text);
double Subt= p1+p2+p3;
double Iva= Subt*.16;
double Total= Subt+Iva;
this.txtsubt.Text= Subt.ToString ();
this.txtiva.Text= Iva.ToString ();
this.txttotal.Text= Total.ToString ();
}
protected void OnBtnlimpClicked (object sender, EventArgs e)
{
this.txt1.Text="";
this.txt2.Text="";
this.txt3.Text="";
this.txtiva.Text="";
this.txtsubt.Text="";
this.txttotal.Text="";
}
}
|
namespace Fedex
{
// External Proprietary Service Class
// Non Editable for consuming client
public class FedexService
{
public void CreateShipment(string address, string shipmentName)
{
System.Console.WriteLine($"Your shipment for {shipmentName} created in Fedex and will be delivered tomorrow");
}
public void TrackShipment(string shipmentId)
{
System.Console.WriteLine($"Shipment {shipmentId} tracked in Fedex");
}
}
} |
using DLMotion;
//*************************************************************************
//@header MachineState
//@abstract Do something when create state.
//@discussion Depend on PlayerState.
//@author Felix Zhang
//@copyright Copyright (c) 2017 FFTAI Co.,Ltd.All rights reserved.
//@version v1.0.0
//**************************************************************************
namespace FZ.HiddenObjectGame
{
public abstract class MachineState : PlayerState
{
public override void Setup(params object[] args)
{
// Do nothing here.
}
public override void OnStateChanged(PlayerState nextState)
{
DynaLinkHS.CmdServoOff();
}
}
}
|
using System;
using Compent.CommandBus;
namespace Uintra.Features.Likes.CommandBus.Commands
{
public abstract class LikeCommand : ICommand
{
public Guid Author { get; }
public Guid EntityId { get; }
public Enum EntityType { get; }
protected LikeCommand(Guid entityId, Enum entityType, Guid author)
{
Author = author;
EntityId = entityId;
EntityType = entityType;
}
}
} |
using System;
using System.Linq;
namespace Triple_sum
{
class Program
{
static void Main(string[] args)
{
long[] arr = Console.ReadLine()
.Split(' ')
.Select(long.Parse)
.ToArray();
bool flag = true;
for (long a = 0; a < arr.Length; a++)
{
for (long b = a + 1; b < arr.Length; b++)
{
for (long c = 0; c < arr.Length; c++)
{
if (arr[a] + arr[b] == arr[c])
{
flag = false;
Console.WriteLine($"{arr[a]} + {arr[b]} == {arr[c]}");
break;
}
}
}
}
if (flag)
{
Console.WriteLine($"No");
}
}
}
}
|
using DigitalFormsSteamLeak.Business;
using DigitalFormsSteamLeak.Entity.IModels;
using DigitalFormsSteamLeak.Entity.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DigitalFormsSteamLeak.Business.Test
{
[TestClass]
public class MOCSessionBusinessTest
{
protected MOCSessionFactory ltr { get; set; }
public MOCSessionBusinessTest()
{
ltr = new MOCSessionFactory();
}
[TestMethod]
public void AddMOCSession()
{
try
{
IMOCSession mocSesseion = new MOCSession()
{
MOCId = Guid.NewGuid(),
LeakDetailsId = Guid.Parse("C124835B-4B82-4CAB-A173-44601AC73012"),
MOCNumber = 123,
MOCDateRequested = DateTime.Now,
MOCStatus = "start",
MOCComments = "Dustin make MOC comments",
};
ltr.Create((MOCSession)mocSesseion);
}
catch (Exception ex)
{
throw ex;
}
}
[TestMethod]
public void UpdateMOCSession()
{
try
{
IMOCSession mocSesseion = new MOCSession()
{
MOCId = Guid.Parse("23BB161F-6402-4096-A2C7-75D82F6F4C53"),
LeakDetailsId = Guid.Parse("C124835B-4B82-4CAB-A173-44601AC73012"),
MOCNumber = 1233,
MOCDateRequested = DateTime.Now,
MOCStatus = "End",
MOCComments = "Dustin MOC comments",
};
ltr.Update((MOCSession)mocSesseion);
}
catch (Exception ex)
{
throw ex;
}
}
[TestMethod]
public void GetMOCSession()
{
try
{
var list = ltr.GetAll().ToList();
Assert.IsNotNull(list);
}
catch (Exception ex)
{
throw ex;
}
}
}
} |
namespace CourseVoiliers.Classes
{
public class Voilier
{
}
} |
using System;
using System.IO;
namespace number_28131
{
class Program
{
/* Задача: На вход программы поступает последовательность из n целых положительных чисел.
Рассматриваются все пары элементов последовательности a[i] и a[j], такие что i < j и a[i] > a[j]
(первый элемент пары больше второго; i и j — порядковые номера чисел в последовательности входных данных).
Среди пар, удовлетворяющих этому условию, необходимо найти и напечатать пару с максимальной суммой элементов,
которая делится на m = 120. Если среди найденных пар максимальную сумму имеют несколько,
то можно напечатать любую из них. */
public static void log(string message)//метод для логгирования
{
try
{
File.AppendAllText("E:\\log.txt", message);//класс и метод для записи в файл
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found!");
}
}
static void Main(string[] args)
{
log(DateTime.Now + "\n");
Console.Write("Введите кол-во чисел: ");
int n = Convert.ToInt32(Console.ReadLine());//переменная для кол-ва чисел
log("Ввод кол-ва чисел в массиве: " + n + '\n');
int m = 120;//переменная - делитель элементов массива
int left = 0;//левое число пары
int right = 0;//правое число пары
log("Объявление переменных и задание им значений: " + m + " " + left + " " + right + '\n');
if (n % 2 == 0)//проверка на четность введенного кол-ва символов
{
log("Обьявление переменной rand" + '\n');
Random rand = new Random();
int[] array = new int[n];//обЪявление массива
log("Объявление массива" + '\n');
for (int i = 0; i < n; i++)
{
array[i] = rand.Next(0, 10000);//заполнение массива случайными числами
Console.WriteLine(array[i]);
log("Элемент " + i + ": " + array[i] + '\n');
}
log("Массив заполнен случайными числами" + '\n');
for (int i = 0; i < n; i++)
{
int p = array[i] % m;//переменая остаток от деления элемента массива на 120
if (p == 0) { p = m; log("Переменной p присваивается значение " + p + '\n'); }
try
{
if (array[m - p] > array[i] & array[m - p] + array[i] > left + right)//поиск элемента с самой большой суммой цифр
{
left = array[m - p];
log("Переменной left присваивается значение " + left + '\n');
right = array[i];
log("Переменной right присваивается значение " + right + '\n');
}
}
catch
{
//так как мы просто отлавливаем исключения для того, чтобы программа дальше работала без вылетов, то здесь ничего нет
}
try
{
if (p < m)
{
if (array[i] > array[p]) { array[p] = array[i]; log("Элемент массива " + p + " приравниватеся к элементу массива " + i + '\n'); }
else if (array[i] > array[0]) { array[0] = array[i]; log("Элемент массива " + 0 + " приравнивается к элементу массива " + i + '\n'); }
}
}
catch
{
//так как мы просто отлавливаем исключения для того, чтобы программа дальше работала без вылетов, то здесь ничего нет
}
}
Console.WriteLine("Пара чисел с максимальной суммой элементов, которая делится на 120: " + left + " " + right);
log("Пара чисел: " + left + " и " + right + '\n');
}
else { Console.WriteLine("Введено нечетное число"); log("Введено нечетное число, значит не все числа будут иметь пару, что требуется по условию задачи"); }
Console.ReadKey();
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
namespace InheritCars.Models
{
public class Car
{
//[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string Model { get; set; }
public decimal Price { get; set; }
}
} |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace MainWebApplication.Migrations
{
public partial class fixes : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_BleCharacteristic_BleService_BleServiceID",
table: "BleCharacteristic");
migrationBuilder.DropTable(
name: "StoredValue<bool>");
migrationBuilder.DropTable(
name: "StoredValue<float>");
migrationBuilder.AlterColumn<long>(
name: "BleServiceID",
table: "BleCharacteristic",
nullable: false,
oldClrType: typeof(long),
oldType: "bigint",
oldNullable: true);
migrationBuilder.CreateTable(
name: "AnalogValue",
columns: table => new
{
Timestamp = table.Column<DateTime>(nullable: false),
BleCharacteristicID = table.Column<long>(nullable: false),
Value = table.Column<float>(nullable: false),
AnalogBleCharacteristicBleCharacteristicID = table.Column<long>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AnalogValue", x => x.Timestamp);
table.ForeignKey(
name: "FK_AnalogValue_BleCharacteristic_AnalogBleCharacteristicBleCharacteristicID",
column: x => x.AnalogBleCharacteristicBleCharacteristicID,
principalTable: "BleCharacteristic",
principalColumn: "BleCharacteristicID",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_AnalogValue_BleCharacteristic_BleCharacteristicID",
column: x => x.BleCharacteristicID,
principalTable: "BleCharacteristic",
principalColumn: "BleCharacteristicID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "DigitalValue",
columns: table => new
{
Timestamp = table.Column<DateTime>(nullable: false),
BleCharacteristicID = table.Column<long>(nullable: false),
Value = table.Column<bool>(nullable: false),
DigitalBleCharacteristicBleCharacteristicID = table.Column<long>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_DigitalValue", x => x.Timestamp);
table.ForeignKey(
name: "FK_DigitalValue_BleCharacteristic_BleCharacteristicID",
column: x => x.BleCharacteristicID,
principalTable: "BleCharacteristic",
principalColumn: "BleCharacteristicID",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_DigitalValue_BleCharacteristic_DigitalBleCharacteristicBleCharacteristicID",
column: x => x.DigitalBleCharacteristicBleCharacteristicID,
principalTable: "BleCharacteristic",
principalColumn: "BleCharacteristicID",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_AnalogValue_AnalogBleCharacteristicBleCharacteristicID",
table: "AnalogValue",
column: "AnalogBleCharacteristicBleCharacteristicID");
migrationBuilder.CreateIndex(
name: "IX_AnalogValue_BleCharacteristicID",
table: "AnalogValue",
column: "BleCharacteristicID");
migrationBuilder.CreateIndex(
name: "IX_DigitalValue_BleCharacteristicID",
table: "DigitalValue",
column: "BleCharacteristicID");
migrationBuilder.CreateIndex(
name: "IX_DigitalValue_DigitalBleCharacteristicBleCharacteristicID",
table: "DigitalValue",
column: "DigitalBleCharacteristicBleCharacteristicID");
migrationBuilder.AddForeignKey(
name: "FK_BleCharacteristic_BleService_BleServiceID",
table: "BleCharacteristic",
column: "BleServiceID",
principalTable: "BleService",
principalColumn: "BleServiceID",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_BleCharacteristic_BleService_BleServiceID",
table: "BleCharacteristic");
migrationBuilder.DropTable(
name: "AnalogValue");
migrationBuilder.DropTable(
name: "DigitalValue");
migrationBuilder.AlterColumn<long>(
name: "BleServiceID",
table: "BleCharacteristic",
type: "bigint",
nullable: true,
oldClrType: typeof(long));
migrationBuilder.CreateTable(
name: "StoredValue<bool>",
columns: table => new
{
Timestamp = table.Column<DateTime>(type: "datetime2", nullable: false),
BleCharacteristicID = table.Column<long>(type: "bigint", nullable: true),
DigitalBleCharacteristicBleCharacteristicID = table.Column<long>(type: "bigint", nullable: true),
Value = table.Column<bool>(type: "bit", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_StoredValue<bool>", x => x.Timestamp);
table.ForeignKey(
name: "FK_StoredValue<bool>_BleCharacteristic_BleCharacteristicID",
column: x => x.BleCharacteristicID,
principalTable: "BleCharacteristic",
principalColumn: "BleCharacteristicID",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_StoredValue<bool>_BleCharacteristic_DigitalBleCharacteristicBleCharacteristicID",
column: x => x.DigitalBleCharacteristicBleCharacteristicID,
principalTable: "BleCharacteristic",
principalColumn: "BleCharacteristicID",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "StoredValue<float>",
columns: table => new
{
Timestamp = table.Column<DateTime>(type: "datetime2", nullable: false),
AnalogBleCharacteristicBleCharacteristicID = table.Column<long>(type: "bigint", nullable: true),
BleCharacteristicID = table.Column<long>(type: "bigint", nullable: true),
Value = table.Column<float>(type: "real", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_StoredValue<float>", x => x.Timestamp);
table.ForeignKey(
name: "FK_StoredValue<float>_BleCharacteristic_AnalogBleCharacteristicBleCharacteristicID",
column: x => x.AnalogBleCharacteristicBleCharacteristicID,
principalTable: "BleCharacteristic",
principalColumn: "BleCharacteristicID",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_StoredValue<float>_BleCharacteristic_BleCharacteristicID",
column: x => x.BleCharacteristicID,
principalTable: "BleCharacteristic",
principalColumn: "BleCharacteristicID",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_StoredValue<bool>_BleCharacteristicID",
table: "StoredValue<bool>",
column: "BleCharacteristicID");
migrationBuilder.CreateIndex(
name: "IX_StoredValue<bool>_DigitalBleCharacteristicBleCharacteristicID",
table: "StoredValue<bool>",
column: "DigitalBleCharacteristicBleCharacteristicID");
migrationBuilder.CreateIndex(
name: "IX_StoredValue<float>_AnalogBleCharacteristicBleCharacteristicID",
table: "StoredValue<float>",
column: "AnalogBleCharacteristicBleCharacteristicID");
migrationBuilder.CreateIndex(
name: "IX_StoredValue<float>_BleCharacteristicID",
table: "StoredValue<float>",
column: "BleCharacteristicID");
migrationBuilder.AddForeignKey(
name: "FK_BleCharacteristic_BleService_BleServiceID",
table: "BleCharacteristic",
column: "BleServiceID",
principalTable: "BleService",
principalColumn: "BleServiceID",
onDelete: ReferentialAction.Restrict);
}
}
}
|
using ApiTemplate.Core.Entities.Users;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace ApiTemplate.Data.Configurations.Users
{
public class AppRoleConfiguration :IEntityTypeConfiguration<AppRole>
{
public void Configure(EntityTypeBuilder<AppRole> builder)
{
}
}
} |
using MVVMExample.Models;
using MVVMExample.ViewModels;
namespace MVVMExample.Views
{
public partial class Area2View
{
#region Constructors
public Area2View(BusinessLogicService businessLogicService)
{
InitializeComponent();
CalculatedValue = businessLogicService.CalculateValue();
}
#endregion
#region Properties
public int CalculatedValue { get; }
public Area2ViewModel ViewModel
{
get { return DataContext as Area2ViewModel; }
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OfficeOpenXml;
using System.IO;
using Stolons.Models;
using System.Threading;
using Microsoft.Data.Entity;
using System.Globalization;
using OfficeOpenXml.Style;
using Stolons.Helpers;
using Stolons.Services;
using System.Text;
namespace Stolons.Tools
{
public static class BillGenerator
{
public class BillEntryConsumer
{
public BillEntry BillEntry { get; set; }
public Consumer Consumer { get; set; }
public BillEntryConsumer(BillEntry billEntry, Consumer consumer)
{
BillEntry = billEntry;
Consumer = consumer;
}
}
public static void ManageBills(ApplicationDbContext dbContext)
{
ApplicationConfig.Modes lastMode = Configurations.Mode;
do
{
ApplicationConfig.Modes currentMode = Configurations.Mode;
if (lastMode == ApplicationConfig.Modes.Order && currentMode == ApplicationConfig.Modes.DeliveryAndStockUpdate)
{
//We moved form Order to Preparation, create and send bills
List<IBill> consumerBills = new List<IBill>();
List<IBill> producerBills = new List<IBill>();
Dictionary<Producer, List<BillEntryConsumer>> brutProducerBills = new Dictionary<Producer, List<BillEntryConsumer>>();
//Consumer (create bills)
List<ValidatedWeekBasket> consumerWeekBaskets = dbContext.ValidatedWeekBaskets.Include(x => x.Products).Include(x => x.Consumer).ToList();
GenerateBill(consumerWeekBaskets,dbContext);
foreach (var weekBasket in consumerWeekBaskets)
{
//Generate bill for consumer
ConsumerBill consumerBill = GenerateBill(weekBasket, dbContext);
consumerBills.Add(consumerBill);
dbContext.Add(consumerBill);
//Add to producer bill entry
foreach (var tmpBillEntry in weekBasket.Products)
{
var billEntry = dbContext.BillEntrys.Include(x => x.Product).ThenInclude(x => x.Producer).First(x=>x.Id == tmpBillEntry.Id);
Producer producer = billEntry.Product.Producer;
if (!brutProducerBills.ContainsKey(producer))
{
brutProducerBills.Add(producer, new List<BillEntryConsumer>());
}
brutProducerBills[producer].Add(new BillEntryConsumer(billEntry,weekBasket.Consumer));
}
}
//Producer (creates bills)
foreach (var producerBill in brutProducerBills)
{
//Generate bill for producer
ProducerBill bill = GenerateBill(producerBill.Key, producerBill.Value, dbContext);
producerBills.Add(bill);
dbContext.Add(bill);
//Send mail to producer
AuthMessageSender.SendEmail(bill.Producer.Email,
bill.Producer.CompanyName,
"Votre commande de la semaine (Facture "+ bill.BillNumber +")",
"<h3>En pièce jointe votre commande de la semaine (Facture " + bill.BillNumber + ")</h3>",
File.ReadAllBytes(bill.GetFilePath()),
"Facture "+ bill.BillNumber + ".xlsx");
}
// => Producer, send mails
foreach (var producer in dbContext.Producers.Where(x=> !brutProducerBills.Keys.Contains(x)))
{
//Un mail à tout les producteurs n'ayant pas de commande
AuthMessageSender.SendEmail(producer.Email, producer.CompanyName, "Aucune commande cette semaine", "<h3>Vous n'avez pas de commande cette semaine</h3>");
}
//Bills (save bills and send mails to user)
foreach(var bill in consumerBills)
{
dbContext.Add(bill);
//Send mail to user with bill
string message = "<h3>"+Configurations.ApplicationConfig.OrderDeliveryMessage+"</h3>";
message += "<br/>";
message += "<h4>En pièce jointe votre commande de la semaine (Facture " + bill.BillNumber + ")</h4>";
AuthMessageSender.SendEmail(bill.User.Email,
bill.User.Name,
"Votre commande de la semaine (Facture " + bill.BillNumber + ")",
message,
File.ReadAllBytes(bill.GetFilePath()),
"Facture " + bill.BillNumber + ".xlsx");
}
//Remove week basket
dbContext.TempsWeekBaskets.Clear();
dbContext.ValidatedWeekBaskets.Clear();
dbContext.BillEntrys.Clear();
//Move product to, to validate
dbContext.Products.ToList().ForEach(x => x.State = Product.ProductState.Stock);
#if (DEBUG)
//For test, remove existing consumer bill and producer bill => That will never exit in normal mode cause they can only have one bill by week per user
dbContext.RemoveRange(dbContext.ConsumerBills.Where(x=> consumerBills.Any(y=>y.BillNumber == x.BillNumber)));
dbContext.RemoveRange(dbContext.ProducerBills.Where(x => producerBills.Any(y => y.BillNumber == x.BillNumber)));
#endif
//
dbContext.SaveChanges();
//Set product remaining stock to week stock value
dbContext.Products.ToList().ForEach(x => x.RemainingStock = x.WeekStock);
dbContext.SaveChanges();
}
if(lastMode == ApplicationConfig.Modes.DeliveryAndStockUpdate && currentMode == ApplicationConfig.Modes.Order)
{
foreach( var product in dbContext.Products.Where(x => x.State == Product.ProductState.Stock))
{
product.State = Product.ProductState.Disabled;
}
dbContext.SaveChanges();
}
lastMode = currentMode;
Thread.Sleep(5000);
} while (true);
}
private static string GetFilePath(this IBill bill)
{
return Path.Combine(Configurations.Environment.WebRootPath,
bill.User is Producer ? Configurations.ProducersBillsStockagePath : Configurations.ConsumersBillsStockagePath,
bill.User.Id.ToString(),
bill.BillNumber + ".xlsx");
}
private static void GenerateBill(List<ValidatedWeekBasket> consumerWeekBaskets, ApplicationDbContext dbContext)
{
//Generate exel file with bill number for user
#region File creation
string billNumber = DateTime.Now.Year + "_" + DateTime.Now.GetIso8601WeekOfYear();
string consumerBillsPath = Path.Combine(Configurations.Environment.WebRootPath, Configurations.StolonsBillsStockagePath);
string newBillPath = Path.Combine(consumerBillsPath, billNumber + ".xlsx");
FileInfo newFile = new FileInfo(newBillPath);
if (newFile.Exists)
{
//Normaly impossible
newFile.Delete(); // ensures we create a new workbook
newFile = new FileInfo(newBillPath);
}
else
{
Directory.CreateDirectory(consumerBillsPath);
}
#endregion File creation
//
using (ExcelPackage package = new ExcelPackage(newFile))
{
if(!consumerWeekBaskets.Any())
{
//Rien de commander cette semaine :'(
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Rien :'(");
worksheet.Cells[1, 1].Value = "Rien cette semaine !";
}
else
{
foreach (ValidatedWeekBasket weekBasket in consumerWeekBaskets.OrderBy(x => x.Consumer.Id))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(weekBasket.Consumer.Id.ToString() + " (" + weekBasket.Consumer.Name + ")");
int row = 1;
//Add global informations
worksheet.Cells[row, 1, 8, 3].Merge = true;
worksheet.Cells[row, 1, 8, 3].Value = weekBasket.Consumer.Id;
worksheet.Cells[row, 1, 8, 3].Style.Font.Size = 100;
worksheet.Cells[row, 1, 8, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
worksheet.Cells[row, 1, 8, 3].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
worksheet.Cells[row, 4].Value = "Facture";
worksheet.Cells[row, 5].Value = billNumber;
row++;
worksheet.Cells[row, 4].Value = "Semaine";
worksheet.Cells[row, 5].Value = DateTime.Now.GetIso8601WeekOfYear();
row++;
worksheet.Cells[row, 4].Value = "Nom";
worksheet.Cells[row, 5].Value = weekBasket.Consumer.Name;
row++;
worksheet.Cells[row, 4].Value = "Prénom";
worksheet.Cells[row, 5].Value = weekBasket.Consumer.Surname;
row++;
worksheet.Cells[row, 4].Value = "Téléphone";
worksheet.Cells[row, 5].Value = weekBasket.Consumer.PhoneNumber;
worksheet.Cells[1, 4, row, 4].Style.Font.Bold = true;
worksheet.Cells[1, 5, row, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
row++;
worksheet.Cells[row, 4, row + 1, 5].Merge = true;
var total = worksheet.Cells[row, 6, row + 1, 6];
total.Merge = true;
worksheet.Cells[row, 4, row + 1, 5].Value = "TOTAL";
worksheet.Cells[row, 4, row + 1, 6].Style.Font.Size = 18;
worksheet.Cells[row, 4, row + 1, 6].Style.Font.Bold = true;
worksheet.Cells[row, 4, row + 1, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
worksheet.Cells[row, 4, row + 1, 6].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
//Add product informations
row++;
row++;
row++;
worksheet.Cells[row, 1, row, 2].Merge = true;
worksheet.Cells[row, 1, row, 2].Value = "NOM";
worksheet.Cells[row, 3].Value = "TYPE";
worksheet.Cells[row, 4].Value = "PRIX UNITAIRE";
worksheet.Cells[row, 5].Value = "QUANTITE";
worksheet.Cells[row, 6].Value = "PRIX TOTAL";
//Create list of bill entry by product
Dictionary<Producer, List<BillEntry>> producersProducts = new Dictionary<Producer, List<BillEntry>>();
foreach (var billEntryConsumer in weekBasket.Products)
{
var billEntry = dbContext.BillEntrys.Include(x => x.Product).ThenInclude(x=>x.Producer).First(x => x.Id == billEntryConsumer.Id);
if (!producersProducts.ContainsKey(billEntry.Product.Producer))
{
producersProducts.Add(billEntry.Product.Producer, new List<BillEntry>());
}
producersProducts[billEntry.Product.Producer].Add(billEntry);
}
List<int> rowsTotal = new List<int>();
// - Add products by producer
foreach (var producer in producersProducts.Keys.OrderBy(x => x.Id))
{
row++;
worksheet.Cells[row, 1, row + 1, 6].Merge = true;
worksheet.Cells[row, 1, row + 1, 6].Value = producer.CompanyName;
worksheet.Cells[row, 1, row + 1, 6].Style.Font.Size = 22;
worksheet.Cells[row, 1, row + 1, 6].Style.Font.Bold = true;
row++;
row++;
int startRow = row;
foreach (var billEntry in producersProducts[producer].OrderBy(x => x.Product.Name))
{
worksheet.Cells[row, 1, row, 2].Merge = true;
worksheet.Cells[row, 1, row, 2].Value = billEntry.Product.Name; ;
string typeDetail = billEntry.Product.Type == Product.SellType.Piece ? "" : " par " + billEntry.Product.QuantityStepString;
worksheet.Cells[row, 3].Value = EnumHelper<Product.SellType>.GetDisplayValue(billEntry.Product.Type) + typeDetail;
worksheet.Cells[row, 4].Value = billEntry.Product.UnitPrice;
worksheet.Cells[row, 4].Style.Numberformat.Format = "0.00€";
worksheet.Cells[row, 5].Value = billEntry.QuantityString;
worksheet.Cells[row, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheet.Cells[row, 6].Formula = billEntry.Quantity + "*" + new ExcelCellAddress(row, 4).Address;
worksheet.Cells[row, 6].Style.Numberformat.Format = "0.00€";
worksheet.Cells[row, 1, row, 6].Style.Font.Bold = true;
worksheet.Cells[row, 1, row, 6].Style.Font.Size = 13;
worksheet.Cells[row, 1, row, 6].Style.Border.BorderAround(ExcelBorderStyle.Thin);
row++;
}
//Total
worksheet.Cells[row, 5].Value = "TOTAL : ";
worksheet.Cells[row, 6].Formula = string.Format("SUBTOTAL(9,{0})", new ExcelAddress(startRow, 6, row - 1, 6).Address);
worksheet.Cells[row, 6].Style.Numberformat.Format = "0.00€";
worksheet.Cells[row, 5, row, 6].Style.Font.Bold = true;
worksheet.Cells[row, 5, row, 6].Style.Font.Size = 13;
worksheet.Cells[row, 5, row, 6].Style.Border.BorderAround(ExcelBorderStyle.Thin);
rowsTotal.Add(row);
}
//Super total
string totalFormula = "";
for (int cpt = 0; cpt < rowsTotal.Count; cpt++)
{
totalFormula += new ExcelCellAddress(rowsTotal[cpt], 6).Address;
if (cpt != rowsTotal.Count - 1)
{
totalFormula += "+";
}
}
total.Formula = totalFormula;
total.Style.Numberformat.Format = "0.00€";
//
worksheet.View.PageLayoutView = true;
worksheet.Column(1).Width = (98 - 12 + 5) / 7d + 1;
worksheet.Column(2).Width = (98 - 12 + 5) / 7d + 1;
worksheet.Column(3).Width = (134 - 12 + 5) / 7d + 1;
worksheet.Column(4).Width = (98 - 12 + 5) / 7d + 1;
worksheet.Column(5).Width = (80 - 12 + 5) / 7d + 1;
worksheet.Column(6).Width = (80 - 12 + 5) / 7d + 1;
}
}
// Document properties
package.Workbook.Properties.Title = "Factures : " + billNumber;
package.Workbook.Properties.Author = "Stolons";
package.Workbook.Properties.Comments = "Factures des adhérants de la semaine " + billNumber;
// Extended property values
package.Workbook.Properties.Company = "Association Stolons";
// save our new workbook and we are done!
package.Save();
}
}
/*
*BILL NAME INFORMATION
*Bills are stored like that : bills\UserId\Year_WeekNumber_UserId
*/
private static ProducerBill GenerateBill(Producer producer, List<BillEntryConsumer> billEntries, ApplicationDbContext dbContext)
{
//DEBUT FIX
StringBuilder builder = new StringBuilder();
#region Par produit
//Create list of bill entry by product
Dictionary<Product, List<BillEntryConsumer>> products = new Dictionary<Product, List<BillEntryConsumer>>();
foreach (var billEntryConsumer in billEntries)
{
if (!products.ContainsKey(billEntryConsumer.BillEntry.Product))
{
products.Add(billEntryConsumer.BillEntry.Product, new List<BillEntryConsumer>());
}
products[billEntryConsumer.BillEntry.Product].Add(billEntryConsumer);
}
builder.AppendLine("<h2>Commande par produit</h2>");
builder.AppendLine("<table class=\"table\">");
builder.AppendLine("<tr>");
builder.AppendLine("<th>Produit</th>");
builder.AppendLine("<th>Quantité</th>");
builder.AppendLine("</tr>");
foreach (var product in products)
{
int quantity = 0;
product.Value.ForEach(x => quantity += x.BillEntry.Quantity);
builder.AppendLine("<tr>");
builder.AppendLine("<td>" + product.Key.Name + "</td>");
builder.AppendLine("<td>" + product.Key.GetQuantityString(quantity) + "</td>");
builder.AppendLine("</tr>");
}
builder.AppendLine("</table>");
#endregion Par produit
#region Par client
builder.AppendLine("<h2>Commande par client</h2>");
var billEntriesByConsumer = billEntries.GroupBy(x => x.Consumer);
builder.AppendLine("<table class=\"table\">");
builder.AppendLine("<tr>");
builder.AppendLine("<th>Client</th>");
builder.AppendLine("<th>Produit</th>");
builder.AppendLine("<th>Quantité</th>");
builder.AppendLine("</tr>");
foreach (var group in billEntriesByConsumer.OrderBy(x => x.Key.Id))
{
builder.AppendLine("<tr>");
builder.AppendLine("<td colspan=\"3\" style=\"border-top:1px solid;\">" + "<b>" + group.Key.Id + "</b>" + "</td>");
builder.AppendLine("</tr>");
foreach (var entries in group.OrderBy(x => x.BillEntry.Product.Name))
{
builder.AppendLine("<tr>");
builder.AppendLine("<td></td>");
builder.AppendLine("<td>" + entries.BillEntry.Product.Name + "</td>");
builder.AppendLine("<td>" + entries.BillEntry.QuantityString + "</td>");
builder.AppendLine("</tr>");
}
}
builder.AppendLine("</table>");
#endregion Par client
AuthMessageSender.SendEmail(producer.Email, "", "Stolons: résumé de votre livraison de la semaine", builder.ToString(), null, null);
//FIN FIX
ProducerBill bill = CreateBill<ProducerBill>(producer);
//Generate exel file with bill number for user
string producerBillsPath = Path.Combine(Configurations.Environment.WebRootPath, Configurations.ProducersBillsStockagePath, bill.User.Id.ToString());
string newBillPath = Path.Combine(producerBillsPath, bill.BillNumber + ".xlsx");
FileInfo newFile = new FileInfo(newBillPath);
if (newFile.Exists)
{
//Normaly impossible
newFile.Delete(); // ensures we create a new workbook
newFile = new FileInfo(newBillPath);
}
else
{
Directory.CreateDirectory(producerBillsPath);
}
using (ExcelPackage package = new ExcelPackage(newFile))
{
#region Facture par produit
// add a new worksheet to the empty workbook
ExcelWorksheet worksheetByProduct = package.Workbook.Worksheets.Add("Facture par produit");
int row = 1;
//Add global informations
worksheetByProduct.Cells[row, 1].Value = "Producteur :";
worksheetByProduct.Cells[row, 2].Value = producer.CompanyName;
worksheetByProduct.Cells[row, 2].Style.Font.Bold = true;
worksheetByProduct.Cells[row ,2].Style.Font.Size = 14;
row++;
worksheetByProduct.Cells[row, 1].Value = "Numéro de facture :";
worksheetByProduct.Cells[row, 2].Value = bill.BillNumber;
row++;
worksheetByProduct.Cells[row, 1].Value = "Année :";
worksheetByProduct.Cells[row, 2].Value = DateTime.Now.Year;
row++;
worksheetByProduct.Cells[row, 1].Value = "Semaine :";
worksheetByProduct.Cells[row, 2].Value = DateTime.Now.GetIso8601WeekOfYear();
row++;
worksheetByProduct.Cells[1, 1, row, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
worksheetByProduct.Cells[1, 1, row, 1].Style.Font.Bold = true;
//Add product informations
row++;
row++;
//Create list of bill entry by product
List<int> rowsTotal = new List<int>();
// - Add products
foreach (var prod in products)
{
// - Add the headers
string typeDetail = prod.Key.Type == Product.SellType.Piece ? "" : " par " + prod.Key.QuantityStepString;
worksheetByProduct.Cells[row, 2].Value = EnumHelper<Product.SellType>.GetDisplayValue(prod.Key.Type) + typeDetail;
worksheetByProduct.Cells[row, 4].Value = prod.Key.UnitPrice;
worksheetByProduct.Cells[row, 4].Style.Numberformat.Format = "0.00€";
worksheetByProduct.Cells[row, 2, row, 4].Style.Font.Bold = true;
worksheetByProduct.Cells[row, 2, row, 4].Style.Font.Size = 12;
worksheetByProduct.Cells[row, 2, row, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
worksheetByProduct.Cells[row, 2, row, 4].Style.Border.BorderAround(ExcelBorderStyle.Thin);
int unitPriceRow = row;
row++;
worksheetByProduct.Cells[row - 1, 1, row, 1].Merge = true;
worksheetByProduct.Cells[row - 1, 1, row, 1].Value = prod.Key.Name;
worksheetByProduct.Cells[row - 1, 1, row, 1].Style.Font.Bold = true;
worksheetByProduct.Cells[row - 1, 1, row, 1].Style.Font.Size = 16;
worksheetByProduct.Cells[row - 1, 1, row, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
worksheetByProduct.Cells[row - 1, 1, row, 1].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
worksheetByProduct.Cells[row - 1, 1, row, 1].Style.Border.BorderAround(ExcelBorderStyle.Thin);
worksheetByProduct.Cells[row, 2].Value = "Gestion";
worksheetByProduct.Cells[row, 3].Value = "Quantité";
worksheetByProduct.Cells[row, 4].Value = "Prix total";
worksheetByProduct.Cells[row, 2, row, 4].Style.Font.Bold = true;
worksheetByProduct.Cells[row, 2, row, 4].Style.Font.Size = 12;
worksheetByProduct.Cells[row, 2, row, 4].Style.Border.BorderAround(ExcelBorderStyle.Thin);
row++;
int productStartRow = row;
foreach (var billEntryConsumer in prod.Value.OrderBy(x => x.Consumer.Id))
{
worksheetByProduct.Cells[row, 1].Value = "• " + billEntryConsumer.Consumer.Id;
worksheetByProduct.Cells[row, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheetByProduct.Cells[row, 2].Value = billEntryConsumer.BillEntry.Quantity;
worksheetByProduct.Cells[row, 3].Value = billEntryConsumer.BillEntry.QuantityString;
worksheetByProduct.Cells[row, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheetByProduct.Cells[row, 4].Formula = new ExcelCellAddress(row, 2).Address + "*" + new ExcelCellAddress(unitPriceRow, 4).Address;
worksheetByProduct.Cells[row, 4].Style.Numberformat.Format = "0.00€";
worksheetByProduct.Cells[row, 5].Value = "☐";
worksheetByProduct.Cells[row, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
row++;
}
worksheetByProduct.Cells[productStartRow, 1, row, 1].Style.Border.BorderAround(ExcelBorderStyle.Thin);
worksheetByProduct.Cells[productStartRow, 2, row, 4].Style.Border.BorderAround(ExcelBorderStyle.Thin);
worksheetByProduct.Cells[productStartRow, 2, row, 4].Style.Border.BorderAround(ExcelBorderStyle.Thin);
rowsTotal.Add(row);
//TOTAL SANS COMISSION
worksheetByProduct.Cells[row, 1].Value = "Total sans comission";
worksheetByProduct.Cells[row, 2].Formula = string.Format("SUBTOTAL(9,{0})", new ExcelAddress(productStartRow, 2, row - 1, 2).Address);
worksheetByProduct.Cells[row, 3].Formula = string.Format("SUBTOTAL(9,{0})", new ExcelAddress(productStartRow, 2, row - 1, 2).Address);
worksheetByProduct.Cells[row, 4].Formula = new ExcelCellAddress(row, 2).Address + "*" + new ExcelCellAddress(unitPriceRow, 4).Address;
worksheetByProduct.Cells[row, 4].Style.Numberformat.Format = "0.00€";
worksheetByProduct.Cells[row, 1, row, 4].Style.Font.Size = 9;
worksheetByProduct.Cells[row, 1, row, 4].Style.Font.Italic = true;
worksheetByProduct.Cells[row, 1, row, 4].Style.Border.BorderAround(ExcelBorderStyle.Thin);
worksheetByProduct.Cells[row, 1, row, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
row++;
//COMISSION
worksheetByProduct.Cells[row, 1].Value = "Comission";
worksheetByProduct.Cells[row, 2].Value = Configurations.ApplicationConfig.Comission + "%";
worksheetByProduct.Cells[row, 3].Value = Configurations.ApplicationConfig.Comission + "%";
worksheetByProduct.Cells[row, 4].Formula = new ExcelCellAddress(row, 2).Address + "*" + new ExcelCellAddress(row - 1, 4).Address;
worksheetByProduct.Cells[row, 4].Style.Numberformat.Format = "0.00€";
worksheetByProduct.Cells[row, 1, row, 4].Style.Font.Size = 9;
worksheetByProduct.Cells[row, 1, row, 4].Style.Font.Italic = true;
worksheetByProduct.Cells[row, 1, row, 4].Style.Border.BorderAround(ExcelBorderStyle.Thin);
worksheetByProduct.Cells[row, 1, row, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
row++;
//TOTAL AVEC COMISSION
worksheetByProduct.Cells[row, 1].Value = "TOTAL";
worksheetByProduct.Cells[row, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheetByProduct.Cells[row, 2].Formula = new ExcelCellAddress(row -2, 2).Address;
worksheetByProduct.Cells[row, 2].Style.Border.BorderAround(ExcelBorderStyle.Thin);
int totalQuantity = 0;
prod.Value.ForEach(billEntry => totalQuantity += billEntry.BillEntry.Quantity);
worksheetByProduct.Cells[row, 3].Value = prod.Key.GetQuantityString(totalQuantity);
worksheetByProduct.Cells[row, 4].Formula = new ExcelCellAddress(row - 2, 4).Address + "-" + new ExcelCellAddress(row - 1, 4).Address;
worksheetByProduct.Cells[row, 4].Style.Numberformat.Format = "0.00€";
worksheetByProduct.Cells[row, 1, row, 4].Style.Font.Bold = true;
worksheetByProduct.Cells[row, 1, row, 4].Style.Border.BorderAround(ExcelBorderStyle.Thin);
worksheetByProduct.Cells[row, 5].Value = "☐";
worksheetByProduct.Cells[row, 1, row, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
worksheetByProduct.Cells[row, 1, row, 5].Style.Font.Size = 14;
//
//Next product
row++;
row++;
}
//Super total
string totalWhitoutComissionFormula ="";
string totalComission = "";
for (int cpt = 0; cpt<rowsTotal.Count;cpt++)
{
totalWhitoutComissionFormula += new ExcelCellAddress(rowsTotal[cpt], 4).Address;
totalComission += new ExcelCellAddress(rowsTotal[cpt] +1, 4).Address;
if (cpt != rowsTotal.Count -1)
{
totalWhitoutComissionFormula += "+";
totalComission += "+";
}
}
worksheetByProduct.Cells[row, 3].Value = "Total sans comission";
worksheetByProduct.Cells[row, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheetByProduct.Cells[row, 4].Formula = totalWhitoutComissionFormula;
worksheetByProduct.Cells[row, 4].Style.Numberformat.Format = "0.00€";
worksheetByProduct.Cells[row, 3, row, 4].Style.Font.Italic = true;
worksheetByProduct.Cells[row, 3, row, 4].Style.Font.Size = 9;
row++;
worksheetByProduct.Cells[row, 3].Value = "Total comission à " + Configurations.ApplicationConfig.Comission + "%";
worksheetByProduct.Cells[row, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheetByProduct.Cells[row, 4].Formula = totalComission;
worksheetByProduct.Cells[row, 4].Style.Numberformat.Format = "0.00€";
worksheetByProduct.Cells[row, 3, row, 4].Style.Font.Italic = true;
worksheetByProduct.Cells[row, 3, row, 4].Style.Font.Size = 9;
row++;
worksheetByProduct.Cells[row, 3].Value = "TOTAL :";
worksheetByProduct.Cells[row, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheetByProduct.Cells[row, 4].Formula = new ExcelCellAddress(row - 2, 4).Address + "-" + new ExcelCellAddress(row - 1, 4).Address;
worksheetByProduct.Cells[row, 4].Style.Numberformat.Format = "0.00€";
worksheetByProduct.Cells[row, 3, row, 4].Style.Font.Bold = true;
worksheetByProduct.Cells[row, 3, row ,4].Style.Font.Size = 18;
//
worksheetByProduct.View.PageLayoutView = true;
worksheetByProduct.Column(1).Width = (290 - 12 + 5) / 7d + 1;
worksheetByProduct.Column(2).Width = 0;
worksheetByProduct.Column(3).Width = (130 - 12 + 5) / 7d + 1;
worksheetByProduct.Column(4).Width = (130 - 12 + 5) / 7d + 1;
worksheetByProduct.Column(5).Width = (40 - 12 + 5) / 7d + 1;
#endregion Facture par produit
#region Facture par client
// add a new worksheet to the empty workbook
ExcelWorksheet worksheetByClient = package.Workbook.Worksheets.Add("Facture par client");
row = 1;
//Add global informations
worksheetByClient.Cells[row, 1].Value = "Producteur :";
worksheetByClient.Cells[row, 2].Value = producer.CompanyName;
worksheetByClient.Cells[row, 2].Style.Font.Bold = true;
worksheetByClient.Cells[row, 2].Style.Font.Size = 14;
row++;
worksheetByClient.Cells[row, 1].Value = "Numéro de facture :";
worksheetByClient.Cells[row, 2].Value = bill.BillNumber;
row++;
worksheetByClient.Cells[row, 1].Value = "Année :";
worksheetByClient.Cells[row, 2].Value = DateTime.Now.Year;
row++;
worksheetByClient.Cells[row, 1].Value = "Semaine :";
worksheetByClient.Cells[row, 2].Value = DateTime.Now.GetIso8601WeekOfYear();
row++;
worksheetByClient.Cells[1, 1, row, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
worksheetByClient.Cells[1, 1, row, 1].Style.Font.Bold = true;
//Add product informations
row++;
row++;
rowsTotal = new List<int>();
foreach (var group in billEntriesByConsumer.OrderBy(x=>x.Key.Id))
{
var clientId = worksheetByClient.Cells[row, 1, row, 5];
clientId.Merge = true;
clientId.Value = group.Key.Id;
clientId.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
clientId.Style.Font.Size = 26;
clientId.Style.Font.Bold = true;
clientId.Style.Border.BorderAround(ExcelBorderStyle.Medium);
row++;
int productStartRow = row;
foreach (var entries in group.OrderBy(x=>x.BillEntry.Product.Name))
{
// 1 Nom > 2 Type > 3 Prix Unitaire > 4 Quantité Total > 5 Prix Total
worksheetByClient.Cells[row, 1].Value = entries.BillEntry.Product.Name;
worksheetByClient.Cells[row, 1].Style.Font.Bold = true;
string typeDetail = entries.BillEntry.Product.Type == Product.SellType.Piece ? "" : " par " + entries.BillEntry.Product.QuantityStepString;
worksheetByClient.Cells[row, 2].Value = EnumHelper<Product.SellType>.GetDisplayValue(entries.BillEntry.Product.Type) + typeDetail;
worksheetByClient.Cells[row, 3].Value = entries.BillEntry.Product.UnitPrice;
worksheetByClient.Cells[row, 3].Style.Numberformat.Format = "0.00€";
worksheetByClient.Cells[row, 4].Value = entries.BillEntry.QuantityString;
worksheetByClient.Cells[row, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheetByClient.Cells[row, 5].Formula = entries.BillEntry.Quantity + "*" + worksheetByClient.Cells[row, 3].Address;
worksheetByClient.Cells[row, 5].Style.Numberformat.Format = "0.00€";
var line = worksheetByClient.Cells[row, 1, row, 5];
line.Style.Font.Size = 13;
line.Style.Border.BorderAround(ExcelBorderStyle.Medium);
worksheetByClient.Cells[row, 6].Value = "☐";
worksheetByClient.Cells[row, 6].Style.Font.Size = 10;
worksheetByClient.Cells[row, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
row++;
}
rowsTotal.Add(row);
//TOTAL SANS COMISSION
worksheetByClient.Cells[row, 4].Value = "Sans comission";
worksheetByClient.Cells[row, 5].Formula = string.Format("SUBTOTAL(9,{0})", new ExcelAddress(productStartRow, 5, row - 1, 5).Address);
worksheetByClient.Cells[row, 5].Style.Numberformat.Format = "0.00€";
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Size = 9;
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Italic = true;
worksheetByClient.Cells[row, 4, row, 5].Style.Border.BorderAround(ExcelBorderStyle.Thin);
worksheetByClient.Cells[row, 4, row, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
row++;
//COMISSION
worksheetByClient.Cells[row, 4].Value = "Comission à "+ Configurations.ApplicationConfig.Comission + " %";
worksheetByClient.Cells[row, 5].Formula = (Configurations.ApplicationConfig.Comission + "%") + " * " + new ExcelCellAddress(row - 1, 5).Address;
worksheetByClient.Cells[row, 5].Style.Numberformat.Format = "0.00€";
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Size = 9;
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Italic = true;
worksheetByClient.Cells[row, 4, row, 5].Style.Border.BorderAround(ExcelBorderStyle.Thin);
worksheetByClient.Cells[row, 4, row, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
row++;
//TOTAL AVEC COMISSION
worksheetByClient.Cells[row, 4].Value = "TOTAL";
worksheetByClient.Cells[row, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheetByClient.Cells[row, 5].Formula = new ExcelCellAddress(row - 2, 5).Address + "-" + new ExcelCellAddress(row - 1, 5).Address;
worksheetByClient.Cells[row, 5].Style.Numberformat.Format = "0.00€";
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Size = 14;
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Bold = true;
worksheetByClient.Cells[row, 4, row, 5].Style.Border.BorderAround(ExcelBorderStyle.Thin);
worksheetByClient.Cells[row, 4, row, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
//☐
worksheetByClient.Cells[row, 6].Value = "☐";
worksheetByClient.Cells[row, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
worksheetByClient.Cells[row, 6].Style.Font.Size = 14;
//
row++;
row++;
}
row++;
//Super Total
totalWhitoutComissionFormula = "";
totalComission = "";
for (int cpt = 0; cpt < rowsTotal.Count; cpt++)
{
totalWhitoutComissionFormula += new ExcelCellAddress(rowsTotal[cpt], 5).Address;
totalComission += new ExcelCellAddress(rowsTotal[cpt] + 1, 5).Address;
if (cpt != rowsTotal.Count - 1)
{
totalWhitoutComissionFormula += "+";
totalComission += "+";
}
}
worksheetByClient.Cells[row, 4].Value = "Total sans comission";
worksheetByClient.Cells[row, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheetByClient.Cells[row, 5].Formula = totalWhitoutComissionFormula;
worksheetByClient.Cells[row, 5].Style.Numberformat.Format = "0.00€";
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Italic = true;
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Bold = true;
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Size = 10;
row++;
worksheetByClient.Cells[row, 4].Value = "Total comission à " + Configurations.ApplicationConfig.Comission + "%";
worksheetByClient.Cells[row, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheetByClient.Cells[row, 5].Formula = totalComission;
worksheetByClient.Cells[row, 5].Style.Numberformat.Format = "0.00€";
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Italic = true;
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Bold = true;
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Size = 10;
row++;
worksheetByClient.Cells[row, 4].Value = "TOTAL :";
worksheetByClient.Cells[row, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheetByClient.Cells[row, 5].Formula = new ExcelCellAddress(row - 2, 5).Address + "-" + new ExcelCellAddress(row - 1, 5).Address;
worksheetByClient.Cells[row, 5].Style.Numberformat.Format = "0.00€";
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Bold = true;
worksheetByClient.Cells[row, 4, row, 5].Style.Font.Size = 18;
//
//Disposition collone
worksheetByClient.View.PageLayoutView = true;
worksheetByClient.Column(1).Width = (161 - 12 + 5) / 7d + 1;
worksheetByClient.Column(2).Width = (133 - 12 + 5) / 7d + 1;
worksheetByClient.Column(3).Width = (83 - 12 + 5) / 7d + 1;
worksheetByClient.Column(4).Width = (108 - 12 + 5) / 7d + 1;
worksheetByClient.Column(5).Width = (83 - 12 + 5) / 7d + 1;
worksheetByClient.Column(6).Width = (20 - 12 + 5) / 7d + 1;
#endregion Facture par client
// Document properties
package.Workbook.Properties.Title = "Facture : " + bill.BillNumber;
package.Workbook.Properties.Author = "Stolons";
package.Workbook.Properties.Comments = "Facture de la semaine " + bill.BillNumber;
// Extended property values
package.Workbook.Properties.Company = "Association Stolons";
// save our new workbook and we are done!
package.Save();
}
//
return bill;
}
private static ConsumerBill GenerateBill(ValidatedWeekBasket weekBasket, ApplicationDbContext dbContext)
{
ConsumerBill bill = CreateBill<ConsumerBill>(weekBasket.Consumer);
//Generate exel file with bill number for user
string consumerBillsPath = Path.Combine(Configurations.Environment.WebRootPath, Configurations.ConsumersBillsStockagePath, bill.User.Id.ToString());
string newBillPath = Path.Combine(consumerBillsPath, bill.BillNumber + ".xlsx");
FileInfo newFile = new FileInfo(newBillPath);
if (newFile.Exists)
{
//Normaly impossible
newFile.Delete(); // ensures we create a new workbook
newFile = new FileInfo(newBillPath);
}
else
{
Directory.CreateDirectory(consumerBillsPath);
}
using (ExcelPackage package = new ExcelPackage(newFile))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Facture");
//Add global informations
int row = 1;
worksheet.Cells[row, 1].Value = Configurations.ApplicationConfig.StolonsLabel;
row++;
worksheet.Cells[row, 1].Value = Configurations.ApplicationConfig.MailAddress;
row++;
worksheet.Cells[row, 1].Value = Configurations.ApplicationConfig.StolonsPhoneNumber;
row++;
worksheet.Cells[row, 1].Value = Configurations.ApplicationConfig.StolonsAddress;
row++;
worksheet.Cells[row, 5].Value = weekBasket.Consumer.Surname + ", " + weekBasket.Consumer.Name;
row++;
worksheet.Cells[row, 5].Value = weekBasket.Consumer.Email;
row++;
worksheet.Cells[row, 1].Value = "Numéro d'adhérent :";
worksheet.Cells[row, 2].Value = weekBasket.Consumer.Id;
worksheet.Cells[row, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
row++;
worksheet.Cells[row, 1].Value = "Numéro de facture :";
worksheet.Cells[row, 2].Value = bill.BillNumber;
worksheet.Cells[row, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
row++;
worksheet.Cells[row, 1].Value = "Année :";
worksheet.Cells[row, 2].Value = DateTime.Now.Year;
worksheet.Cells[row, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
row++;
worksheet.Cells[row, 1].Value = "Semaine :";
worksheet.Cells[row, 2].Value = DateTime.Now.GetIso8601WeekOfYear();
worksheet.Cells[row, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
row++;
worksheet.Cells[row, 1].Value = "Edité le :";
worksheet.Cells[row, 2].Value = DateTime.Now.ToString();
worksheet.Cells[row, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
row++;
row++;
//Add product informations
worksheet.Cells[row, 1, row + 1, 6].Merge = true;
worksheet.Cells[row, 1, row + 1, 6].Value = "Produits de votre panier de la semaine";
worksheet.Cells[row, 1, row + 1, 6].Style.Font.Bold = true;
worksheet.Cells[row, 1, row + 1, 6].Style.Font.Size = 14;
row++;
row++;
// - Add the headers
worksheet.Cells[row, 1].Value = "NOM";
worksheet.Cells[row, 2].Value = "TYPE";
worksheet.Cells[row, 3].Value = "PRIX UNITAIRE";
worksheet.Cells[row, 4].Value = "QUANTITE";
worksheet.Cells[row, 5].Value = "";
worksheet.Cells[row, 6].Value = "MONTANT";
worksheet.Cells[row, 1, row, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
worksheet.Cells[row, 1, row, 6].Style.Font.Bold = true;
row++;
int startRow = row;
// - Add products
foreach (var tmpBillEntry in weekBasket.Products)
{
var billEntry = dbContext.BillEntrys.Include(x => x.Product).ThenInclude(x => x.Familly).First(x => x.Id == tmpBillEntry.Id);
worksheet.Cells[row, 1].Value = billEntry.Product.Name;
worksheet.Cells[row, 1].Style.Font.Bold = true;
string typeDetail = billEntry.Product.Type == Product.SellType.Piece ? "" : " par " + billEntry.Product.QuantityStepString;
worksheet.Cells[row, 2].Value = EnumHelper<Product.SellType>.GetDisplayValue(billEntry.Product.Type) + typeDetail;
worksheet.Cells[row, 3].Value = billEntry.Product.UnitPrice;
worksheet.Cells[row, 3].Style.Numberformat.Format = "0.00€";
worksheet.Cells[row, 4].Value = billEntry.Quantity;
worksheet.Cells[row, 5].Value = billEntry.QuantityString;
worksheet.Cells[row, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheet.Cells[row, 6].Formula = new ExcelCellAddress(row,3).Address +"*" + new ExcelCellAddress(row, 4).Address;
worksheet.Cells[row, 6].Style.Numberformat.Format = "0.00€";
row++;
}
worksheet.Cells[startRow - 1, 1, row - 1, 6].Style.Border.BorderAround(ExcelBorderStyle.Thin);
//- Add TOTAL
worksheet.Cells[row, 5].Value = "TOTAL : ";
worksheet.Cells[row, 5].Style.Font.Bold = true;
//Add a formula for the value-column
worksheet.Cells[row, 6].Formula = string.Format("SUBTOTAL(9,{0})", new ExcelAddress(startRow, 6, row -1, 6).Address);
worksheet.Cells[row, 6].Style.Numberformat.Format = "0.00€";
worksheet.Cells[row, 6].Style.Font.Bold = true;
row++;
row++;
worksheet.Cells[row, 1].Value = Configurations.ApplicationConfig.OrderDeliveryMessage;
worksheet.Cells[row, 1].Style.Font.Bold = true;
// Document properties
package.Workbook.Properties.Title = "Facture : " + bill.BillNumber;
package.Workbook.Properties.Author = "Stolons";
package.Workbook.Properties.Comments = "Facture de la semaine " + bill.BillNumber;
// Extended property values
package.Workbook.Properties.Company = "Association Stolons";
//Column size
worksheet.View.PageLayoutView = true;
worksheet.Column(1).Width = (134 - 12 + 5) / 7d + 1;
worksheet.Column(2).Width = (134 - 12 + 5) / 7d + 1;
worksheet.Column(3).Width = (90 - 12 + 5) / 7d + 1;
worksheet.Column(4).Width = (80 - 12 + 5) / 7d + 1;
worksheet.Column(5).Width = (80 - 12 + 5) / 7d + 1;
worksheet.Column(6).Width = (80 - 12 + 5) / 7d + 1;
// save our new workbook and we are done!
package.Save();
}
//
return bill;
}
private static T CreateBill<T>(User user) where T : class, IBill , new()
{
IBill bill = new T();
bill.BillNumber = DateTime.Now.Year + "_" + DateTime.Now.GetIso8601WeekOfYear() +"_" + user.Id;
bill.User = user;
bill.State = BillState.Pending;
bill.EditionDate = DateTime.Now;
return bill as T;
}
public static int GetIso8601WeekOfYear(this DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
}
}
}
|
/***********************************************
*
* This class should only contain instructions for using weapons
* and such by the player
*
* The class is functions is meant to be called by another class,
* This class will act of the assumption that there is no restriction
* on WHEN the player can attack
*
***********************************************/
using DChild.Gameplay.Player.Equipments;
using DChild.Inputs;
using UnityEngine;
namespace DChild.Gameplay.Player
{
[System.Serializable]
public class PlayerCombat : IPlayerCombat
{
public struct ComboInfo
{
private Player.State m_state;
private Player.Focus m_focus;
public ComboInfo(Player.State m_state, Player.Focus m_focus)
{
this.m_state = m_state;
this.m_focus = m_focus;
}
public Player.State state => m_state;
public Player.Focus focus => m_focus;
}
[SerializeField]
private float m_downSlashUplift;
private StraightSwordAnimation m_weaponAnimation;
private int m_comboIndex;
private ComboInfo m_currentCombo;
private IPlayer m_player;
private bool m_canReactToEnemyHit;
private const int MAX_COMBO = 3;
public void Initialize(IPlayer player)
{
m_player = player;
m_weaponAnimation = player.animation.straightSwordAnimation;
m_comboIndex = 0;
}
public void OnEnemyHit()
{
if (m_canReactToEnemyHit)
{
if (m_currentCombo.state == Player.State.Midair && m_currentCombo.focus == Player.Focus.Down)
{
m_player.physics.SetVelocity(0, m_downSlashUplift);
m_canReactToEnemyHit = false;
}
}
}
public bool UseWeapon(Player.State state, Player.Focus focus)
{
if (state == Player.State.Standing && focus == Player.Focus.Front)
{
var result = DoWeaponCombo(m_comboIndex);
m_comboIndex++;
if (m_comboIndex >= MAX_COMBO)
{
ResetCombo();
}
if (result)
{
m_canReactToEnemyHit = true;
m_currentCombo = new ComboInfo(state, focus);
}
return result;
}
else
{
ResetCombo();
var result = DoBlendWeaponAttack(state, focus);
if (result)
{
m_canReactToEnemyHit = true;
m_currentCombo = new ComboInfo(state, focus);
}
return result;
}
}
public void ResetCombo()
{
m_comboIndex = 0;
}
private bool DoWeaponCombo(int comboIndex)
{
switch (comboIndex)
{
case 0:
m_weaponAnimation.DoCombo1();
return true;
case 1:
m_weaponAnimation.DoCombo2();
return true;
case 2:
m_weaponAnimation.DoCombo3();
return true;
default:
return false;
}
}
private bool DoBlendWeaponAttack(Player.State state, Player.Focus focus)
{
switch (state)
{
case Player.State.Midair:
if (focus == Player.Focus.Down)
{
m_weaponAnimation.BlendDownSlash();
}
else if (focus == Player.Focus.Front)
{
m_weaponAnimation.BlendFrontSlash();
}
else
{
m_weaponAnimation.BlendUpSlash();
}
return true;
case Player.State.Dashing:
m_weaponAnimation.BlendFrontSlash();
return true;
case Player.State.Crouching:
m_weaponAnimation.BlendFrontSlash();
return true;
//Comment this for now since the animation sucks
//case Player.State.Standing:
// if (focus == Player.Focus.Up)
// {
// m_weaponAnimation.BlendUpSlash();
// }
// return true;
default:
return false;
}
}
}
}
|
using InoDrive.Domain.Entities;
using InoDrive.Domain.Models;
using InoDrive.Domain.Models.InputModels;
using InoDrive.Domain.Models.OutputModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace InoDrive.Api.App_Start
{
public static class AutoMapperConfig
{
public static void Register()
{
AutoMapper.Mapper.CreateMap<Trip, OutputMyTripModel>()
.ForMember(pv => pv.OriginPlaceName, opt => opt.MapFrom(src => src.OriginPlace.Name))
.ForMember(pv => pv.DestinationPlaceName, opt => opt.MapFrom(src => src.DestinationPlace.Name))
.ForMember(pv => pv.FirstName, opt => opt.MapFrom(src => src.User.FirstName))
.ForMember(pv => pv.LastName, opt => opt.MapFrom(src => src.User.LastName))
.ForMember(pv => pv.TotalPlaces, opt => opt.MapFrom(src => src.PeopleCount))
.ForMember(pv => pv.IsEnded, opt => opt.MapFrom(src => src.EndDate < DateTimeOffset.Now))
.ForMember(pv => pv.IsStarted, opt => opt.MapFrom(src => src.LeavingDate < DateTimeOffset.Now))
.ForMember(pv => pv.FreePlaces, opt => opt.MapFrom(src => src.PeopleCount - src.Bids.Count(b => b.IsAccepted == true)));
AutoMapper.Mapper.CreateMap<Trip, OutputFindTripModel>()
.ForMember(pv => pv.OriginPlaceName, opt => opt.MapFrom(src => src.OriginPlace.Name))
.ForMember(pv => pv.DestinationPlaceName, opt => opt.MapFrom(src => src.DestinationPlace.Name))
//.ForMember(pv => pv.UserId, opt => opt.MapFrom(src => src.UserId))
.ForMember(pv => pv.FirstName, opt => opt.MapFrom(src => src.User.FirstName))
.ForMember(pv => pv.LastName, opt => opt.MapFrom(src => src.User.LastName))
.ForMember(pv => pv.TotalPlaces, opt => opt.MapFrom(src => src.PeopleCount))
.ForMember(pv => pv.IsEnded, opt => opt.MapFrom(src => src.EndDate < DateTimeOffset.Now))
.ForMember(pv => pv.IsStarted, opt => opt.MapFrom(src => src.LeavingDate < DateTimeOffset.Now))
.ForMember(pv => pv.FreePlaces, opt => opt.MapFrom(src => src.PeopleCount - src.Bids.Count(b => b.IsAccepted == true)))
.ForMember(pv => pv.Rating, opt => opt.MapFrom(src =>
((double)(src.User.Trips.SelectMany(lk => lk.Commnents).Select(n => n.Vote).Sum()) /
(double)(src.User.Trips.SelectMany(l => l.Commnents).Count() * 5)) * 100
));
AutoMapper.Mapper.CreateMap<Trip, InputEditTripModel>()
.ForMember(pv => pv.WayPoints, opt => opt.MapFrom(src => new List<PlaceModel>()))
.ForMember(pv => pv.RawOriginPlace, opt => opt.MapFrom(src => new PlaceModel
{
PlaceId = src.OriginPlace.PlaceId,
Name = src.OriginPlace.Name
}))
.ForMember(pv => pv.RawDestinationPlace, opt => opt.MapFrom(src => new PlaceModel
{
PlaceId = src.DestinationPlace.PlaceId,
Name = src.DestinationPlace.Name
}));
AutoMapper.Mapper.CreateMap<Trip, OutputTripModel>()
.ForMember(pv => pv.Initials, opt => opt.MapFrom(src => src.User.FirstName + " " + src.User.LastName))
.ForMember(pv => pv.OriginPlace, opt => opt.MapFrom(src => new PlaceModel
{
PlaceId = src.OriginPlaceId,
Name = src.OriginPlace.Name,
Lat = src.OriginPlace.Latitude,
Lng = src.OriginPlace.Longitude
}))
.ForMember(pv => pv.DestinationPlace, opt => opt.MapFrom(src => new PlaceModel
{
PlaceId = src.DestinationPlaceId,
Name = src.DestinationPlace.Name,
Lat = src.DestinationPlace.Latitude,
Lng = src.DestinationPlace.Longitude
}))
.ForMember(pv => pv.TotalPlaces, opt => opt.MapFrom(src => src.PeopleCount))
.ForMember(pv => pv.FreePlaces, opt => opt.MapFrom(src => src.PeopleCount - src.Bids.Count(b => b.IsAccepted == true)))
.ForMember(pv => pv.IsEnded, opt => opt.MapFrom(src => src.EndDate < DateTimeOffset.Now))
.ForMember(pv => pv.WayPoints, opt => opt.MapFrom(src => src.WayPoints.OrderBy(w => w.WayPointIndex).Select(wp => new PlaceModel
{
PlaceId = wp.PlaceId,
Name = wp.Place.Name,
Lat = wp.Place.Latitude,
Lng = wp.Place.Longitude
}).ToList<PlaceModel>()))
.ForMember(pv => pv.UserIndicators, opt => opt.MapFrom(src => src.Bids.Where(b => b.IsAccepted == true).Select(ui => new UserIndicator
{
UserId = ui.UserId,
AvatarImage = ui.User.AvatarImage,
FirstName = ui.User.FirstName,
LastName = ui.User.LastName,
WasTriped =
(ui.User.Trips.Any(t => !t.IsDeleted && t.EndDate < DateTimeOffset.Now) ||
ui.User.Bids.Any(b => b.IsAccepted == true && b.Trip.EndDate < DateTimeOffset.Now))
}).ToList<UserIndicator>()));
}
}
} |
namespace ElementsInRange
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Wintellect.PowerCollections;
class MainProgram
{
static void Main()
{
StringBuilder allProductsToString = new StringBuilder();
Stopwatch stopWatch = new Stopwatch();
OrderedBag<Product> orderedBag = new OrderedBag<Product>();
int ranges = 10000;
stopWatch.Start();
AddProductsToBag(orderedBag, 500001);
for (int i = 0; i < ranges; i++)
{
stopWatch.Start();
List<Product> found = FindFirst20(orderedBag, 100000, 100000 + i * 2);
//time for adding to stringbuilder not included
stopWatch.Stop();
allProductsToString.Append(found.GetProductsToString());
}
// uncomment to see all ranges found
// Console.WriteLine(allProductsToString.ToString());
Console.WriteLine("Adding products and range searching done in: {0}", stopWatch.Elapsed);
}
public static void AddProductsToBag(OrderedBag<Product> orderedBag, int numberOfItems)
{
for (int i = 1; i < numberOfItems; i++)
{
orderedBag.Add(new Product(i.ToString(), i));
}
}
public static List<Product> FindFirst20(OrderedBag<Product> orderedBag, int lowPrice, int highPrice)
{
var result = orderedBag.Range(new Product("searchItem", highPrice), true,
new Product("searchItem", lowPrice), true);
List<Product> listResult = new List<Product>();
if (result.Count == 0)
{
return listResult;
}
for (int i = 0; i < 20 && i < result.Count; i++)
{
listResult.Add(result[i]);
}
return listResult;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// Author: M. Fathir Irhas | OpenKattis | 02/06/2017
namespace Unbearablezoo
{
class Program
{
static List<List<string>> ListOfAnimals(List<List<string>> list){
List<List<string>> e = new List<List<string>>();
foreach(var sublist in list){
List<string> ee = new List<string>();
for(int i=0;i<sublist.Count;i++){
string k = sublist[i].Split(' ').Last().ToLower();
ee.Add(k);
}
ee.Sort();
e.Add(ee);
}
return e;
}
static void CountOfAnimals(List<List<string>> list){
List<List<string>> loa = ListOfAnimals(list);
for(int i=0;i<loa.Count;i++){
Console.WriteLine("List "+(i+1)+":");
var vc = from x in loa[i]
group x by x into g
let count = g.Count()
select new {Value = g.Key, Count= count};
foreach(var x in vc){
Console.WriteLine(x.Value +" | "+x.Count);
}
}
}
static void Main(string[] args)
{
int num;
string animal;
List<List<string>> list = new List<List<string>>();
while((num = Int32.Parse(Console.ReadLine())) != 0){
List<string> l = new List<string>();
for(int i=0;i<num;i++){
animal = Console.ReadLine();
l.Add(animal);
}
list.Add(l);
}
CountOfAnimals(list);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.ModelConfiguration.Conventions;
using Repository.Entities;
namespace Repository.Context
{
public class AuthContext : DbContext
{
public AuthContext() : base("DefaultConnection")
{
Configuration.ProxyCreationEnabled = false;
//Database.SetInitializer(new MigrateDatabaseToLatestVersion<ProductContext, Repository.Migrations.Configuration>("DefaultConnection"));
Database.SetInitializer<AuthContext>(null);
}
public DbSet<Expense> Expense { set; get; }
public DbSet<Category> Category { set; get; }
public DbSet<Bank> Bank { set; get; }
public DbSet<Supplier> Supplier { set; get; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
//modelBuilder.Entity<Activity>()
// .HasRequired<Product>(s => s.Products)
// .WithMany(s => s.Activities)
// .HasForeignKey(s => s.Id);
base.OnModelCreating(modelBuilder);
}
}
}
|
using Microsoft.AspNetCore.Mvc;
namespace IntegrationAdaptersPharmacySystemService.Controllers
{
[Route("[controller]")]
[ApiController]
public class PingController : ControllerBase
{
public IActionResult Ping()
{
return Ok("Service-1");
}
}
}
|
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Pobs.Domain.Entities;
using Pobs.Tests.Integration.Helpers;
using Pobs.Web.Models.Watching;
using Xunit;
namespace Pobs.Tests.Integration.Watching
{
public class PostWatchAnswerTests : IDisposable
{
private string _buildUrl(int questionId, int answerId) => $"/api/questions/{questionId}/answers/{answerId}/watch";
private readonly User _user;
private readonly Answer _answer;
public PostWatchAnswerTests()
{
_user = DataHelpers.CreateUser();
_answer = DataHelpers.CreateQuestions(_user, 1, _user, 1).Single().Answers.Single();
}
[Fact]
public async Task Add_ShouldAddWatch()
{
using (var server = new IntegrationTestingServer())
using (var client = server.CreateClient())
{
client.AuthenticateAs(_user.Id);
var url = _buildUrl(_answer.Question.Id, _answer.Id);
var response = await client.PostAsync(url, null);
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
var watchingAnswerModel = JsonConvert.DeserializeObject<WatchingAnswerListItemModel>(responseContent);
Assert.Equal(_answer.Question.Id, watchingAnswerModel.QuestionId);
Assert.Equal(_answer.Question.Slug, watchingAnswerModel.QuestionSlug);
Assert.Equal(_answer.Question.Text, watchingAnswerModel.QuestionText);
Assert.Equal(_answer.Id, watchingAnswerModel.AnswerId);
Assert.Equal(_answer.Slug, watchingAnswerModel.AnswerSlug);
Assert.Equal(_answer.Text, watchingAnswerModel.AnswerText);
using (var dbContext = TestSetup.CreateDbContext())
{
Assert.True(dbContext.Watches.Any(x => x.UserId == _user.Id && x.AnswerId == _answer.Id));
}
}
}
[Fact]
public async Task Add_AlreadyWatching_ShouldReturnConflict()
{
using (var dbContext = TestSetup.CreateDbContext())
{
dbContext.Watches.Add(new Watch(_user.Id) { AnswerId = _answer.Id });
dbContext.SaveChanges();
}
using (var server = new IntegrationTestingServer())
using (var client = server.CreateClient())
{
client.AuthenticateAs(_user.Id);
var url = _buildUrl(_answer.Question.Id, _answer.Id);
var response = await client.PostAsync(url, null);
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
var responseContent = await response.Content.ReadAsStringAsync();
Assert.Equal("Watch already exists.", responseContent);
using (var dbContext = TestSetup.CreateDbContext())
{
Assert.True(dbContext.Watches.Any(x => x.UserId == _user.Id && x.AnswerId == _answer.Id));
}
}
}
[Fact]
public async Task Remove_ShouldRemoveWatch()
{
using (var dbContext = TestSetup.CreateDbContext())
{
dbContext.Watches.Add(new Watch(_user.Id) { AnswerId = _answer.Id });
dbContext.SaveChanges();
}
using (var server = new IntegrationTestingServer())
using (var client = server.CreateClient())
{
client.AuthenticateAs(_user.Id);
var url = _buildUrl(_answer.Question.Id, _answer.Id);
var response = await client.DeleteAsync(url);
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
var watchModel = JsonConvert.DeserializeObject<WatchResponseModel>(responseContent);
Assert.False(watchModel.Watching);
using (var dbContext = TestSetup.CreateDbContext())
{
Assert.False(dbContext.Watches.Any(x => x.UserId == _user.Id && x.AnswerId == _answer.Id));
}
}
}
[Fact]
public async Task Remove_NotWatching_ShouldReturnBadRequest()
{
using (var server = new IntegrationTestingServer())
using (var client = server.CreateClient())
{
client.AuthenticateAs(_user.Id);
var url = _buildUrl(_answer.Question.Id, _answer.Id);
var response = await client.DeleteAsync(url);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var responseContent = await response.Content.ReadAsStringAsync();
Assert.Equal("Watch does not exist.", responseContent);
using (var dbContext = TestSetup.CreateDbContext())
{
Assert.False(dbContext.Watches.Any(x => x.UserId == _user.Id && x.AnswerId == _answer.Id));
}
}
}
[Fact]
public async Task Add_NotAuthenticated_ShouldBeDenied()
{
using (var server = new IntegrationTestingServer())
using (var client = server.CreateClient())
{
var url = _buildUrl(_answer.Question.Id, _answer.Id);
var response = await client.PostAsync(url, null);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
[Fact]
public async Task Remove_NotAuthenticated_ShouldBeDenied()
{
using (var server = new IntegrationTestingServer())
using (var client = server.CreateClient())
{
var url = _buildUrl(_answer.Question.Id, _answer.Id);
var response = await client.DeleteAsync(url);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
[Fact]
public async Task Add_UnknownAnswerId_ShouldReturnNotFound()
{
using (var server = new IntegrationTestingServer())
using (var client = server.CreateClient())
{
client.AuthenticateAs(_user.Id);
var url = _buildUrl(_answer.Question.Id, 0);
var response = await client.PostAsync(url, null);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}
[Fact]
public async Task Remove_UnknownAnswerId_ShouldReturnNotFound()
{
using (var server = new IntegrationTestingServer())
using (var client = server.CreateClient())
{
client.AuthenticateAs(_user.Id);
var url = _buildUrl(_answer.Question.Id, 0);
var response = await client.DeleteAsync(url);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}
public void Dispose()
{
DataHelpers.DeleteUser(_user.Id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
namespace Task1
{
class MultiCom
{
static string ConvertGagStringToNumber(string digit)
{
string result = "NO";
switch (digit)
{
case "CHU": result = "0"; break;
case "TEL": result = "1"; break;
case "OFT": result = "2"; break;
case "IVA": result = "3"; break;
case "EMY": result = "4"; break;
case "VNB": result = "5"; break;
case "POQ": result = "6"; break;
case "ERI": result = "7"; break;
case "CAD": result = "8"; break;
case "K-A": result = "9"; break;
case "IIA": result = "10"; break;
case "YLO": result = "11"; break;
case "PLA": result = "12"; break;
default:
break;
}
return result;
}
static BigInteger PowerOfNine(int power)
{
BigInteger result = 1;
for (int i = 0; i < power; i++)
{
result *= 13;
}
return result;
}
static void Main()
{
string input = Console.ReadLine();
string partialInput = string.Empty;
string nineSystemNumber = "";
for (int i = 0; i < input.Length; i++)
{
partialInput += input[i];
string currentDigit =
ConvertGagStringToNumber(partialInput);
if (currentDigit != "NO")
{
nineSystemNumber += currentDigit + " ";
partialInput = "";
}
}
nineSystemNumber.Trim();
// Console.WriteLine(nineSystemNumber);
string[] nums = nineSystemNumber.Split(' ');
List<string> newNums = new List<string>();
foreach (var item in nums)
{
if (item != " " && item != "")
{
newNums.Add(item);
}
}
BigInteger result = 0;
for (int i = 0; i < newNums.Count; i++)
{
BigInteger digit =
BigInteger.Parse(newNums[i]);
result += digit * PowerOfNine(newNums.Count - i - 1);
}
Console.WriteLine(result);
}
}
}
|
namespace Indexer
{
class Program
{
static void Main(string[] args)
{
#region Creating custom collection class
Demo1.Run();
#endregion
#region Creating custom collection class
Demo2.Run();
#endregion
#region Indexing data using string values
Demo2.Run();
#endregion
}
}
}
|
using FluentNHibernate.Automapping;
using FluentNHibernate.Automapping.Alterations;
using Profiling2.Domain.Prf.Events;
using Profiling2.Domain.Prf.Responsibility;
namespace Profiling2.Infrastructure.NHibernateMaps.Overrides
{
public class ViolationMappingOverride : IAutoMappingOverride<Violation>
{
public void Override(AutoMapping<Violation> mapping)
{
mapping.HasManyToMany<Event>(x => x.Events)
.Table("PRF_EventViolation")
.ParentKeyColumn("ViolationID")
.ChildKeyColumn("EventID")
.Inverse()
.Cascade.None()
.AsBag();
mapping.HasManyToMany<PersonResponsibility>(x => x.PersonResponsibilities)
.Table("PRF_PersonResponsibilityViolation")
.ParentKeyColumn("ViolationID")
.ChildKeyColumn("PersonResponsibilityID")
.Inverse()
.Cascade.None()
.AsBag();
mapping.HasMany<Violation>(x => x.ChildrenViolations)
.KeyColumn("ParentViolationID")
.Cascade.None()
.Inverse();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace CompanyRoster
{
public class Company_Roster
{
public static void Main()
{
var company = new List<Employee>();
var n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
var input = Console.ReadLine().Split();
var personName = input[0];
var personSalary = double.Parse(input[1]);
var personPosition = input[2];
var department = input[3];
var currentPerson = new Employee(personName, personSalary, personPosition, department);
if (input.Length > 4)
{
int age;
if (int.TryParse(input[4], out age))
{
currentPerson.Age = age;
}
else
{
currentPerson.Email = input[4];
}
}
if (input.Length > 5)
{
currentPerson.Age = int.Parse(input[5]);
}
company.Add(currentPerson);
}
var depart = company.GroupBy(dep => dep.Department)
.Select(gr => new
{
Name = gr.Key,
AverageSalary = gr.Average(x => x.Salary),
Employees = gr
})
.OrderByDescending(gr => gr.AverageSalary)
.FirstOrDefault();
Console.WriteLine($"Highest Average Salary: {depart.Name}");
foreach (var item in depart.Employees.OrderByDescending(x=>x.Salary))
{
Console.WriteLine(item.PrintEmployeeInfo());
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using BugunNeYesem.Data.Entity;
namespace BugunNeYesem.Data.Repository
{
public interface IRepository
{
bool SaveChanges();
}
public interface IRepository<T> : IRepository
where T : BaseEntity
{
T Insert(T entity);
T Update(T entity);
void Delete(long id);
void Delete(Expression<Func<T, bool>> where);
T SelectFirst(long id, bool isNotCached = false, params Expression<Func<T, object>>[] includeProperties);
T SelectFirst(Expression<Func<T, bool>> where = null, bool isNotCached = false, params Expression<Func<T, object>>[] includeProperties);
T SelectLast(Expression<Func<T, bool>> where = null, bool isNotCached = false, params Expression<Func<T, object>>[] includeProperties);
IQueryable<T> SelectAllOrdered<T2>(Expression<Func<T, bool>> where = null, Expression<Func<T, T2>> orderBy = null, bool isOrderByAsc = true, bool isNotCached = false, params Expression<Func<T, object>>[] includeProperties);
IQueryable<T> SelectPageOrdered<T2>(int pageSize, int pageNumber, Expression<Func<T, bool>> where = null, Expression<Func<T, T2>> orderBy = null, bool isOrderByAsc = true, bool isNotCached = false, params Expression<Func<T, object>>[] includeProperties);
IQueryable<T> SelectAll(Expression<Func<T, bool>> where = null, bool isNotCached = false, params Expression<Func<T, object>>[] includeProperties);
IQueryable<T> SelectPage(int pageSize, int pageNumber, Expression<Func<T, bool>> where = null, bool isNotCached = false, params Expression<Func<T, object>>[] includeProperties);
bool Any(Expression<Func<T, bool>> where);
long Count(Expression<Func<T, bool>> where);
long Max(Expression<Func<T, int>> column, Expression<Func<T, bool>> where = null);
long Min(Expression<Func<T, int>> column, Expression<Func<T, bool>> where = null);
long Sum(Expression<Func<T, long>> column, Expression<Func<T, bool>> where = null);
void BulkInsertSlow(IEnumerable<T> entities);
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace MAS_Końcowy.Migrations
{
public partial class init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "People",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(nullable: true),
Lastname = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_People", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Employees",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
HireDate = table.Column<DateTime>(nullable: false),
PESEL = table.Column<string>(nullable: true),
SanepidBookExpirationDate = table.Column<DateTime>(nullable: true),
Salary = table.Column<decimal>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Employees", x => x.Id);
table.ForeignKey(
name: "FK_Employees_People_Id",
column: x => x.Id,
principalTable: "People",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Ingredients",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(nullable: true),
PricePerKg = table.Column<decimal>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Ingredients", x => x.Id);
});
migrationBuilder.CreateTable(
name: "IngredientSuppliers",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
NIP = table.Column<string>(nullable: true),
CompanyName = table.Column<string>(nullable: true),
HasRefrigeratedTrailers = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IngredientSuppliers", x => x.Id);
table.ForeignKey(
name: "FK_Employees_IngredientSuppliers_Id",
column: x => x.Id,
principalTable: "People",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Menus",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ProfitMargin = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Menus", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Cooks",
columns: table => new
{
Id = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Cooks", x => x.Id);
table.ForeignKey(
name: "FK_Cooks_Employees_Id",
column: x => x.Id,
principalTable: "Employees",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Deliverers",
columns: table => new
{
Id = table.Column<int>(nullable: false),
DrivingLicense = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Deliverers", x => x.Id);
table.ForeignKey(
name: "FK_Deliverers_Employees_Id",
column: x => x.Id,
principalTable: "Employees",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Managers",
columns: table => new
{
Id = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Managers", x => x.Id);
table.ForeignKey(
name: "FK_Managers_Employees_Id",
column: x => x.Id,
principalTable: "Employees",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Waiters",
columns: table => new
{
Id = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Waiters", x => x.Id);
table.ForeignKey(
name: "FK_Waiters_Employees_Id",
column: x => x.Id,
principalTable: "Employees",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Contracts",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
DateOfSigning = table.Column<DateTime>(nullable: false),
ExpirationDate = table.Column<DateTime>(nullable: false),
NumberOfDeliveries = table.Column<int>(nullable: false),
Description = table.Column<string>(nullable: true),
SupplierId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Contracts", x => x.Id);
table.ForeignKey(
name: "FK_Contracts_IngredientSuppliers_SupplierId",
column: x => x.SupplierId,
principalTable: "IngredientSuppliers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Dishes",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(nullable: true),
Price = table.Column<decimal>(nullable: false),
GlutenFree = table.Column<bool>(nullable: false),
Type = table.Column<int>(nullable: false),
AnimalOrigin = table.Column<int>(nullable: false),
MenuId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Dishes", x => x.Id);
table.ForeignKey(
name: "FK_Dishes_Menus_MenuId",
column: x => x.MenuId,
principalTable: "Menus",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Addresses",
columns: table => new
{
Id = table.Column<int>(nullable: false),
StreetName = table.Column<string>(nullable: true),
BuildingNumber = table.Column<string>(nullable: true),
FlatNumber = table.Column<string>(nullable: true),
Postcode = table.Column<string>(nullable: true),
CityName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Addresses", x => x.Id);
table.ForeignKey(
name: "FK_Addresses_People_Id",
column: x => x.Id,
principalTable: "People",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ContractIngredients",
columns: table => new
{
ContractId = table.Column<int>(nullable: false),
IngredientId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ContractIngredients", x => new { x.ContractId, x.IngredientId });
table.ForeignKey(
name: "FK_ContractIngredients_Contracts_ContractId",
column: x => x.ContractId,
principalTable: "Contracts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ContractIngredients_Ingredients_IngredientId",
column: x => x.IngredientId,
principalTable: "Ingredients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "DishContents",
columns: table => new
{
DishId = table.Column<int>(nullable: false),
IngredientId = table.Column<int>(nullable: false),
Quantity = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DishContents", x => new { x.DishId, x.IngredientId });
table.ForeignKey(
name: "FK_DishContents_Dishes_DishId",
column: x => x.DishId,
principalTable: "Dishes",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_DishContents_Ingredients_IngredientId",
column: x => x.IngredientId,
principalTable: "Ingredients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
OrderDate = table.Column<DateTime>(nullable: false),
Price = table.Column<decimal>(nullable: false),
TableNumber = table.Column<int>(nullable: true),
DeliveryAddressId = table.Column<int>(nullable: true),
CookId = table.Column<int>(nullable: true),
WaiterId = table.Column<int>(nullable: true),
DelivererId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Cooks_CookId",
column: x => x.CookId,
principalTable: "Cooks",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Orders_Deliverers_DelivererId",
column: x => x.DelivererId,
principalTable: "Deliverers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Orders_Addresses_DeliveryAddressId",
column: x => x.DeliveryAddressId,
principalTable: "Addresses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Orders_Waiters_WaiterId",
column: x => x.WaiterId,
principalTable: "Waiters",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "OrderContents",
columns: table => new
{
OrderId = table.Column<int>(nullable: false),
DishId = table.Column<int>(nullable: false),
Number = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OrderContents", x => new { x.DishId, x.OrderId });
table.ForeignKey(
name: "FK_OrderContents_Dishes_DishId",
column: x => x.DishId,
principalTable: "Dishes",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_OrderContents_Orders_OrderId",
column: x => x.OrderId,
principalTable: "Orders",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ContractIngredients_IngredientId",
table: "ContractIngredients",
column: "IngredientId");
migrationBuilder.CreateIndex(
name: "IX_Contracts_SupplierId",
table: "Contracts",
column: "SupplierId");
migrationBuilder.CreateIndex(
name: "IX_DishContents_IngredientId",
table: "DishContents",
column: "IngredientId");
migrationBuilder.CreateIndex(
name: "IX_Dishes_MenuId",
table: "Dishes",
column: "MenuId");
migrationBuilder.CreateIndex(
name: "IX_OrderContents_OrderId",
table: "OrderContents",
column: "OrderId");
migrationBuilder.CreateIndex(
name: "IX_Orders_CookId",
table: "Orders",
column: "CookId");
migrationBuilder.CreateIndex(
name: "IX_Orders_DelivererId",
table: "Orders",
column: "DelivererId");
migrationBuilder.CreateIndex(
name: "IX_Orders_DeliveryAddressId",
table: "Orders",
column: "DeliveryAddressId");
migrationBuilder.CreateIndex(
name: "IX_Orders_WaiterId",
table: "Orders",
column: "WaiterId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ContractIngredients");
migrationBuilder.DropTable(
name: "DishContents");
migrationBuilder.DropTable(
name: "Managers");
migrationBuilder.DropTable(
name: "OrderContents");
migrationBuilder.DropTable(
name: "Contracts");
migrationBuilder.DropTable(
name: "Ingredients");
migrationBuilder.DropTable(
name: "Dishes");
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "IngredientSuppliers");
migrationBuilder.DropTable(
name: "Menus");
migrationBuilder.DropTable(
name: "Cooks");
migrationBuilder.DropTable(
name: "Deliverers");
migrationBuilder.DropTable(
name: "Addresses");
migrationBuilder.DropTable(
name: "Waiters");
migrationBuilder.DropTable(
name: "People");
migrationBuilder.DropTable(
name: "Employees");
}
}
}
|
using Newtonsoft.Json;
using ProjectGrace.Logic.Business;
using ProjectGrace.Logic.Business.Business_Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace ProjectGrace.Logic.API.Controllers
{
public class FormController : ApiController
{
private readonly BusinessHelper biz = new BusinessHelper();
public async Task<HttpResponseMessage> Get()
{
return Request.CreateResponse(HttpStatusCode.OK, await biz.GetForms());
}
public async Task<HttpResponseMessage> Post([FromBody]object o)
{
var newForm = JsonConvert.DeserializeObject<FormDTO>(o.ToString());
await biz.AddForm(newForm);
return Request.CreateResponse(HttpStatusCode.OK);
}
public async Task<HttpResponseMessage> Put([FromBody]object o)
{
var newForm = JsonConvert.DeserializeObject<FormDTO>(o.ToString());
await biz.UpdateForm(newForm);
return Request.CreateResponse(HttpStatusCode.OK);
}
public async Task<HttpResponseMessage> Delete([FromBody]object o)
{
var newForm = JsonConvert.DeserializeObject<FormDTO>(o.ToString());
await biz.DeleteForm(newForm);
return Request.CreateResponse(HttpStatusCode.OK);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YoloCampersTwoPointO.Lib;
namespace YoloCampersTwoPointO.Web.Areas.Admin.ViewModels
{
public class CampersIndexVm
{
public IEnumerable<Camper> Campers { get; set; }
}
}
|
using InoDrive.Domain.Models;
using InoDrive.Domain.Models.InputModels;
using InoDrive.Domain.Models.OutputModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InoDrive.Domain.Repositories.Abstract
{
public interface ITripsRepository
{
#region Select
OutputList<OutputFindTripModel> FindTrips(InputFindTripsModel model);
OutputList<OutputMyTripModel> GetAllTrips(InputPageSortModel<Int32> model);
OutputList<OutputMyTripModel> GetDriverTrips(InputPageSortModel<Int32> model);
OutputList<OutputMyTripModel> GetPassengerTrips(InputPageSortModel<Int32> model);
InputEditTripModel GetTripForEdit(InputManageTripModel model);
OutputTripModel GetTrip(InputManageTripModel model);
CarModel GetCar(ShortUserModel model);
#endregion
#region Modifications
void CreateTrip(InputCreateTripModel model);
void RemoveTrip(InputManageTripModel model);
void RecoverTrip(InputManageTripModel model);
void EditTrip(InputCreateTripModel model);
void AddComment(InpuCommentModel model);
#endregion
}
}
|
using System.Collections.Generic;
using ServiceDeskSVC.DataAccess.Models;
namespace ServiceDeskSVC.DataAccess
{
public interface IHelpDeskTicketDocumentRepository
{
List<HelpDesk_TicketDocuments> GetAllDocumentsForTicket(int ticketId);
HelpDesk_TicketDocuments GetSingleDocument(int documentId);
int SaveDocument(HelpDesk_TicketDocuments document);
bool DeleteDocument(int documentID);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.