text stringlengths 13 6.01M |
|---|
using System;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class VAInitializedEvent : Event
{
public const string NAME = "VA initialized";
public const string DESCRIPTION = "Triggered when the VoiceAttack plugin is first initialized";
public const string SAMPLE = @"{""timestamp"":""2017-09-04T00:20:48Z"", ""event"":""VAInitialized"" }";
public VAInitializedEvent(DateTime timestamp) : base(timestamp, NAME)
{ }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DXF.Header
{
/// <summary>
/// Variables string del sistema
/// </summary>
public static class SystemVariable
{
/// <summary>
/// La version de la database de AUTOCAD
/// </summary>
public const string DabaseVersion = "$ACADVER";
/// <summary>
/// Proximo handle disponible (esta variable debe estar presente en la seccion del header)
/// </summary>
public const string HandSeed = "$HANDSEED";
}
}
|
namespace Ach.Fulfillment.Data
{
public class PartnerDetailEntity : BaseEntity
{
public virtual PartnerEntity Partner { get; set; }
public virtual string ImmediateDestination { get; set; }
public virtual string CompanyIdentification { get; set; }
public virtual string Destination { get; set; }
public virtual string OriginOrCompanyName { get; set; }
public virtual string CompanyName { get; set; }
public virtual string DiscretionaryData { get; set; }
public virtual string DfiIdentification { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Hakaima;
public class CharacterManager : MonoBehaviour {
private static CharacterManager instance;
public static CharacterManager Instance {
get {
instance = instance ?? GameObject.FindObjectOfType<CharacterManager> ();
return instance;
}
}
[HideInInspector]
public Dictionary<int, Sprite> spritePlayerGirl;
[HideInInspector]
public Dictionary<int, Sprite> spritePlayerNinja;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
private string[] spriteFileName = {
"right_0",
"right_1",
"right_2",
"left_0",
"left_1",
"left_2",
"top_0",
"top_1",
"top_2",
"bottom_0",
"bottom_1",
"bottom_2",
"spin_right_0",
"spin_left_0",
"spin_top_0",
"spin_bottom_0",
};
public void RegistSpriteList()
{
spritePlayerGirl = new Dictionary<int, Sprite> ();
spritePlayerNinja = new Dictionary<int, Sprite> ();
string body = "Character/Girl/player_";
for (int i = 0; i < spriteFileName.Length; i++) {
Debug.Log (body + spriteFileName [i]);
Sprite spt = Resources.Load<Sprite> (body + spriteFileName [i]) as Sprite;
spritePlayerGirl.Add(i, spt);
}
body = "Character/Ninja/player_";
for (int i = 0; i < spriteFileName.Length; i++) {
Sprite spt = Resources.Load<Sprite> (body + spriteFileName [i]) as Sprite;
spritePlayerNinja.Add(i, spt);
}
}
public void ChangeCharacter()
{
RegistSpriteList ();
ResourceManager.Instance.spritePlayerList.Clear ();
bool flg = true;
if (flg) {
ResourceManager.Instance.spritePlayerList = new Dictionary<int, Sprite> (){
{0 + (int)Player.Compass.Right * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_0, spritePlayerGirl[0] },
{0 + (int)Player.Compass.Right * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_1, spritePlayerGirl[1] },
{0 + (int)Player.Compass.Right * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_2, spritePlayerGirl[2] },
{0 + (int)Player.Compass.Left * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_0, spritePlayerGirl[3] },
{0 + (int)Player.Compass.Left * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_1, spritePlayerGirl[4] },
{0 + (int)Player.Compass.Left * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_2, spritePlayerGirl[5] },
{0 + (int)Player.Compass.Top * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_0, spritePlayerGirl[6] },
{0 + (int)Player.Compass.Top * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_1, spritePlayerGirl[7] },
{0 + (int)Player.Compass.Top * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_2, spritePlayerGirl[8] },
{0 + (int)Player.Compass.Bottom * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_0, spritePlayerGirl[9] },
{0 + (int)Player.Compass.Bottom * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_1, spritePlayerGirl[10] },
{0 + (int)Player.Compass.Bottom * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_2, spritePlayerGirl[11] },
{ResourceManager.SPRITE_MULTI_TYPE + (int)Player.Compass.Right * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_0, spritePlayerGirl[12] },
{ResourceManager.SPRITE_MULTI_TYPE + (int)Player.Compass.Right * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_1, spritePlayerGirl[12] },
{ResourceManager.SPRITE_MULTI_TYPE + (int)Player.Compass.Right * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_2, spritePlayerGirl[12] },
{ResourceManager.SPRITE_MULTI_TYPE + (int)Player.Compass.Left * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_0, spritePlayerGirl[13] },
{ResourceManager.SPRITE_MULTI_TYPE + (int)Player.Compass.Left * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_1, spritePlayerGirl[13] },
{ResourceManager.SPRITE_MULTI_TYPE + (int)Player.Compass.Left * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_2, spritePlayerGirl[13] },
{ResourceManager.SPRITE_MULTI_TYPE + (int)Player.Compass.Top * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_0, spritePlayerGirl[14] },
{ResourceManager.SPRITE_MULTI_TYPE + (int)Player.Compass.Top * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_1, spritePlayerGirl[14] },
{ResourceManager.SPRITE_MULTI_TYPE + (int)Player.Compass.Top * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_2, spritePlayerGirl[14] },
{ResourceManager.SPRITE_MULTI_TYPE + (int)Player.Compass.Bottom * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_0, spritePlayerGirl[15] },
{ResourceManager.SPRITE_MULTI_TYPE + (int)Player.Compass.Bottom * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_1, spritePlayerGirl[15] },
{ResourceManager.SPRITE_MULTI_TYPE + (int)Player.Compass.Bottom * ResourceManager.SPRITE_MULTI_COMPASS + Player.IMAGE_2, spritePlayerGirl[15] },
};
} else {
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OlvinerBrodcast.DAL.Models;
namespace OlvinerBrodcast.Models
{
public class ChatDisplayModel:BaseModel
{
public List<ChatModel> ChatContent { get; set; }
public ChatDisplayModel()
{
ChatContent = new List<ChatModel>();
}
}
public class GetUserChatInputModel
{
public string UserId { get;set;}
public string ChatDate {get;set;}
public bool Mode { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPatterns.Command.Example4
{
public class InsertTextCommand : BaseCommand
{
public InsertTextCommand(ApplicationMakeText app, TextEditor editor) : base(app, editor)
{
}
public override bool Execute()
{
SaveBackup();
editor.Insert(app.CurrentText);
return true;
}
}
}
|
using System;
using Membership.Contract;
using Membership.Data;
namespace Membership.Service
{
public class UserAssembler
{
public UserDto Assemble(User entity)
{
if (entity == null) { return null; }
var userTypeAssembler = new UserTypeAssembler();
var genderAssembler = new GenderAssembler();
return new UserDto
{
Id = entity.Id,
Comment = entity.Comment,
LastUpdatedBy = entity.LastUpdatedBy,
CreatedOn = entity.CreatedOn,
UpdatedOn = entity.UpdatedOn,
DeletedOn = entity.DeletedOn.HasValue ? entity.DeletedOn.Value : new DateTime(),
UserType = userTypeAssembler.Assemble(entity.UserType),
Gender = genderAssembler.Assemble(entity.Gender),
Email = entity.Email,
PasswordHash = entity.PasswordHash,
Names = entity.Names,
FirstName = entity.FirstName,
LastName = entity.LastName,
PreferredName = entity.PreferredName,
IdentityNumber = entity.IdentityNumber,
Birthday = entity.Birthday,
Website = entity.Website,
FacebookId = entity.FacebookId,
TwitterId = entity.TwitterId,
PhotoUrl = entity.PhotoUrl,
IsActive = entity.IsActive,
IsMailingActive = entity.IsMailingActive,
IsOtherMailingActive = entity.IsOtherMailingActive,
AffiliateSlug = entity.AffiliateSlug,
RefererSource = entity.RefererSource,
LastInvoiceAddressId = entity.LastInvoiceAddressId,
LastShippingAddressId = entity.LastShippingAddressId,
Point = entity.Point,
VirtualMoney = entity.VirtualMoney
};
}
}
} |
using System;
using Cosmos.IL2CPU.API;
namespace Cosmos.System_Plugs.System {
[Plug(Target = typeof(Environment))]
public static class EnvironmentImpl {
// [PlugMethod(Signature = "System_Environment_OSName__System_Environment_get_OSInfo__")]
// public static int get_OSName() { return 0x82; }
public static string GetResourceFromDefault(string aResource) {
return "";
}
public static string GetResourceString(string aResource) {
return "";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SqlServerWebAdmin
{
public partial class Error : System.Web.UI.Page
{
private string ErrorLookup(int id)
{
/* To handle more errors:
* When catching the error, redirect to "Error.aspx?errorPassCode="
* followed by the number of your error code, which can be any number
* that is not used already in the switch statement below.
* Finally, just add the case for that number in the switch statement
* below and write a user-friendly error message.
*/
switch (id)
{
case 1000:
return "Database does not exist";
case 1001:
return "Stored procedure does not exist";
case 1002:
return "Table does not exist";
case 1003:
return "Column does not exist";
case 2001: // DatabaseProperties.aspx (user might not have permission to view properties)
return "There was a problem reading the properties of the database. " +
"It is possible you are not authorized to view or change the properties of this database.";
case 2002: // Used whenever the application tries to connect to a database.
return "There was a problem connecting to the database. Please check that " +
"the database is available, your login information is correct, and you have permission to access the database.";
default:
return "An unknown error has occurred. If it continues, please try logging out and logging back in.";
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
// There are two kinds of errors - custom errors with numbers, and uncaught exceptions
if (Request["error"] != null)
{
ErrorLabel.Text = String.Format("Error {0}: {1}", Server.HtmlEncode(Request["error"]), ErrorLookup(Convert.ToInt32(Request["error"])));
}
else if (Request["errormsg"] != null || Request["stacktrace"] != null)
{
ErrorLabel.Text = "Error Message: <br>" + Request["errormsg"].Replace("\n", "<br>") + "<br><br>" +
"Stack Trace: <br>" + Request["stacktrace"].Replace("\n", "<br>");
}
else
{
ErrorLabel.Text = "An unknown error has occured. Please try again.";
Exception x = (Exception)Application["Error"];
while (x != null)
{
ErrorLabel.Text += x.Message.Replace("\n", "<br>") + "<br><br>" + x.StackTrace.Replace("\n", "<br>") + "<br><hr><br>";
x = x.InnerException;
}
Application.Remove("Error");
}
}
}
} |
using Galeri.Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Galeri.Entities.Map
{
public class YorumMap:EntityTypeConfiguration<Yorum>
{
public YorumMap()
{
this.HasKey(c => c.Id);
this.Property(c => c.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
this.Property(c => c.Ad).HasMaxLength(25).IsRequired();
this.Property(c => c.Soyad).HasMaxLength(25).IsRequired();
this.Property(c => c.Mail).HasMaxLength(100).IsRequired();
this.Property(c => c.Icerik).HasMaxLength(2500).IsRequired();
this.Property(c => c.TasitId).IsRequired();
this.ToTable("Yorum");
this.Property(c => c.Id).HasColumnName("Id");
this.Property(c => c.Ad).HasColumnName("Ad");
this.Property(c => c.Soyad).HasColumnName("Soyad");
this.Property(c => c.Mail).HasColumnName("Mail");
this.Property(c => c.Icerik).HasColumnName("Icerik");
this.Property(c => c.TasitId).HasColumnName("TasitId");
}
}
}
|
using Cs_Notas.Aplicacao.Interfaces;
using Cs_Notas.Dominio.Entities;
using Cs_Notas.Dominio.Interfaces.Servicos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Aplicacao.ServicosApp
{
public class AppServicoCadProcuracao: AppServicoBase<CadProcuracao>, IAppServicoCadProcuracao
{
private readonly IServicoCadProcuracao _IServicoCadProcuracao;
public AppServicoCadProcuracao(IServicoCadProcuracao IServicoCadProcuracao)
: base(IServicoCadProcuracao)
{
_IServicoCadProcuracao = IServicoCadProcuracao;
}
public CadProcuracao SalvarAlteracaoProcuracao(CadProcuracao alterar)
{
return _IServicoCadProcuracao.SalvarAlteracaoProcuracao(alterar);
}
public CadProcuracao ObterProcuracaoPorSeloLivroFolhaAto(string selo, string aleatorio, string livro, int folhainicio, int folhaFim, int ato)
{
return _IServicoCadProcuracao.ObterProcuracaoPorSeloLivroFolhaAto(selo, aleatorio, livro, folhainicio, folhaFim, ato);
}
public List<CadProcuracao> ObterProcuracaoPorPeriodo(DateTime dataInicio, DateTime dataFim)
{
return _IServicoCadProcuracao.ObterProcuracaoPorPeriodo(dataInicio, dataFim);
}
public List<CadProcuracao> ObterProcuracaoPorLivro(string livro)
{
return _IServicoCadProcuracao.ObterProcuracaoPorLivro(livro);
}
public List<CadProcuracao> ObterProcuracaoPorAto(int numeroAto)
{
return _IServicoCadProcuracao.ObterProcuracaoPorAto(numeroAto);
}
public List<CadProcuracao> ObterProcuracaoPorSelo(string selo)
{
return _IServicoCadProcuracao.ObterProcuracaoPorSelo(selo);
}
public List<CadProcuracao> ObterProcuracaoPorParticipante(List<int> idsAto)
{
return _IServicoCadProcuracao.ObterProcuracaoPorParticipante(idsAto);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using odatav4webapi.Models;
namespace odatav4webapi.Controllers
{
public class MkupacsController : Controller
{
private AWEntities db = new AWEntities();
// GET: Mkupacs
public async Task<ActionResult> Index()
{
var kupacs = db.Kupacs.Include(k => k.Grad);
return View(await kupacs.ToListAsync());
}
// GET: Mkupacs/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Kupac kupac = await db.Kupacs.FindAsync(id);
if (kupac == null)
{
return HttpNotFound();
}
return View(kupac);
}
// GET: Mkupacs/Create
public ActionResult Create()
{
ViewBag.GradID = new SelectList(db.Grads, "IDGrad", "Naziv");
return View();
}
// POST: Mkupacs/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "IDKupac,Ime,Prezime,Email,Telefon,GradID")] Kupac kupac)
{
if (ModelState.IsValid)
{
db.Kupacs.Add(kupac);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.GradID = new SelectList(db.Grads, "IDGrad", "Naziv", kupac.GradID);
return View(kupac);
}
// GET: Mkupacs/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Kupac kupac = await db.Kupacs.FindAsync(id);
if (kupac == null)
{
return HttpNotFound();
}
ViewBag.GradID = new SelectList(db.Grads, "IDGrad", "Naziv", kupac.GradID);
return View(kupac);
}
// POST: Mkupacs/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "IDKupac,Ime,Prezime,Email,Telefon,GradID")] Kupac kupac)
{
if (ModelState.IsValid)
{
db.Entry(kupac).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.GradID = new SelectList(db.Grads, "IDGrad", "Naziv", kupac.GradID);
return View(kupac);
}
// GET: Mkupacs/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Kupac kupac = await db.Kupacs.FindAsync(id);
if (kupac == null)
{
return HttpNotFound();
}
return View(kupac);
}
// POST: Mkupacs/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
Kupac kupac = await db.Kupacs.FindAsync(id);
db.Kupacs.Remove(kupac);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
/******************************************************************************\
* Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved. *
* Leap Motion proprietary and confidential. Not for distribution. *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
\******************************************************************************/
namespace Leap
{
using System;
/**
* The Matrix struct represents a transformation matrix.
*
* To use this struct to transform a Vector, construct a matrix containing the
* desired transformation and then use the Matrix::transformPoint() or
* Matrix::transformDirection() functions to apply the transform.
*
* Transforms can be combined by multiplying two or more transform matrices using
* the * operator.
* @since 1.0
*/
public struct Matrix
{
/** Multiply two matrices. */
public static Matrix operator *(Matrix m1, Matrix m2)
{
return m1._operator_mul(m2);
}
/** Copy this matrix to the specified array of 9 float values in row-major order. */
public float[] ToArray3x3(float[] output)
{
output[0] = xBasis.x;
output[1] = xBasis.y;
output[2] = xBasis.z;
output[3] = yBasis.x;
output[4] = yBasis.y;
output[5] = yBasis.z;
output[6] = zBasis.x;
output[7] = zBasis.y;
output[8] = zBasis.z;
return output;
}
/** Copy this matrix to the specified array containing 9 double values in row-major order. */
public double[] ToArray3x3(double[] output)
{
output[0] = xBasis.x;
output[1] = xBasis.y;
output[2] = xBasis.z;
output[3] = yBasis.x;
output[4] = yBasis.y;
output[5] = yBasis.z;
output[6] = zBasis.x;
output[7] = zBasis.y;
output[8] = zBasis.z;
return output;
}
/** Convert this matrix to an array containing 9 float values in row-major order. */
public float[] ToArray3x3()
{
return ToArray3x3(new float[9]);
}
/** Copy this matrix to the specified array of 16 float values in row-major order. */
public float[] ToArray4x4(float[] output)
{
output[0] = xBasis.x;
output[1] = xBasis.y;
output[2] = xBasis.z;
output[3] = 0.0f;
output[4] = yBasis.x;
output[5] = yBasis.y;
output[6] = yBasis.z;
output[7] = 0.0f;
output[8] = zBasis.x;
output[9] = zBasis.y;
output[10] = zBasis.z;
output[11] = 0.0f;
output[12] = origin.x;
output[13] = origin.y;
output[14] = origin.z;
output[15] = 1.0f;
return output;
}
/** Copy this matrix to the specified array of 16 double values in row-major order. */
public double[] ToArray4x4(double[] output)
{
output[0] = xBasis.x;
output[1] = xBasis.y;
output[2] = xBasis.z;
output[3] = 0.0f;
output[4] = yBasis.x;
output[5] = yBasis.y;
output[6] = yBasis.z;
output[7] = 0.0f;
output[8] = zBasis.x;
output[9] = zBasis.y;
output[10] = zBasis.z;
output[11] = 0.0f;
output[12] = origin.x;
output[13] = origin.y;
output[14] = origin.z;
output[15] = 1.0f;
return output;
}
/** Convert this matrix to an array containing 16 float values in row-major order. */
public float[] ToArray4x4()
{
return ToArray4x4(new float[16]);
}
/**
* Constructs a copy of the specified Matrix object.
*
* \include Matrix_Matrix_copy.txt
*
* @since 1.0
*/
public Matrix(Matrix other):
this()
{
xBasis = other.xBasis;
yBasis = other.yBasis;
zBasis = other.zBasis;
origin = other.origin;
}
/**
* Constructs a transformation matrix from the specified basis vectors.
*
* \include Matrix_Matrix_basis.txt
*
* @param xBasis A Vector specifying rotation and scale factors for the x-axis.
* @param yBasis A Vector specifying rotation and scale factors for the y-axis.
* @param zBasis A Vector specifying rotation and scale factors for the z-axis.
* @since 1.0
*/
public Matrix(Vector xBasis, Vector yBasis, Vector zBasis) :
this()
{
this.xBasis = xBasis;
this.yBasis = yBasis;
this.zBasis = zBasis;
this.origin = Vector.Zero;
}
/**
* Constructs a transformation matrix from the specified basis and translation vectors.
*
* \include Matrix_Matrix_basis_origin.txt
*
* @param xBasis A Vector specifying rotation and scale factors for the x-axis.
* @param yBasis A Vector specifying rotation and scale factors for the y-axis.
* @param zBasis A Vector specifying rotation and scale factors for the z-axis.
* @param origin A Vector specifying translation factors on all three axes.
* @since 1.0
*/
public Matrix(Vector xBasis, Vector yBasis, Vector zBasis, Vector origin) :
this()
{
this.xBasis = xBasis;
this.yBasis = yBasis;
this.zBasis = zBasis;
this.origin = origin;
}
/**
* Constructs a transformation matrix specifying a rotation around the specified vector.
*
* \include Matrix_Matrix_rotation.txt
*
* @param axis A Vector specifying the axis of rotation.
* @param angleRadians The amount of rotation in radians.
* @since 1.0
*/
public Matrix(Vector axis, float angleRadians) :
this()
{
xBasis = Vector.XAxis;
yBasis = Vector.YAxis;
zBasis = Vector.ZAxis;
origin = Vector.Zero;
this.SetRotation(axis, angleRadians);
}
/**
* Constructs a transformation matrix specifying a rotation around the specified vector
* and a translation by the specified vector.
*
* \include Matrix_Matrix_rotation_translation.txt
*
* @param axis A Vector specifying the axis of rotation.
* @param angleRadians The angle of rotation in radians.
* @param translation A Vector representing the translation part of the transform.
* @since 1.0
*/
public Matrix(Vector axis, float angleRadians, Vector translation) :
this()
{
xBasis = Vector.XAxis;
yBasis = Vector.YAxis;
zBasis = Vector.ZAxis;
origin = translation;
this.SetRotation(axis, angleRadians);
}
public Matrix(float m00,
float m01,
float m02,
float m10,
float m11,
float m12,
float m20,
float m21,
float m22) :
this()
{
xBasis = new Vector(m00, m01, m02);
yBasis = new Vector(m10, m11, m12);
zBasis = new Vector(m20, m21, m22);
origin = Vector.Zero;
}
public Matrix(float m00,
float m01,
float m02,
float m10,
float m11,
float m12,
float m20,
float m21,
float m22,
float m30,
float m31,
float m32) :
this()
{
xBasis = new Vector(m00, m01, m02);
yBasis = new Vector(m10, m11, m12);
zBasis = new Vector(m20, m21, m22);
origin = new Vector(m30, m31, m32);
}
/**
* Sets this transformation matrix to represent a rotation around the specified vector.
*
* \include Matrix_setRotation.txt
*
* This function erases any previous rotation and scale transforms applied
* to this matrix, but does not affect translation.
*
* @param axis A Vector specifying the axis of rotation.
* @param angleRadians The amount of rotation in radians.
* @since 1.0
*/
public void SetRotation(Vector axis, float angleRadians)
{
Vector n = axis.Normalized;
float s = (float)Math.Sin(angleRadians);
float c = (float)Math.Cos(angleRadians);
float C = (1 - c);
xBasis = new Vector(n[0] * n[0] * C + c, n[0] * n[1] * C - n[2] * s, n[0] * n[2] * C + n[1] * s);
yBasis = new Vector(n[1] * n[0] * C + n[2] * s, n[1] * n[1] * C + c, n[1] * n[2] * C - n[0] * s);
zBasis = new Vector(n[2] * n[0] * C - n[1] * s, n[2] * n[1] * C + n[0] * s, n[2] * n[2] * C + c);
}
//TODO functions for getting Axis and Angle from matrix
/**
* Transforms a vector with this matrix by transforming its rotation,
* scale, and translation.
*
* \include Matrix_transformPoint.txt
*
* Translation is applied after rotation and scale.
*
* @param point The Vector to transform.
* @returns A new Vector representing the transformed original.
* @since 1.0
*/
public Vector TransformPoint(Vector point)
{
return xBasis * point.x + yBasis * point.y + zBasis * point.z + origin;
}
/**
* Transforms a vector with this matrix by transforming its rotation and
* scale only.
*
* \include Matrix_transformDirection.txt
*
* @param in The Vector to transform.
* @returns A new Vector representing the transformed original.
* @since 1.0
*/
public Vector TransformDirection(Vector direction)
{
return xBasis * direction.x + yBasis * direction.y + zBasis * direction.z;
}
/**
* Performs a matrix inverse if the matrix consists entirely of rigid
* transformations (translations and rotations). If the matrix is not rigid,
* this operation will not represent an inverse.
*
* \include Matrix_rigidInverse.txt
*
* Note that all matrices that are directly returned by the API are rigid.
*
* @returns The rigid inverse of the matrix.
* @since 1.0
*/
public Matrix RigidInverse()
{
Matrix rotInverse = new Matrix(new Vector(xBasis[0], yBasis[0], zBasis[0]),
new Vector(xBasis[1], yBasis[1], zBasis[1]),
new Vector(xBasis[2], yBasis[2], zBasis[2]));
rotInverse.origin = rotInverse.TransformDirection(-origin);
return rotInverse;
}
/**
* Multiply transform matrices.
*
* Combines two transformations into a single equivalent transformation.
*
* \include Matrix_operator_times.txt
*
* @param other A Matrix to multiply on the right hand side.
* @returns A new Matrix representing the transformation equivalent to
* applying the other transformation followed by this transformation.
* @since 1.0
*/
private Matrix _operator_mul(Matrix other)
{
return new Matrix(TransformDirection(other.xBasis),
TransformDirection(other.yBasis),
TransformDirection(other.zBasis),
TransformPoint(other.origin));
}
/**
* Compare Matrix equality component-wise.
*
* \include Matrix_operator_equals.txt
*
* @since 1.0
*/
public bool Equals(Matrix other)
{
return xBasis == other.xBasis &&
yBasis == other.yBasis &&
zBasis == other.zBasis &&
origin == other.origin;
}
/**
* Write the matrix to a string in a human readable format.
* @since 1.0
*/
public override string ToString()
{
return string.Format("xBasis: {0} yBasis: {1} zBasis: {2} origin: {3}", xBasis, yBasis, zBasis, origin);
}
/**
* The basis vector for the x-axis.
*
* \include Matrix_xBasis.txt
*
* @since 1.0
*/
public Vector xBasis { get; set; }
/**
* The basis vector for the y-axis.
*
* \include Matrix_yBasis.txt
*
* @since 1.0
*/
public Vector yBasis { get; set; }
/**
* The basis vector for the z-axis.
*
* \include Matrix_zBasis.txt
*
* @since 1.0
*/
public Vector zBasis { get; set; }
/**
* The translation factors for all three axes.
*
* \include Matrix_origin.txt
*
* @since 1.0
*/
public Vector origin { get; set; }
/**
* Returns the identity matrix specifying no translation, rotation, and scale.
*
* \include Matrix_identity.txt
*
* @returns The identity matrix.
* @since 1.0
*/
public static readonly Matrix Identity = new Matrix(Vector.XAxis, Vector.YAxis, Vector.ZAxis, Vector.Zero);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Ex03.GarageLogic;
namespace Ex03.ConsoleUI
{
public class GarageUI
{
private enum ekeyBoard { One = 1, Two, Three, Four, Five, Six, Seven, Esc }; // Set menu keys
private GarageLogics m_GarageLogic;
public GarageUI()
{
m_GarageLogic = NewObj.NewGarageLogics();
}
public void InsertVehicle(string i_lincesNumber) // this function insert a new vehicle to garage
{
if (!m_GarageLogic.CheckIfLincesExicetAndTryToUpdate(i_lincesNumber)) // If the vehicle already exists in the garage
{
Console.WriteLine("The Vehicle already exists and change to in process");
}
else // If the vehicle does not exist in the garage
{
Console.WriteLine("The Vehicle is not exists");
MakeANewVehicle(i_lincesNumber); // call to function that create a new vehicle by lincesNumber
}
}
public void MakeANewVehicle(string i_lincesNumber) // this function create a new vehicle by lincesNumber
{
string inputFromUser;
Owner_Details newOwner;
List<string> Quastions; // this list hold the quastios to be displayed to the user
bool isNotCorrectInput = true; // a boolean variable that checks whether the input from the user is correct
newOwner = NewObj.NewOwnerDetails();
Console.WriteLine("Please enter the type of Vichle for example <'electric car, gasolin motorcycle> and press 'Enter'");
while (isNotCorrectInput) // while the input isnt correct
try
{
inputFromUser = Console.ReadLine();// Receiving the type of vehicle from the user
newOwner.ownerVehicle = NewObj.NewVehicle(inputFromUser); // create a new owner
Quastions = newOwner.QuestionsForOwner();
ShowOwnerQuastionsAndCheckAnswear(Quastions, newOwner); // Display the questions related to the vehicle owner to the user
newOwner.ownerVehicle.lincesNumber = i_lincesNumber; // updeate the linces number
Quastions = Vehicle.QuestionsForVehicle();
ShowVehicleQuastionsAndCheckAnswear(Quastions, newOwner); // Display the questions related to the vehicle to the user
Quastions = Wheel.QuestionsForWheel();
ShowWheelsQuastionsAndCheckAnswear(Quastions, newOwner); // Display the questions related to the wheels to the user
Quastions = newOwner.ownerVehicle.engine.QuestionsForEngine();
ShowEngineQuastionsAndCheckAnswear(Quastions, newOwner); // Display the questions related to the engine to the user
newOwner.ownerVehicle.updateTheFualPrecent(); // call to function that updeat the fual precent
Quastions = newOwner.ownerVehicle.QuestionsForAllVehicles();
ShowQuastionsForAllVehicleAndCheckAnswear(Quastions, newOwner); // Display the questions related to the vehicle to the user
m_GarageLogic.AddOwnerToGarage(newOwner);
isNotCorrectInput = false;
}
catch (ArgumentException Ex)
{
Console.WriteLine(Ex.Message);
}
}
public void ShowOwnerQuastionsAndCheckAnswear(List<string> i_quastions, Owner_Details io_newOwner) // this function display the owner questions and checks inputs
{
int numberOfQuestion = 1; // count the number of question
bool isNotCorrectInput = true; // a boolean variable that checks whether the input from the user is correct
string inputFormUser;
foreach (string question in i_quastions) // For each question in the list of questions
{
while (isNotCorrectInput) // while the input isnt correct
{
try
{
isNotCorrectInput = true;
Console.WriteLine(question); // display the question to user
inputFormUser = Console.ReadLine();
io_newOwner.CheckOwnerDetailsInput(inputFormUser, numberOfQuestion); // send the input to a check function
io_newOwner.updateOwnerDetailsInput(inputFormUser, numberOfQuestion); // Update user details
isNotCorrectInput = false;
}
catch (Exception wrrongLogicInput)
{
Console.WriteLine("Iligale input");
Console.WriteLine(wrrongLogicInput.Message);
}
}
numberOfQuestion++;
isNotCorrectInput = true;
}
}
public void ShowVehicleQuastionsAndCheckAnswear(List<string> i_quastions, Owner_Details io_newOwner) // this function display the Vehicle questions and checks inputs
{
int numberOfQuestion = 1; // count the number of question
bool isNotCorrectInput = true; // a boolean variable that checks whether the input from the user is correct
string inputFormUser;
foreach (string question in i_quastions) // For each question in the list of questions
{
while (isNotCorrectInput) // while the input isnt correct
{
try
{
isNotCorrectInput = true;
Console.WriteLine(question); // display the question to user
inputFormUser = Console.ReadLine();
io_newOwner.ownerVehicle.CheckVehicleInput(inputFormUser, numberOfQuestion); // send the input to a check function
io_newOwner.ownerVehicle.UpdateVehicleInput(inputFormUser, numberOfQuestion); // updeate the vehicle details
isNotCorrectInput = false;
}
catch (Exception wrrongLogicInput)
{
Console.WriteLine("Iligale input");
Console.WriteLine(wrrongLogicInput.Message);
}
}
numberOfQuestion++;
isNotCorrectInput = true;
}
}
public void ShowWheelsQuastionsAndCheckAnswear(List<string> i_quastions, Owner_Details io_newOwner) // this function display the wheels questions and checks inputs
{
int numberOfQuestion = 1; // count the number of question
bool isNotCorrectInput = true; // a boolean variable that checks whether the input from the user is correct
string inputFormUser;
foreach (string question in i_quastions) // For each question in the list of questions
{
while (isNotCorrectInput) // while the input isnt correct
{
try
{
isNotCorrectInput = true;
Console.WriteLine(question); // display the question to user
inputFormUser = Console.ReadLine();
io_newOwner.ownerVehicle.UpdateWheels(inputFormUser, numberOfQuestion); // call to function that updeate the wheels details and return an Ex if the input worng
isNotCorrectInput = false;
}
catch (FormatException wrrongLogicInput)
{
Console.WriteLine("Iligale input");
Console.WriteLine(wrrongLogicInput.Message);
}
catch (ArgumentException wrrongLogicInput)
{
Console.WriteLine("Iligale input");
Console.WriteLine(wrrongLogicInput.Message);
}
}
numberOfQuestion++;
isNotCorrectInput = true;
}
}
public void ShowEngineQuastionsAndCheckAnswear(List<string> i_quastions, Owner_Details io_newOwner) // this function display the Engine questions and checks inputs
{
int numberOfQuestion = 1; // count the number of question
bool isNotCorrectInput = true; // a boolean variable that checks whether the input from the user is correct
string inputFormUser;
foreach (string question in i_quastions) // For each question in the list of questions
{
while (isNotCorrectInput) // while the input isnt correct
{
try
{
isNotCorrectInput = true;
Console.WriteLine(question); // display the question to user
inputFormUser = Console.ReadLine();
io_newOwner.ownerVehicle.engine.CheckInputAndUpdateForEngine(inputFormUser, numberOfQuestion); // call to function that updeate the engine details and return an Ex if the input worng
isNotCorrectInput = false;
}
catch (FormatException wrrongLogicInput)
{
Console.WriteLine("Iligale input");
Console.WriteLine(wrrongLogicInput.Message);
}
catch (ArgumentException wrrongLogicInput)
{
Console.WriteLine("Iligale input");
Console.WriteLine(wrrongLogicInput.Message);
}
}
numberOfQuestion++;
isNotCorrectInput = true;
}
}
public void ShowQuastionsForAllVehicleAndCheckAnswear(List<string> i_quastions, Owner_Details io_newOwner) // this function display the All Vehicle questions and checks inputs
{
int numberOfQuestion = 1; // count the number of question
bool isNotCorrectInput = true; // a boolean variable that checks whether the input from the user is correct
string inputFormUser;
foreach (string question in i_quastions) // For each question in the list of questions
{
while (isNotCorrectInput) // while the input isnt correct
{
try
{
isNotCorrectInput = true;
Console.WriteLine(question); // display the question to user
inputFormUser = Console.ReadLine();
io_newOwner.ownerVehicle.CheckInputAndUpdateForAllVehicles(inputFormUser, numberOfQuestion); // send the input to a check function
isNotCorrectInput = false;
}
catch (FormatException wrrongLogicInput)
{
Console.WriteLine("Iligale input");
Console.WriteLine(wrrongLogicInput.Message);
}
catch (ArgumentException wrrongLogicInput)
{
Console.WriteLine("Iligale input");
Console.WriteLine(wrrongLogicInput.Message);
}
}
numberOfQuestion++;
isNotCorrectInput = true;
}
}
public void MainMenu() // this function displays the main menu
{
string inputFromUser;
bool notFinishProg = true;
int inputFromUserInInt; // a Boolean variable that tells if the program is finished
while (notFinishProg) // while the program is not finished
{
Console.Clear();
Console.Write(@"
**** Hello and welcome to David and Sigal's garage :) ****
To insert a vehicle into the garage, please press < 1 >
To view a list of vehicles license numbers in the garage, please press < 2 >
To change the condition of a vehicle in the garage, please press < 3 >
To inflate a vehicle air tires to the maximum, please press < 4 >
To fuel a vehicle that powered by fuel, please press < 5 >
To recharge electric vehicle, please press < 6 >
To view the full data of a vehicle by license number, please press < 7 >
To exit the program, please press < 8 >
");
inputFromUser = Console.ReadLine();
inputFromUserInInt = checkMenuInput(inputFromUser); // call to function that cheeck user input
if (inputFromUserInInt == (int)ekeyBoard.Esc) // if the user want to exit
{
notFinishProg = false;
}
SentToFunctionSwitch(inputFromUserInInt); // call to function that starts what the user has selected
}
}
public int checkMenuInput(string i_inputFromUser) // this function cheeck user input at the main menu and return the input in int
{
int inputFromUser = 0;
bool notCorrectInput = true; // a Boolean variable that tells if the user input is correct
bool successParse; // a Boolean variable that tells if the parss was successful
while (notCorrectInput) // while the user input isnt correct
{
successParse = int.TryParse(i_inputFromUser, out inputFromUser); // try to parss the input to int
if (successParse) // if the parss success
{
if (inputFromUser < 1 || inputFromUser > 8) // check if the user input isnt in range
{
Console.WriteLine("You have to choose a number bettwen 1 - 8");
i_inputFromUser = Console.ReadLine();
}
else
{
notCorrectInput = false;
}
}
else // if the user input isnt a number
{
Console.WriteLine("You have to choose a number bettwen 1 - 8");
i_inputFromUser = Console.ReadLine();
}
}
return inputFromUser;
}
public void SentToFunctionSwitch(int i_inputFromUser) // this function starts what the user has selected in the main menu
{
switch (i_inputFromUser)
{
case (int)ekeyBoard.One: // The user chose option number 1
{
InsertVehicleToGarage(); // call to function that insert a new vehicle to garage
break;
}
case (int)ekeyBoard.Two: // The user chose option number 2
{
ShowListOfVehicles(); // call to function that display the vichels list
break;
}
case (int)ekeyBoard.Three: // The user chose option number 3
{
ChangeVehicleStatus(); // call to function that change vehicle status
break;
}
case (int)ekeyBoard.Four: // The user chose option number 4
{
InflateVehicleAirTiresToTheMaximum(); // call to function that inflate vehicle air tires to the maximum
break;
}
case (int)ekeyBoard.Five: // The user chose option number 5
{
FuelVehicleThatPoweredByFuel(); // call to function that fuel a vehicle that powered by fuel
break;
}
case (int)ekeyBoard.Six: // The user chose option number
{
RechargeElectricVehicle(); // call to function that recharge an electric vehicle
break;
}
case (int)ekeyBoard.Seven: // The user chose option number 7
{
ShowFullDataOfVehicle(); // call to function that show the full data of vehicle
break;
}
case (int)ekeyBoard.Esc: // The user chose option number 8
{
Console.Clear();
Console.WriteLine("GoodBye...");
break;
}
}
}
public void InsertVehicleToGarage() // this function insert a new vehicle to garage
{
string inputLicenseNumberFromUser;
bool isNotCorrectInpt = true; // a Boolean variable that says whether the input from the user is correct
Console.Clear();
while (isNotCorrectInpt) // while the input from the user isnt correct
{
try
{
Console.WriteLine("Please inseart a license number or 'Q' to go back to menu and press 'Enter'");
inputLicenseNumberFromUser = Console.ReadLine();
if (inputLicenseNumberFromUser.CompareTo("Q") != 0) // if the user dont want to exit
{
InsertVehicle(inputLicenseNumberFromUser); // call to function that insert a Vehicle by license number
}
isNotCorrectInpt = false;
}
catch (ArgumentException Ex)
{
Console.WriteLine(Ex.Message);
}
}
}
public void ShowListOfVehicles() // this function display the vichels list
{
string inputFromUser;
bool inputNotCorrect = true; // a Boolean variable that says whether the input from the user is correct
List<string> listOfLicense =null;
Console.Clear();
while (inputNotCorrect) // while the input from the user isnt correct
{
try
{
Console.WriteLine("Please select the sort type to display vehicle license numbers <NONE,INPROCESS,FIXED,PAIDUP> or 'Q' to go back to menu");
inputFromUser = Console.ReadLine();
if (inputFromUser.CompareTo("Q") != 0) // if the user dont want to exit
{
listOfLicense = m_GarageLogic.ShowListOfVehicles(inputFromUser); // call to function that shows the list of vehicles according to the filter the user has selected
}
if(listOfLicense != null) // if the list isnt empty
{
foreach(string license in listOfLicense)
{
Console.WriteLine(license); // Writing the vehicle license
}
}
Console.WriteLine("Press 'enter' to continue");
Console.ReadLine();
inputNotCorrect = false;
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
}
}
}
public void ChangeVehicleStatus() // this function change vehicle status
{
string inputLicenseFromUser;
string inputStatusFromUser;
bool isntCurrectInput = true; // a Boolean variable that says whether the input from the user is correct
Console.Clear();
while (isntCurrectInput) // while the input from the user isnt correct
{
try
{
Console.WriteLine("Please inseart a license number or press 'Q' to return to the main manu");
inputLicenseFromUser = Console.ReadLine();
if (inputLicenseFromUser.CompareTo("Q") != 0) // if the user dont want to exit
{
Console.WriteLine("Please inseart the vehicle status < INPROCESS / FIXED / PAIDUP > and press 'Enter'");
inputStatusFromUser = Console.ReadLine();
m_GarageLogic.ChangeVehicleStatus(inputLicenseFromUser,inputStatusFromUser); // call to function changes the vehicle status by license number and new status from the user
Console.WriteLine("succssed to change status of Vehicle");
Console.WriteLine("Press 'enter' to continue");
Console.ReadLine();
}
isntCurrectInput = false;
}
catch (ArgumentException Ex)
{
Console.WriteLine(Ex.Message);
}
}
}
public void InflateVehicleAirTiresToTheMaximum() // this function inflate vehicle air tires to the maximum
{
string inputFromUser;
bool isntCurrectInput = true; // a Boolean variable that says whether the input from the user is correct
Console.Clear();
while (isntCurrectInput) // while the input from the user isnt correct
{
try
{
Console.WriteLine("Please inseart a license number or press 'Q' to return to the main manu");
inputFromUser = Console.ReadLine();
if (inputFromUser.CompareTo("Q") != 0) // if the user dont want to exit
{
m_GarageLogic.InflateVehicleAirTiresToTheMaximum(inputFromUser); // call to function that inflating tires to the maximum by number of vehicles
Console.WriteLine("succssed to inflate vehicle air tires to max");
Console.WriteLine("Press 'enter' to continue");
Console.ReadLine();
}
isntCurrectInput = false;
}
catch (ArgumentException Ex)
{
Console.WriteLine(Ex.Message);
}
}
}
public void FuelVehicleThatPoweredByFuel() // this function fuel a vehicle that powered by fuel
{
bool isntCurrectInput = true; // a Boolean variable that says whether the input from the user is correct
string inputLicenseFromUser;
string fualTypeFromUser;
string quantityToFillFromUser;
Console.Clear();
while (isntCurrectInput) // while the input from the user isnt correct
{
try
{
Console.WriteLine("Please inseart a license number or press 'Q' to return to the main manu");
inputLicenseFromUser = Console.ReadLine();
if (inputLicenseFromUser.CompareTo("Q") != 0) // if the user dont want to exit
{
Console.WriteLine("Please inseart a fual type { SOLER, OCTAN95, OCTAN96, OCTAN98 } and press 'Enter'");
fualTypeFromUser = Console.ReadLine();
Console.WriteLine("Please enter a quantity to fill in and press 'Enter'");
quantityToFillFromUser = Console.ReadLine();
m_GarageLogic.FuelVehicleThatPoweredByFuel(inputLicenseFromUser, fualTypeFromUser, quantityToFillFromUser); // call to function that fual the vehicle and return Ex if inputs worngs
Console.WriteLine("fuel was successeful ");
Console.WriteLine("Press 'enter' to continue");
Console.ReadLine();
isntCurrectInput = false;
}
isntCurrectInput = false;
}
catch (ValueOutOfRangeException Ex)
{
Console.WriteLine(Ex.Message);
}
catch (ArgumentException Ex)
{
Console.WriteLine(Ex.Message);
}
}
}
public void RechargeElectricVehicle() // this function recharge an electric vehicle
{
bool isntCurrectInput = true; // a Boolean variable that says whether the input from the user is correct
string inputLicenseFromUser;
string quantityToFillFromUser;
Console.Clear();
while (isntCurrectInput) // while the input from the user isnt correct
{
try
{
Console.WriteLine("Please inseart a license number or press 'Q' to return to the main manu");
inputLicenseFromUser = Console.ReadLine();
if (inputLicenseFromUser.CompareTo("Q") != 0) // if the user dont want to exit
{
Console.WriteLine("Please enter a quantity to fill in and press 'Enter'");
quantityToFillFromUser = Console.ReadLine();
m_GarageLogic.RechargeElectricVehicle(inputLicenseFromUser, quantityToFillFromUser); // call to function that charge the vehicle and return Ex if inputs worngs
Console.WriteLine("fuel was successeful ");
Console.WriteLine("Press 'enter' to continue");
Console.ReadLine();
}
isntCurrectInput = false;
}
catch (ValueOutOfRangeException Ex)
{
Console.WriteLine(Ex.Message);
}
catch (ArgumentException Ex)
{
Console.WriteLine(Ex.Message);
}
}
}
public void ShowFullDataOfVehicle() // this function show the full data of vehicle
{
List<string> AllDetailsToPrint = null;
bool isntCurrectInput = true; // a Boolean variable that says whether the input from the user is correct
string inputLicenseFromUser;
Console.Clear();
while (isntCurrectInput) // while the input from the user isnt correct
{
try
{
Console.WriteLine("Please inseart a license number or press 'Q' to return to the main manu");
inputLicenseFromUser = Console.ReadLine();
if (inputLicenseFromUser.CompareTo("Q") != 0) // if the user dont want to exit
{
AllDetailsToPrint = m_GarageLogic.ShowFullDataOfVehicle(inputLicenseFromUser); // call to function that return the list of data
}
if (AllDetailsToPrint != null) // if the list isnt empty
{
foreach (string detaile in AllDetailsToPrint) // for each data in the list
{
Console.WriteLine(detaile); // output the data
}
}
isntCurrectInput = false;
Console.WriteLine("Press 'Enter' to continue");
Console.ReadLine();
}
catch (ArgumentException Ex)
{
Console.WriteLine(Ex.Message);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Globalization;
using System.IO;
using System.Reflection;
using Phenix.Core;
using Phenix.Core.Data;
using Phenix.Core.IO;
using Phenix.Core.Log;
using Phenix.Core.Mapping;
using Phenix.Core.Security;
using Phenix.Services.Host.Core;
namespace Phenix.Services.Host.Service
{
public sealed class Data : MarshalByRefObject, IData
{
#region 事件
//internal static event Action<DataSecurityEventArgs> DataSecurityChanged;
//private static void OnDataSecurityChanged(DataSecurityEventArgs e)
//{
// Action<DataSecurityEventArgs> action = DataSecurityChanged;
// if (action != null)
// action(e);
//}
#endregion
#region 属性
#region IData 成员
#region Sequence
public long SequenceValue
{
get
{
ServiceManager.CheckActive();
return DataHub.SequenceValue;
}
}
#endregion
#endregion
#endregion
#region 方法
#region Sequence
public long[] GetSequenceValues(int count)
{
ServiceManager.CheckActive();
return DataHub.GetSequenceValues(count);
}
#endregion
#region Schema
public string GetTablesContent(string dataSourceKey, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DataHub.GetTablesContent(dataSourceKey, context.Identity);
}
public string GetTableColumnsContent(string dataSourceKey, string tableName, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DataHub.GetTableColumnsContent(dataSourceKey, tableName, context.Identity);
}
public string GetTablePrimaryKeysContent(string dataSourceKey, string tableName, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DataHub.GetTablePrimaryKeysContent(dataSourceKey, tableName, context.Identity);
}
public string GetTableForeignKeysContent(string dataSourceKey, string tableName, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DataHub.GetTableForeignKeysContent(dataSourceKey, tableName, context.Identity);
}
public string GetTableDetailForeignKeysContent(string dataSourceKey, string tableName, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DataHub.GetTableDetailForeignKeysContent(dataSourceKey, tableName, context.Identity);
}
public string GetTableIndexesContent(string dataSourceKey, string tableName, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DataHub.GetTableIndexesContent(dataSourceKey, tableName, context.Identity);
}
public string GetViewsContent(string dataSourceKey, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DataHub.GetViewsContent(dataSourceKey, context.Identity);
}
public string GetViewColumnsContent(string dataSourceKey, string viewName, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DataHub.GetViewColumnsContent(dataSourceKey, viewName, context.Identity);
}
#endregion
#region Execute
public IService Execute(IService service, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(service.GetType(), ExecuteAction.Update, identity);
DateTime dt = DateTime.Now;
IService result = DataHub.Execute(service, context.Identity);
//OnDataSecurityChanged(new DataSecurityEventArgs(identity.Name));
//跟踪日志
if (AppConfig.Debugging)
PerformanceAnalyse.Default.CheckSaveMaxElapsedTime(service.GetType().FullName, DateTime.Now.Subtract(dt).TotalSeconds, -1, context.Identity);
return result;
}
public IService UploadFiles(IService service, IDictionary<string, Stream> fileStreams, UserIdentity identity)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public IService UploadFiles(IService service, IDictionary<string, byte[]> fileByteses, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(service.GetType(), ExecuteAction.Update, identity);
DateTime dt = DateTime.Now;
IService result = DataHub.UploadFiles(service, fileByteses, context.Identity);
//OnDataSecurityChanged(new DataSecurityEventArgs(identity.Name));
//跟踪日志
if (AppConfig.Debugging)
PerformanceAnalyse.Default.CheckSaveMaxElapsedTime(service.GetType().FullName, DateTime.Now.Subtract(dt).TotalSeconds, -1, context.Identity);
return result;
}
public IService UploadBigFile(IService service, FileChunkInfo fileChunkInfo, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(service.GetType(), ExecuteAction.Update, identity);
DateTime dt = DateTime.Now;
IService result = DataHub.UploadBigFile(service, fileChunkInfo, context.Identity);
//OnDataSecurityChanged(new DataSecurityEventArgs(identity.Name));
//跟踪日志
if (AppConfig.Debugging)
PerformanceAnalyse.Default.CheckSaveMaxElapsedTime(service.GetType().FullName, DateTime.Now.Subtract(dt).TotalSeconds, -1, context.Identity);
return result;
}
public Stream DownloadFile(IService service, UserIdentity identity)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public byte[] DownloadFileBytes(IService service, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(service.GetType(), ExecuteAction.Update, identity);
DateTime dt = DateTime.Now;
byte[] result = DataHub.DownloadFileBytes(service, context.Identity);
//OnDataSecurityChanged(new DataSecurityEventArgs(identity.Name));
//跟踪日志
if (AppConfig.Debugging)
PerformanceAnalyse.Default.CheckSaveMaxElapsedTime(service.GetType().FullName, DateTime.Now.Subtract(dt).TotalSeconds, -1, context.Identity);
return result;
}
public FileChunkInfo DownloadBigFile(IService service, int chunkNumber, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(service.GetType(), ExecuteAction.Update, identity);
DateTime dt = DateTime.Now;
FileChunkInfo result = DataHub.DownloadBigFile(service, chunkNumber, context.Identity);
//OnDataSecurityChanged(new DataSecurityEventArgs(identity.Name));
//跟踪日志
if (AppConfig.Debugging)
PerformanceAnalyse.Default.CheckSaveMaxElapsedTime(service.GetType().FullName, DateTime.Now.Subtract(dt).TotalSeconds, -1, context.Identity);
return result;
}
#endregion
#region Fetch
public object Fetch(ICriterions criterions, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(criterions.ResultType, ExecuteAction.Fetch, identity);
DateTime dt = DateTime.Now;
object result = DataHub.Fetch(criterions, context.Identity);
//OnDataSecurityChanged(new DataSecurityEventArgs(identity.Name));
//跟踪日志
if (AppConfig.Debugging)
{
int count = result != null ? 1 : 0;
EventLog.SaveLocal(MethodBase.GetCurrentMethod().Name + ' ' + criterions.ResultType.FullName +
(criterions.Criteria != null ? " with " + criterions.Criteria.GetType().FullName : String.Empty) +
" take " + DateTime.Now.Subtract(dt).TotalMilliseconds.ToString(CultureInfo.InvariantCulture) + " millisecond," +
" count = " + count);
PerformanceAnalyse.Default.CheckFetchMaxCount(criterions.ResultType.FullName, count, context.Identity);
PerformanceAnalyse.Default.CheckFetchMaxElapsedTime(criterions.ResultType.FullName, DateTime.Now.Subtract(dt).TotalSeconds, count, context.Identity);
}
return result;
}
public IList<object> FetchList(ICriterions criterions, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(criterions.ResultType, ExecuteAction.Fetch, identity);
DateTime dt = DateTime.Now;
IList<object> result = DataHub.FetchList(criterions, context.Identity);
//OnDataSecurityChanged(new DataSecurityEventArgs(identity.Name));
//跟踪日志
if (AppConfig.Debugging)
{
int count = result != null ? result.Count : 0;
EventLog.SaveLocal(MethodBase.GetCurrentMethod().Name + ' ' + criterions.ResultType.FullName +
(criterions.Criteria != null ? " with " + criterions.Criteria.GetType().FullName : String.Empty) +
" take " + DateTime.Now.Subtract(dt).TotalMilliseconds.ToString(CultureInfo.InvariantCulture) + " millisecond," +
" count = " + count);
PerformanceAnalyse.Default.CheckFetchMaxCount(criterions.ResultType.FullName, count, context.Identity);
PerformanceAnalyse.Default.CheckFetchMaxElapsedTime(criterions.ResultType.FullName, DateTime.Now.Subtract(dt).TotalSeconds, count, context.Identity);
}
return result;
}
public string FetchContent(ICriterions criterions, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(criterions.ResultType, ExecuteAction.Fetch, identity);
DateTime dt = DateTime.Now;
string result = DataHub.FetchContent(criterions, context.Identity);
//OnDataSecurityChanged(new DataSecurityEventArgs(identity.Name));
//跟踪日志
if (AppConfig.Debugging)
{
int length = result != null ? result.Length : 0;
EventLog.SaveLocal(MethodBase.GetCurrentMethod().Name + ' ' + criterions.ResultType.FullName +
(criterions.Criteria != null ? " with " + criterions.Criteria.GetType().FullName : String.Empty) +
" take " + DateTime.Now.Subtract(dt).TotalMilliseconds.ToString(CultureInfo.InvariantCulture) + " millisecond," +
" length = " + length);
PerformanceAnalyse.Default.CheckFetchMaxCount(criterions.ResultType.FullName, length, context.Identity);
PerformanceAnalyse.Default.CheckFetchMaxElapsedTime(criterions.ResultType.FullName, DateTime.Now.Subtract(dt).TotalSeconds, length, context.Identity);
}
return result;
}
#endregion
#region Save
public bool Save(IEntity entity, bool needCheckDirty, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(entity.GetType(), ExecuteAction.Update, identity);
DateTime dt = DateTime.Now;
bool result = DataHub.Save(entity, needCheckDirty, context.Identity);
//OnDataSecurityChanged(new DataSecurityEventArgs(identity.Name));
//跟踪日志
if (AppConfig.Debugging)
PerformanceAnalyse.Default.CheckSaveMaxElapsedTime(entity.GetType().FullName, DateTime.Now.Subtract(dt).TotalSeconds, result ? 1 : 0, context.Identity);
return result;
}
public int Save(IEntityCollection entityCollection, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(entityCollection.GetType(), ExecuteAction.Update, identity);
DateTime dt = DateTime.Now;
int result = DataHub.Save(entityCollection, context.Identity);
//OnDataSecurityChanged(new DataSecurityEventArgs(identity.Name));
//跟踪日志
if (AppConfig.Debugging)
PerformanceAnalyse.Default.CheckSaveMaxElapsedTime(entityCollection.GetType().FullName, DateTime.Now.Subtract(dt).TotalSeconds, entityCollection.Count, context.Identity);
return result;
}
public int SaveContent(string objectTypeName, string source, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(Type.GetType(objectTypeName), ExecuteAction.Update, identity);
DateTime dt = DateTime.Now;
int result = DataHub.SaveContent(objectTypeName, source, identity);
//OnDataSecurityChanged(new DataSecurityEventArgs(identity.Name));
//跟踪日志
if (AppConfig.Debugging)
PerformanceAnalyse.Default.CheckSaveMaxElapsedTime(objectTypeName, DateTime.Now.Subtract(dt).TotalSeconds, result, context.Identity);
return result;
}
#endregion
#region Insert
public bool Insert(object obj, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(obj.GetType(), ExecuteAction.Insert, identity);
return DataHub.Insert(obj, context.Identity);
}
public int InsertList(IList<IEntity> entities, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(entities.GetType(), ExecuteAction.Insert, identity);
return DataHub.InsertList(entities, context.Identity);
}
#endregion
#region Update
public bool Update(object obj, IList<FieldValue> oldFieldValues, bool needCheckDirty, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(obj.GetType(), ExecuteAction.Update, identity);
return DataHub.Update(obj, oldFieldValues, needCheckDirty, context.Identity);
}
public int UpdateList(IList<IEntity> entities, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(entities.GetType(), ExecuteAction.Update, identity);
return DataHub.UpdateList(entities, context.Identity);
}
#endregion
#region Delete
public bool Delete(object obj, IList<FieldValue> oldFieldValues, bool needCheckDirty, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(obj.GetType(), ExecuteAction.Delete, identity);
return DataHub.Delete(obj, oldFieldValues, needCheckDirty, context.Identity);
}
public int DeleteList(IList<IEntity> entities, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(entities.GetType(), ExecuteAction.Delete, identity);
return DataHub.DeleteList(entities, context.Identity);
}
#endregion
#region UpdateRecord
public int UpdateRecord(ICriterions criterions, IDictionary<string, object> data, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(criterions.ResultType, ExecuteAction.Update, identity);
return DataHub.UpdateRecord(criterions, data, context.Identity);
}
#endregion
#region DeleteRecord
public int DeleteRecord(ICriterions criterions, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(criterions.ResultType, ExecuteAction.Delete, identity);
return DataHub.DeleteRecord(criterions, context.Identity);
}
#endregion
#region RecordCount
public long GetRecordCount(ICriterions criterions, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(criterions.ResultType, ExecuteAction.Fetch, identity);
return DataHub.GetRecordCount(criterions, context.Identity);
}
#endregion
#region CheckRepeated
public bool CheckRepeated(IEntity entity, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DataHub.CheckRepeated(entity, context.Identity);
}
public IList<IEntity> CheckRepeated(string rootTypeName, IList<IEntity> entities, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DataHub.CheckRepeated(rootTypeName, entities, context.Identity);
}
#endregion
#region BusinessCode
public long GetBusinessCodeSerial(string key, long initialValue, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DataHub.GetBusinessCodeSerial(key, initialValue, context.Identity);
}
public long[] GetBusinessCodeSerials(string key, long initialValue, int count, UserIdentity identity)
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DataHub.GetBusinessCodeSerials(key, initialValue, count, context.Identity);
}
#endregion
#region 应用服务不支持传事务
public object Fetch(DbConnection connection, ICriterions criterions)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public object Fetch(DbTransaction transaction, ICriterions criterions)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public IList<object> FetchList(DbConnection connection, ICriterions criterions)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public IList<object> FetchList(DbTransaction transaction, ICriterions criterions)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public bool Save(DbConnection connection, IEntity entity, bool needCheckDirty)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public bool Save(DbTransaction transaction, IEntity entity, bool needCheckDirty)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public int Save(DbConnection connection, IEntityCollection entityCollection)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public int Save(DbTransaction transaction, IEntityCollection entityCollection)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public bool Insert(DbConnection connection, object obj)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public bool Insert(DbTransaction transaction, object obj)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public int InsertList(DbConnection connection, IList<IEntity> entities)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public int InsertList(DbTransaction transaction, IList<IEntity> entities)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public bool Update(DbConnection connection, object obj, IList<FieldValue> oldFieldValues, bool needCheckDirty)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public bool Update(DbTransaction transaction, object obj, IList<FieldValue> oldFieldValues, bool needCheckDirty)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public int UpdateList(DbConnection connection, IList<IEntity> entities)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public int UpdateList(DbTransaction transaction, IList<IEntity> entities)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public bool Delete(DbConnection connection, object obj, IList<FieldValue> oldFieldValues, bool needCheckDirty)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public bool Delete(DbTransaction transaction, object obj, IList<FieldValue> oldFieldValues, bool needCheckDirty)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public int DeleteList(DbConnection connection, IList<IEntity> entities)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public int DeleteList(DbTransaction transaction, IList<IEntity> entities)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public int UpdateRecord(DbConnection connection, ICriterions criterions, IDictionary<string, object> data)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public int UpdateRecord(DbTransaction transaction, ICriterions criterions, IDictionary<string, object> data)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public int DeleteRecord(DbConnection connection, ICriterions criterions)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public int DeleteRecord(DbTransaction transaction, ICriterions criterions)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public long GetRecordCount(DbConnection connection, ICriterions criterions)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public long GetRecordCount(DbTransaction transaction, ICriterions criterions)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public long GetBusinessCodeSerial(DbConnection connection, string key, long initialValue)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
public long[] GetBusinessCodeSerials(DbConnection connection, string key, long initialValue, int count)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
#endregion
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApp
{
public class MyActionFilter : ActionFilterAttribute
{
void OnAcyionExecuted(ActionExecutedContext filteContext)
{
var controllerName = filteContext.Controller
.ControllerContext
.RequestContext
.RouteData
.Values
.First()
.Value;
List<string> headers = null;
}
}
} |
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 CourseWork
{
public partial class Form8 : Form
{
public Form8()
{
InitializeComponent();
}
public bool checkCorrect()
{
var From = textBox2.Text;
var To = textBox1.Text;
try
{
if (!From.Contains(".")) return false;
string[] s = From.Split('.');
if (s.Length != 3) return false;
if (int.Parse(s[0]) < 1 || int.Parse(s[0]) > 31 || int.Parse(s[1]) < 0 || int.Parse(s[1]) > 12 || int.Parse(s[2]) < 2007 || int.Parse(s[2]) > 2030)
{
return false;
}
if (!To.Contains(".")) return false;
string[] s1 = To.Split('.');
if (s.Length != 3) return false;
if (int.Parse(s1[0]) < 1 || int.Parse(s1[0]) > 31 || int.Parse(s1[1]) < 0 || int.Parse(s1[1]) > 12 || int.Parse(s1[2]) < 2007 || int.Parse(s1[2]) > 2030)
{
return false;
}
return true;
}
catch (Exception)
{
MessageBox.Show("Ошибка ввода!");
return false;
}
}
public DateKey Max() {
var To = textBox1.Text;
string[] s = To.Split('.');
return new DateKey(int.Parse(s[0]), int.Parse(s[1]), int.Parse(s[2]));
}
public DateKey Min() {
var From = textBox2.Text;
string[] s = From.Split('.');
return new DateKey(int.Parse(s[0]), int.Parse(s[1]), int.Parse(s[2]));
}
private void button1_Click(object sender, EventArgs e)
{
if (checkCorrect())
{
DialogResult = DialogResult.OK;
Hide();
}
else MessageBox.Show("Ошибка ввода!");
}
}
}
|
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
/*
[System.Serializable]
public class CustomEvent : UnityEvent<GameObject>
{
}
*/
public class SideChain : MonoBehaviour {
public int lfoHigh = 510;
public int lfoLow = 10;
public int rate = 4;
public Spectrum spectrum;
private AudioSource clip;
private AudioLowPassFilter lowpass;
//private AudioEchoFilter delay;
private float angle;
public float minAngle = -90f;
public float maxAngle = 90f;
public float rotateSensitivity = 1f;
private float output;
private float mouseShit = 0f;
//public CustomEvent event_;
//public UnityEvent myEvent;
Coroutine PumpFrequencyCoroutine = null;
Coroutine DropFrequencyCoroutine = null;
void Start() {
clip = gameObject.GetComponent<AudioSource> ();
lowpass = gameObject.GetComponent<AudioLowPassFilter> ();
//delay = gameObject.GetComponent<AudioEchoFilter> ();
lowpass.cutoffFrequency = lfoLow;
angle = 0f;
PumpFrequencyCoroutine = StartCoroutine (PumpFrequency());
}
void Update () {
clip.volume = spectrum.compression;
//Debug.Log ("PP " + PumpFrequencyCoroutine);
angle += mouseShit * -rotateSensitivity;
transform.RotateAround (transform.position, transform.up, angle);
float rawAngle = transform.localEulerAngles.y;
rawAngle = (rawAngle > 180) ? rawAngle - 360 : rawAngle;
output = rawAngle / 180f;
// Debug.Log (output);
//
//transform.eulerAngles = Vector3.Lerp (transform.eulerAngles, new Vector3 (0f, angle, 0f), Time.deltaTime * lerpSpeed);
}
/*public void DoEvent(GameObject go)
{
Debug.Log (go.name);
}*/
public float GetRotationOutputNormalized()
{
return output;
}
void OnMouseDown(){
//myEvent.Invoke ();
StopAllCoroutines();
lowpass.cutoffFrequency = 10;
StartCoroutine (PumpFrequency ());
if (Input.GetMouseButton (0)) {
mouseShit = Input.GetAxis ("Mouse X");
}
}
IEnumerator PumpFrequency()
{
while (lowpass.cutoffFrequency < lfoHigh) {
lowpass.cutoffFrequency += ((lfoHigh / rate) * (Time.deltaTime) * 4);
yield return null;
}
StartCoroutine (DropFrequency ());
}
IEnumerator DropFrequency()
{
while (lowpass.cutoffFrequency > lfoLow) {
var newValue = lowpass.cutoffFrequency - ((lfoHigh / rate) * (Time.deltaTime) * 4);
if (newValue < lfoLow)
newValue = lfoLow;
lowpass.cutoffFrequency = newValue;
yield return null;
}
StartCoroutine (PumpFrequency ());
}
}
|
namespace Alabo.Cloud.People.Identities
{
public class IdentityApiResult
{
/// <summary>
/// 状态
/// </summary>
public string Status { get; set; }
/// <summary>
/// 认证结果消息
/// </summary>
public string Message { get; set; }
}
} |
namespace gView.MapServer
{
public class InterpreterCapabilities
{
public InterpreterCapabilities(Capability[] capabilites)
{
Capabilities = capabilites;
}
public Capability[] Capabilities
{
get;
private set;
}
#region Classes
public enum Method { Get = 0, Post = 1 };
public class Capability
{
public Capability(string name)
: this(name, Method.Get, "1.0")
{
}
public Capability(string name, Method method, string version)
{
Name = name;
Method = method;
Version = version;
}
public string Name { get; private set; }
public Method Method { get; private set; }
public string Version { get; private set; }
public string RequestText { get; protected set; }
}
public class SimpleCapability : Capability
{
public SimpleCapability(string name, string link, string version)
: this(name, Method.Get, link, version)
{
}
public SimpleCapability(string name, Method method, string requestText, string version)
: base(name, method, version)
{
base.RequestText = requestText;
}
}
public class LinkCapability : Capability
{
public LinkCapability(string name, string requestLink, string version)
: this(name, Method.Get, requestLink, version)
{
}
public LinkCapability(string name, Method method, string requestLink, string version)
: base(name, method, version)
{
base.RequestText = requestLink;
}
}
#endregion
}
}
|
using NRaas.CommonSpace.Helpers;
using NRaas.CommonSpace.Scoring;
using NRaas.CommonSpace.ScoringMethods;
using NRaas.StoryProgressionSpace.Managers;
using NRaas.StoryProgressionSpace.Options;
using NRaas.StoryProgressionSpace.Personalities;
using NRaas.StoryProgressionSpace.Scenarios;
using NRaas.StoryProgressionSpace.Scenarios.Sims;
using Sims3.Gameplay.Abstracts;
using Sims3.Gameplay.Actors;
using Sims3.Gameplay.ActorSystems;
using Sims3.Gameplay.Autonomy;
using Sims3.Gameplay.Careers;
using Sims3.Gameplay.CAS;
using Sims3.Gameplay.Core;
using Sims3.Gameplay.Interactions;
using Sims3.Gameplay.Interfaces;
using Sims3.Gameplay.MapTags;
using Sims3.Gameplay.Objects.Vehicles;
using Sims3.Gameplay.Roles;
using Sims3.Gameplay.Socializing;
using Sims3.Gameplay.Utilities;
using Sims3.SimIFace;
using Sims3.SimIFace.CAS;
using Sims3.UI;
using System;
using System.Collections.Generic;
namespace NRaas.StoryProgressionSpace.MapTags
{
public class TrackedSim : MapTag
{
ulong mCount = 0;
private static CommodityKind[] sMotives = new CommodityKind[]
{
CommodityKind.Hunger,
CommodityKind.Energy,
CommodityKind.Bladder,
CommodityKind.Hygiene,
CommodityKind.Fun,
CommodityKind.Social
};
public TrackedSim(Sim targetsim, Sim owner)
: base(targetsim, owner)
{}
public override void ClickedOn(UIMouseEventArgs eventArgs)
{
Sim target = this.Target as Sim;
if (((target == null) || (target.Household == null)) || (target.Household.LotHome == null))
{
target = null;
}
if ((target != null) &&
(eventArgs.MouseKey == MouseKeys.kMouseRight) &&
(eventArgs.Modifiers == (Modifiers.kModifierMaskNone | Modifiers.kModifierMaskControl)))
{
PlumbBob.ForceSelectActor(target);
}
else
{
base.ClickedOn(eventArgs);
}
}
public override float RelationshipLevel
{
get
{
try
{
using (Common.TestSpan span = new Common.TestSpan(NRaas.StoryProgression.Main.Scenarios, "TrackedSim RelationshipLevel"))
{
Sim target = Target as Sim;
if ((target == null) || (target.HasBeenDestroyed))
{
return base.RelationshipLevel;
}
Relationship relationship = Owner.GetRelationship(target, false);
if (relationship != null)
{
return relationship.LTR.Liking;
}
}
}
catch (Exception e)
{
Common.Exception(Sim.ActiveActor, Target, e);
}
return 0f;
}
}
public override bool ShowHotSpotGlow
{
get
{
using (Common.TestSpan span = new Common.TestSpan(NRaas.StoryProgression.Main.Scenarios, "TrackedSim ShowHotSpotGlow"))
{
if (NRaas.StoryProgression.Main.GetValue<Scenarios.Sims.HandleMapTagsScenario.PersonalityTagOption, bool>())
{
Sim target = Target as Sim;
if (NRaas.StoryProgression.Main.Personalities.GetClanLeadership(target.SimDescription).Count > 0)
{
return true;
}
}
return base.ShowHotSpotGlow;
}
}
}
public override MapTagType TagType
{
get
{
try
{
if (mCount < HandleMapTagsScenario.sCount)
{
using (Common.TestSpan span = new Common.TestSpan(NRaas.StoryProgression.Main.Scenarios, "TrackedSim TagType"))
{
mCount = HandleMapTagsScenario.sCount;
mType = MapTagType.NPCSim;
Sim target = Target as Sim;
if ((target != null) && (!target.HasBeenDestroyed))
{
Sim active = Sims3.Gameplay.Actors.Sim.ActiveActor;
if ((target.SimDescription != null) && (active != null))
{
if (target.Household == Household.ActiveHousehold)
{
if (target == active)
{
mType = MapTagType.SelectedSim;
}
else
{
mType = MapTagType.FamilySim;
}
}
else if ((target.LotHome == null) && (target.SimDescription.AssignedRole is Proprietor))
{
mType = MapTagType.Proprietor;
}
else if ((target.SimDescription.IsCelebrity) && (target.SimDescription.CelebrityLevel > 3))
{
mType = MapTagType.Celebrity;
}
else if (active.OccultManager != null)
{
OccultVampire vampire = active.OccultManager.GetOccultType(Sims3.UI.Hud.OccultTypes.Vampire) as OccultVampire;
if ((vampire != null) && (vampire.PreyMapTag != null))
{
if (target == vampire.PreyMapTag.Target)
{
mType = MapTagType.VampirePrey;
}
}
}
}
}
}
}
}
catch (Exception e)
{
Common.Exception(Sim.ActiveActor, Target, e);
}
return mType;
}
}
public override string HoverText
{
get
{
string str = null;
try
{
Sim target = Target as Sim;
return StoryProgression.Main.Sims.GetStatus(target.SimDescription);
}
catch (Exception exception)
{
Common.Exception(Target, exception);
}
return str;
}
}
public override string Hours
{
get
{
try
{
Sim target = Target as Sim;
if (target != null)
{
string hours = ManagerSim.GetRoleHours(target.SimDescription);
if (!string.IsNullOrEmpty(hours))
{
return hours;
}
}
return base.Hours;
}
catch (Exception e)
{
Common.Exception(Target, e);
return null;
}
}
}
public override string HouseholdName
{
get
{
try
{
Sim target = Target as Sim;
if (target != null)
{
if (target.SimDescription.AssignedRole is Proprietor)
{
GameObject roleGivingObject = target.SimDescription.AssignedRole.RoleGivingObject as GameObject;
if ((roleGivingObject != null) && (roleGivingObject.LotCurrent != null))
{
return Common.LocalizeEAString(false, "Gameplay/MapTags/MapTag:LotNameWithProprietor", new object[] { target, roleGivingObject.LotCurrent.Name });
}
}
else if ((target.Household != null) && (!SimTypes.IsSpecial(target.Household)))
{
return target.Household.Name;
}
}
}
catch (Exception e)
{
Common.Exception(Target, e);
}
return string.Empty;
}
}
public override string LotName
{
get
{
try
{
Sim target = Target as Sim;
if (target != null)
{
GameObject roleGivingObject = target.SimDescription.AssignedRole.RoleGivingObject as GameObject;
if (roleGivingObject != null)
{
string str = string.Empty;
switch (roleGivingObject.LotCurrent.CommercialLotSubType)
{
case CommercialLotSubType.kSmallPark:
case CommercialLotSubType.kBigPark:
return Common.LocalizeEAString("Gameplay/Excel/Venues/CommuntiyTypes:BigPark");
case CommercialLotSubType.kEP6_Bistro:
return Common.LocalizeEAString("Gameplay/Excel/Venues/CommuntiyTypes:kEP6_Bistro");
case CommercialLotSubType.kEP6_PerformanceClub:
return Common.LocalizeEAString("Gameplay/Excel/Venues/CommuntiyTypes:kEP6_PerformanceClub");
case CommercialLotSubType.kEP6_PrivateVenue:
return Common.LocalizeEAString("Gameplay/Excel/Venues/CommuntiyTypes:kEP6_PrivateVenue");
case CommercialLotSubType.kEP6_BigShow:
return Common.LocalizeEAString("Gameplay/Excel/Venues/CommuntiyTypes:kEP6_BigShow");
}
return str;
}
}
}
catch (Exception e)
{
Common.Exception(Target, e);
}
return string.Empty;
}
}
public override Color ShadeColor
{
get
{
try
{
using (Common.TestSpan span = new Common.TestSpan(NRaas.StoryProgression.Main.Scenarios, "TrackedSim ShadeColor"))
{
Sim target = Target as Sim;
if ((target == null) || (Sim.ActiveActor == null) || (target == Sim.ActiveActor))
{
return base.ShadeColor;
}
if (Sim.ActiveActor.Household == target.Household)
{
return base.ShadeColor;
}
if (target.SimDescription.AssignedRole is RoleSpecialMerchant)
{
return new Color(0, 0, 0);
}
else if (target.SimDescription.AssignedRole is Proprietor)
{
return new Color(0, 0, 0);
}
if (StoryProgression.Main.GetValue<HandleMapTagsScenario.ColorOption, bool>())
{
if (StoryProgression.Main.GetValue<HandleMapTagsScenario.ColorByAgeOption, bool>())
{
switch (target.SimDescription.Age)
{
case CASAgeGenderFlags.Baby:
// White
return new Color(255, 255, 255);
case CASAgeGenderFlags.Toddler:
// Orange
return new Color(255, 128, 0);
case CASAgeGenderFlags.Teen:
// Red
return new Color(255, 0, 0);
case CASAgeGenderFlags.YoungAdult:
// Yellow
return new Color(255, 255, 0);
case CASAgeGenderFlags.Adult:
// Cyan
return new Color(0, 255, 255);
case CASAgeGenderFlags.Elder:
// Purple
return new Color(128, 0, 255);
}
}
else
{
if (Relationships.IsCloselyRelated(Sim.ActiveActor.SimDescription, target.SimDescription, false))
{
// Cyan
return new Color(0, 255, 255);
}
Relationship relation = Relationship.Get(Sim.ActiveActor, target, false);
if (relation == null)
{
// White
return new Color(255, 255, 255);
}
else if (relation.AreRomantic())
{
// Pink
return new Color(255, 128, 255);
}
else if (ManagerCareer.IsCoworkerOrBoss(Sim.ActiveActor.Occupation, target.SimDescription))
{
// Purple
return new Color(128, 0, 255);
}
else if (relation.LTR.Liking <= (int)SimScenarioFilter.RelationshipLevel.Disliked)
{
// Red
return new Color(255, 0, 0);
}
else if (relation.LTR.Liking >= (int)SimScenarioFilter.RelationshipLevel.Friend)
{
// Orange
return new Color(255, 128, 0);
}
else if (relation.LTR.Liking != 0)
{
// Yellow
return new Color(255, 255, 0);
}
else if (ManagerCareer.IsCoworkerOrBoss(Sim.ActiveActor.School, target.SimDescription))
{
// Purple
return new Color(128, 0, 255);
}
}
}
return base.ShadeColor;
}
}
catch (Exception exception)
{
Common.Exception(Target, exception);
}
// White
return new Color(255, 255, 255);
}
}
public override MapTagFilterType FilterType
{
get
{
try
{
using (Common.TestSpan span = new Common.TestSpan(NRaas.StoryProgression.Main.Scenarios, "TrackedSim FilterType"))
{
Sim target = Target as Sim;
if ((target == null) || (target.SimDescription == null) || (target.HasBeenDestroyed))
{
return MapTagFilterType.None;
}
if (Sim.ActiveActor == null)
{
return MapTagFilterType.None;
}
if (target == Sim.ActiveActor)
{
return ~MapTagFilterType.None;
}
MapTagFilterType result = MapTagFilterType.PublicSpacesAndActivities;
Relationship relation = Relationship.Get(Sim.ActiveActor, target, false);
if (relation != null)
{
if (relation.AreFriends())
{
result |= MapTagFilterType.FriendsHomes;
}
}
if (target.SimDescription.AssignedRole is Proprietor)
{
GameObject roleGivingObject = target.SimDescription.AssignedRole.RoleGivingObject as GameObject;
if (((roleGivingObject != null) && (roleGivingObject.LotCurrent != null)) && Occupation.IsLotAPerformanceCareerLocation(roleGivingObject.LotCurrent))
{
result |= MapTagFilterType.OpportunitiesAndJobs;
}
}
if (Sim.ActiveActor.Household == target.Household)
{
result |= MapTagFilterType.HouseholdAndWork;
}
if (ManagerCareer.IsCoworkerOrBoss(Sim.ActiveActor.Occupation, target.SimDescription))
{
result |= MapTagFilterType.HouseholdAndWork;
result |= MapTagFilterType.Work;
}
if (ManagerCareer.IsCoworkerOrBoss(Sim.ActiveActor.School, target.SimDescription))
{
result |= MapTagFilterType.HouseholdAndWork;
result |= MapTagFilterType.Work;
}
return result;
}
}
catch (Exception exception)
{
Common.Exception(Target, exception);
return MapTagFilterType.None;
}
}
}
public override bool IsSimInRabbithole
{
get
{
if (MapTagManager.ActiveMapTagManager == null)
{
return false;
}
Sim target = Target as Sim;
return ((target.RabbitHoleCurrent != null) && MapTagManager.ActiveMapTagManager.HasTag(target.RabbitHoleCurrent));
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
using ShopApp.DataAccess.Abstract;
using ShopApp.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShopApp.DataAccess.Concrete
{
public class EfCoreOrderDal : EfCoreGenericRepository<Order, ShopContext>, IOrderDal
{
public List<Order> GetByUserId(string userId)
{
using (var context = new ShopContext())
{
return context
.Orders
.Include(i=>i.BillingAddress)
.Include(i => i.ShippingAddress)
.Include(i => i.OrderItems)
.ThenInclude(i=>i.Product)
.Where(i => i.UserId == userId).ToList();
}
}
public List<Order> GetAll()
{
using (var context = new ShopContext())
{
return context
.Orders
.Include(i => i.BillingAddress)
.Include(i => i.ShippingAddress)
.Include(i => i.OrderItems)
.ThenInclude(i => i.Product).ToList();
}
}
}
}
|
using Gerenciador.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
namespace Gerenciador.Controllers
{
public class CategoriaController : ApiController
{
private GerenciadorContext ctx = new GerenciadorContext();
[Route("api/Categoria/getcategorias")]
public IQueryable GetCategorias()
{
return ctx.Categorias;
}
[ResponseType(typeof(Categoria))]
[Route("api/Categoria/getcategoria/{id}")]
public IHttpActionResult GetCategoria(int id)
{
Categoria categoria = FindCategoria(id);
if (categoria == null)
{
return NotFound();
}
return Ok(categoria);
}
public IHttpActionResult PostCategoria(Categoria categoria)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
ctx.Categorias.Add(categoria);
ctx.SaveChanges();
return CreatedAtRoute("DefaultApi", new Categoria { CategoriaID = categoria.CategoriaID }, categoria);
}
private Categoria FindCategoria(int id)
{
return (from c in ctx.Categorias
where c.CategoriaID == id
select c).FirstOrDefault();
}
}
}
|
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace Ink.UnityIntegration {
[CustomEditor(typeof(UnityEngine.Object), true)]
public class ObjectEditor : Editor {
private ObjectInspector objectInspector;
private void OnEnable () {
objectInspector = FindObjectInspector ();
if(objectInspector != null) {
objectInspector.serializedObject = serializedObject;
objectInspector.target = target;
objectInspector.OnEnable();
}
}
private void OnDisable () {
if(objectInspector != null)
objectInspector.OnDisable();
}
public override void OnInspectorGUI () {
if(objectInspector != null) {
GUI.enabled = true;
objectInspector.OnInspectorGUI();
}
else if (target.GetType() != typeof(UnityEditor.DefaultAsset))
base.OnInspectorGUI();
}
private ObjectInspector FindObjectInspector () {
List<string> assembliesToCheck = new List<string>{"Assembly-CSharp-Editor", "Assembly-CSharp-Editor-firstpass", "Assembly-UnityScript-Editor", "Assembly-UnityScript-Editor-firstpass"};
string assetPath = AssetDatabase.GetAssetPath(target);
Assembly[] referencedAssemblies = System.AppDomain.CurrentDomain.GetAssemblies();
for(int i = 0; i < referencedAssemblies.Length; ++i) {
if(!assembliesToCheck.Contains(referencedAssemblies[i].GetName().Name))
continue;
foreach(var type in referencedAssemblies[i].GetTypes()) {
if(!type.IsSubclassOf(typeof(ObjectInspector)))
continue;
ObjectInspector objectInspector = (ObjectInspector)Activator.CreateInstance(type);
if(objectInspector.IsValid(assetPath)) {
objectInspector.target = target;
return objectInspector;
}
}
}
return null;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercicio13
{
class SalarioBase
{
static void Main(string[] args)
{
{
Console.Write("Digite a categoria profissional> ");
char Categ = Convert.ToChar(Console.ReadLine().ToUpper());
double Salbase;
switch (Categ)
{
case 'A':
case 'B':
case 'C':
Salbase = 1500;
break;
case 'D':
Salbase = 1250;
break;
case 'E':
case 'F':
Salbase = 1000;
break;
default:
Salbase = 500;
break;
}
Console.WriteLine("A categoria {0} tem {1} euros de salário base", Categ, Salbase);
}
}
}
}
|
using DSSLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DSSCriterias.Logic.States;
using System.Xml.Serialization;
namespace DSSCriterias.Logic
{
public enum Chances
{
Riscs, Unknown
}
public abstract class StateChances : State<Chances>
{
private static readonly Dictionary<Chances, StateChances> Values = new Dictionary<Chances, StateChances>()
{
[Chances.Riscs] = new ChancesRiscs(),
[Chances.Unknown] = new ChancesUnknown()
};
public static StateChances Get(Chances chance)
{
return Values[chance];
}
public static StateChances Unknown()
{
return new ChancesUnknown();
}
public static StateChances Riscs()
{
return new ChancesRiscs();
}
public double GetChance(IEnumerable<Case> cases, int pos)
{
return GetChance(cases, cases.ElementAt(pos));
}
public virtual double GetChance(IEnumerable<Case> cases, Case c)
{
return DefaultMod(cases);
}
public double SumCases(IEnumerable<Case> cases)
{
return cases.Sum(c => GetChance(cases, c));
}
public bool IsOk(IEnumerable<Case> cases)
{
return SumCases(cases) == 1;
}
protected StateChances(Chances chances) : base(chances)
{
}
protected double DefaultMod(IEnumerable<Case> cases)
{
return (double)1 / cases.Count();
}
}
}
namespace DSSCriterias.Logic.States
{
public class ChancesRiscs : StateChances
{
public ChancesRiscs() : base(Chances.Riscs)
{
Name = "Риски";
AddCompare(Chances.Riscs, 3, "Предназначен для условий риска");
AddCompare(Chances.Unknown, -10, "Не применяется в условиях неопределенности");
}
public override double GetChance(IEnumerable<Case> cases, Case c)
{
double sum = cases.Sum(cas => cas.Chance);
if (sum == 0)
{
return DefaultMod(cases);
}
else
{
return c.Chance / sum;
}
}
}
public class ChancesUnknown : StateChances
{
public ChancesUnknown() : base(Chances.Unknown)
{
Name = "Неопределенность";
AddCompare(Chances.Unknown, 3, "Предназначен для условий неопределенности");
AddCompare(Chances.Riscs, -10, "Не применяется в условиях риска");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Pixemsoft_BookStore.Model.Repositroy
{
public class BookRepository
{
public List<BookModel> getallBooks()
{
return datasource();
}
public BookModel GetbookbyID(int ID)
{
return datasource().Where(x => x.id == ID).FirstOrDefault();
}
public List<BookModel> searchbook(string title, string author)
{
return datasource().Where(x => x.Title == title || x.Author == author).ToList();
}
private List<BookModel> datasource()
{
return new List<BookModel>()
{
new BookModel(){ id=1,Title="MVC",Author="Javed"},
new BookModel(){ id=2,Title="Englis",Author="Ali"},
new BookModel(){ id=3,Title="Math",Author="hader"},
new BookModel(){ id=4,Title="Computer",Author="fahad"},
new BookModel(){ id=5,Title="Java",Author="khan"},
};
}
}
}
|
using CSConsoleRL.Components;
using CSConsoleRL.Entities;
using CSConsoleRL.Events;
using CSConsoleRL.Enums;
using CSConsoleRL.Game.Managers;
using GameTiles.Tiles;
using SFML.Window;
using SFML.System;
using CSConsoleRL.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSConsoleRL.GameSystems
{
public class GameStateSystem : GameSystem
{
private GameStateHelper _gameStateHelper;
public GameStateSystem(GameSystemManager manager, GameStateHelper gameStateHelper)
{
SystemManager = manager;
_gameStateHelper = gameStateHelper;
_systemEntities = new List<Entity>();
}
public override void InitializeSystem()
{
}
public override void HandleMessage(IGameEvent gameEvent)
{
switch (gameEvent.EventName)
{
case "RequestChangeGameState":
var newState = (EnumGameState)gameEvent.EventParams[0];
ChangeState(newState);
break;
case "SnapCameraToEntity":
var entity = (Entity)gameEvent.EventParams[0];
_gameStateHelper.SetCameraCoords(
entity.GetComponent<PositionComponent>().ComponentXPositionOnMap,
entity.GetComponent<PositionComponent>().ComponentYPositionOnMap
);
break;
}
}
public override void AddEntity(Entity entity)
{
}
private void ChangeState(EnumGameState newState)
{
_gameStateHelper.SetGameState(newState);
BroadcastMessage(new NotifyChangeGameStateEvent(newState));
}
}
} |
using System;
using System.Collections.Generic;
namespace Task2_3
{
class Program
{
static void Main(string[] args)
{
List<string> words = new List<string>();
string toAdd = "";
while (toAdd != "stop") {
toAdd = Console.ReadLine();
words.Add(toAdd);
}
for(int i = 2; i <= words.Count; i++ ) {
int pos = words.Count-i;
Console.WriteLine(words[pos]);
}
}
}
}
|
using AutoMapper;
using BLL.DTO;
using BLL.Infrastructure;
using BLL.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiUI.Models;
namespace WebApiUI.Controllers
{
[RoutePrefix("api")]
public class FriendsController : ApiController
{
private IFriendsService friendsService;
private AutoMapperCollection mapperCollection;
public FriendsController(IFriendsService friendsService)
{
this.friendsService = friendsService;
mapperCollection = new AutoMapperCollection();
}
[HttpGet]
[Route("friends/get/{id}")]
public IEnumerable<UserInformation> GetFriends(int id)
{
var friends = friendsService.GetListFriends(id);
var result = mapperCollection.Map<UserDTO, UserInformation>(friends);
return result;
}
[HttpPost]
[Route("messages/send")]
public HttpResponseMessage SendMessage([FromBody] MessageModel model)
{
model.MessageDate = TimeZoneInfo.ConvertTime(model.MessageDate,
TimeZoneInfo.FindSystemTimeZoneById("FLE Standard Time"));
var message = Mapper.Map<MessageModel, MessageDTO>(model);
friendsService.SendMessage(message);
return Request.CreateResponse(HttpStatusCode.Created);
}
[HttpGet]
[Route("messages/getReceived/{id}")]
public IEnumerable<ReceivedMessageModel> GetReceivedMessages(int id)
{
var messages = friendsService.GetReceivedMessages(id);
return mapperCollection.Map<MessageDTO, ReceivedMessageModel>(messages);
}
[HttpGet]
[Route("messages/getSent/{id}")]
public IEnumerable<SentMessageModule> GetSentMessages(int id)
{
var messages = friendsService.GetSentMessages(id);
return mapperCollection.Map<MessageDTO, SentMessageModule>(messages);
}
[HttpDelete]
[Route("messages/{id}")]
public void DeletedSentMessage(int id)
{
friendsService.DeleteMessage(id);
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
public class BulletPool : MonoBehaviour
{
private Queue<Bullet> _queueBullet = new Queue<Bullet>();
[SerializeField] Bullet _bulletPrefab;
public Bullet CreateBullet(Transform spawnPoint)
{
Bullet bullet;
if (_queueBullet.Count == 0)
bullet = Instantiate(_bulletPrefab, transform);
else
bullet = _queueBullet.Dequeue();
bullet.transform.parent = null;
bullet.transform.position = spawnPoint.position;
bullet.transform.rotation = spawnPoint.rotation;
bullet.transform.localScale = Vector3.one;
bullet.gameObject.SetActive(true);
bullet.BulletMissionCompleted += DestroyBullet;
return bullet;
}
public void DestroyBullet(Bullet bullet)
{
bullet.BulletMissionCompleted -= DestroyBullet;
bullet.gameObject.SetActive(false);
bullet.transform.parent = transform;
_queueBullet.Enqueue(bullet);
}
}
|
#if UNITY_2018_3_OR_NEWER
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
#if UNITY_2019_1_OR_NEWER
using UnityEngine.UIElements;
#elif UNITY_2018_3_OR_NEWER
using UnityEditor.Experimental.UIElements;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleEnums;
#endif
namespace UnityAtoms.Editor
{
/// <summary>
/// Editor class for the `Generator`. Use it via the top window bar at _Tools / Unity Atoms / Generator_. Only availble in `UNITY_2019_1_OR_NEWER`.
/// </summary>
public class GeneratorEditor : EditorWindow
{
/// <summary>
/// Create the editor window.
/// </summary>
[MenuItem("Tools/Unity Atoms/Generator")]
static void Init()
{
var window = GetWindow<GeneratorEditor>(false, "Unity Atoms - Generator");
window.position = new Rect(Screen.width / 2, Screen.height / 2, 440, 540);
window.Show();
}
private string _valueType = "";
private bool _isValueTypeEquatable = true;
private string _valueTypeNamespace = "";
private string _subUnityAtomsNamespace = "";
private List<AtomType> _atomTypesToGenerate = new List<AtomType>(AtomTypes.ALL_ATOM_TYPES);
private Dictionary<AtomType, VisualElement> _typeVEDict = new Dictionary<AtomType, VisualElement>();
private VisualElement _typesToGenerateInfoRow;
/// <summary>
/// Add provided `AtomType` to the list of Atom types to be generated.
/// </summary>
/// <param name="atomType">The `AtomType` to be added.</param>
private void AddAtomTypeToGenerate(AtomType atomType)
{
_atomTypesToGenerate.Add(atomType);
foreach (KeyValuePair<AtomType, List<AtomType>> entry in AtomTypes.DEPENDENCY_GRAPH)
{
if (!_typeVEDict.ContainsKey(entry.Key)) continue;
if (entry.Value.All((atom) => _atomTypesToGenerate.Contains(atom)))
{
_typeVEDict[entry.Key].SetEnabled(true);
}
}
_typesToGenerateInfoRow.Query<Label>().First().text = "";
}
/// <summary>
/// Remove provided `AtomType` from the list of Atom types to be generated.
/// </summary>
/// <param name="atomType">The `AtomType` to be removed.</param>
private List<AtomType> RemoveAtomTypeToGenerate(AtomType atomType)
{
_atomTypesToGenerate.Remove(atomType);
List<AtomType> disabledDeps = new List<AtomType>();
foreach (KeyValuePair<AtomType, List<AtomType>> entry in AtomTypes.DEPENDENCY_GRAPH)
{
if (!_typeVEDict.ContainsKey(entry.Key)) continue;
if (_atomTypesToGenerate.Contains(entry.Key) && entry.Value.Any((atom) => !_atomTypesToGenerate.Contains(atom)))
{
_typeVEDict[entry.Key].SetEnabled(false);
var toggle = _typeVEDict[entry.Key].Query<Toggle>().First();
toggle.SetValueWithoutNotify(false);
toggle.MarkDirtyRepaint();
disabledDeps.Add(entry.Key);
disabledDeps = disabledDeps.Concat(RemoveAtomTypeToGenerate(entry.Key)).ToList();
}
}
return disabledDeps;
}
/// <summary>
/// Set and display warning text in the editor.
/// </summary>
/// <param name="atomType">`AtomType` to generate the warning for.</param>
/// <param name="disabledDeps">List of disabled deps.</param>
private void SetWarningText(AtomType atomType, List<AtomType> disabledDeps = null)
{
if (disabledDeps != null && disabledDeps.Count > 0)
{
string warningText = $"{String.Join(", ", disabledDeps.Select((a) => a.Name))} depend(s) on {atomType.Name}.";
_typesToGenerateInfoRow.Query<Label>().First().text = warningText;
}
else
{
_typesToGenerateInfoRow.Query<Label>().First().text = "";
}
}
private static string _baseWritePath = Runtime.IsUnityAtomsRepo
? "../Packages/BaseAtoms" : "Assets/Atoms";
/// <summary>
/// Called when editor is enabled.
/// </summary>
private void OnEnable()
{
#if UNITY_2019_1_OR_NEWER
var root = this.rootVisualElement;
#elif UNITY_2018_3_OR_NEWER
var root = this.GetRootVisualContainer();
#endif
var pathRow = new VisualElement() { style = { flexDirection = FlexDirection.Row } };
pathRow.Add(new Label() { text = "Relative Write Path", style = { width = 180, marginRight = 8 } });
var textfield = new TextField() { value = _baseWritePath, style = { flexGrow = 1 } };
textfield.RegisterCallback<ChangeEvent<string>>(evt => _baseWritePath = evt.newValue);
pathRow.Add(textfield);
root.Add(pathRow);
var typeNameRow = new VisualElement() { style = { flexDirection = FlexDirection.Row } };
typeNameRow.Add(new Label() { text = "Type", style = { width = 180, marginRight = 8 } });
textfield = new TextField() { value = _valueType, style = { flexGrow = 1 } };
textfield.RegisterCallback<ChangeEvent<string>>(evt => _valueType = evt.newValue);
typeNameRow.Add(textfield);
root.Add(typeNameRow);
var equatableRow = new VisualElement() { style = { flexDirection = FlexDirection.Row } };
equatableRow.Add(new Label() { text = "Is Type Equatable?", style = { width = 180, marginRight = 8 } });
var equatableToggle = new Toggle() { value = _isValueTypeEquatable, style = { flexGrow = 1 } };
equatableToggle.RegisterCallback<ChangeEvent<bool>>(evt => _isValueTypeEquatable = evt.newValue);
equatableRow.Add(equatableToggle);
root.Add(equatableRow);
var typeNamespaceRow = new VisualElement() { style = { flexDirection = FlexDirection.Row } };
typeNamespaceRow.Add(new Label() { text = "Type Namespace", style = { width = 180, marginRight = 8 } });
textfield = new TextField() { value = _valueTypeNamespace, style = { flexGrow = 1 } };
textfield.RegisterCallback<ChangeEvent<string>>(evt => _valueTypeNamespace = evt.newValue);
typeNamespaceRow.Add(textfield);
root.Add(typeNamespaceRow);
var subUnityAtomsNamespaceRow = new VisualElement() { style = { flexDirection = FlexDirection.Row } };
subUnityAtomsNamespaceRow.Add(new Label() { text = "Sub Unity Atoms Namespace", style = { width = 180, marginRight = 8 } });
textfield = new TextField() { value = _subUnityAtomsNamespace, style = { flexGrow = 1 } };
textfield.RegisterCallback<ChangeEvent<string>>(evt => _subUnityAtomsNamespace = evt.newValue);
subUnityAtomsNamespaceRow.Add(textfield);
root.Add(subUnityAtomsNamespaceRow);
root.Add(CreateDivider());
var typesToGenerateLabelRow = new VisualElement() { style = { flexDirection = FlexDirection.Row } };
typesToGenerateLabelRow.Add(new Label() { text = "Type(s) to Generate" });
root.Add(typesToGenerateLabelRow);
foreach (var atomType in AtomTypes.ALL_ATOM_TYPES)
{
_typeVEDict.Add(atomType, CreateAtomTypeToGenerateToggleRow(atomType));
root.Add(_typeVEDict[atomType]);
}
root.Add(CreateDivider());
_typesToGenerateInfoRow = new VisualElement() { style = { flexDirection = FlexDirection.Column } };
_typesToGenerateInfoRow.Add(new Label() { style = { color = Color.yellow, height = 12 } });
_typesToGenerateInfoRow.RegisterCallback<MouseUpEvent>((e) => { _typesToGenerateInfoRow.Query<Label>().First().text = ""; });
root.Add(_typesToGenerateInfoRow);
root.Add(CreateDivider());
var buttonRow = new VisualElement()
{
style = { flexDirection = FlexDirection.Row }
};
var button1 = new Button(Close)
{
text = "Close",
style = { flexGrow = 1 }
};
buttonRow.Add(button1);
var button2 = new Button(() =>
{
var templates = Generator.GetTemplatePaths();
var templateConditions = Generator.CreateTemplateConditions(_isValueTypeEquatable, _valueTypeNamespace, _subUnityAtomsNamespace, _valueType);
var templateVariables = Generator.CreateTemplateVariablesMap(_valueType, _valueTypeNamespace, _subUnityAtomsNamespace);
var capitalizedValueType = _valueType.Replace('.', '_').Capitalize();
_atomTypesToGenerate.ForEach((atomType) =>
{
templateVariables["VALUE_TYPE_NAME"] = atomType.IsValuePair ? $"{capitalizedValueType}Pair" : capitalizedValueType;
var valueType = atomType.IsValuePair ? $"{capitalizedValueType}Pair" : _valueType;
templateVariables["VALUE_TYPE"] = valueType;
Generator.Generate(new AtomReceipe(atomType, valueType), _baseWritePath, templates, templateConditions, templateVariables);
});
AssetDatabase.Refresh();
})
{
text = "Generate",
style = { flexGrow = 1 }
};
buttonRow.Add(button2);
root.Add(buttonRow);
}
/// <summary>
/// Helper method to create a divider.
/// </summary>
/// <returns>The divider (`VisualElement`) created.</returns>
private VisualElement CreateDivider()
{
return new VisualElement()
{
style = { flexDirection = FlexDirection.Row, marginBottom = 2, marginTop = 2, marginLeft = 2, marginRight = 2, height = 1 }
};
}
/// <summary>
/// Helper to create toogle row for a specific `AtomType`.
/// </summary>
/// <param name="atomType">The provided `AtomType`.</param>
/// <returns>A new toggle row (`VisualElement`).</returns>
private VisualElement CreateAtomTypeToGenerateToggleRow(AtomType atomType)
{
var row = new VisualElement() { style = { flexDirection = FlexDirection.Row } };
row.Add(new Label() { text = atomType.DisplayName, style = { width = 220, marginRight = 8 } });
var toggle = new Toggle() { value = _atomTypesToGenerate.Contains(atomType) };
toggle.RegisterCallback<ChangeEvent<bool>>(evt =>
{
if (evt.newValue)
{
AddAtomTypeToGenerate(atomType);
}
else
{
var disabledDeps = RemoveAtomTypeToGenerate(atomType);
SetWarningText(atomType, disabledDeps);
}
});
row.Add(toggle);
return row;
}
}
}
#endif
|
using Harmony;
using Odyssey.Core;
using Odyssey.Utilities;
using System.Reflection;
namespace Odyssey
{
/**
* Entry point into our Odyssey submarine
*/
public class EntryPoint
{
public static string QMODS_FOLDER_LOCATION { get; private set; }
public static string MOD_FOLDER_NAME { get; private set; }
public static readonly string ASSET_FOLDER_NAME = "Assets/";
public static HarmonyInstance HarmonyInstance { get; private set; }
public static void Entry()
{
HarmonyInstance = HarmonyInstance.Create("taylor.brett.Odyssey.mod");
HarmonyInstance.PatchAll(Assembly.GetExecutingAssembly());
OdysseyAssetLoader.LoadAssets();
OdysseyMod manta = new OdysseyMod();
manta.Patch();
}
public static void SetModFolderDirectory(string qmodsFolderLocation, string modFolderName)
{
QMODS_FOLDER_LOCATION = qmodsFolderLocation;
MOD_FOLDER_NAME = modFolderName;
}
}
}
|
using Shiftgram.AccountServer.Helpers;
using Shiftgram.AccountServer.Models;
using Shiftgram.Core.Enums;
using Shiftgram.Core.Exceptions;
using Shiftgram.Core.Repository;
using Shiftgram.Core.ViewModels;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
namespace Shiftgram.AccountServer.Controllers
{
[RoutePrefix("api/friend")]
public class FriendController : ApiController
{
private IFriendRepository _friendRepository;
private IAccountRepository _accountRepository;
public FriendController(IFriendRepository friendRepository, IAccountRepository accountRepository)
{
this._friendRepository = friendRepository;
this._accountRepository = accountRepository;
}
[HttpPost]
public async Task<IHttpActionResult> AddFriend(FriendViewModel model)
{
try
{
var accountB = await this._accountRepository.GetByPhone(model.AccountBPhone);
if (accountB != null)
{
var item = Copy.CopyToFriend(model.AccountAId, accountB.Id);
await this._friendRepository.Add(item);
return Ok();
}
}
catch(AccountException)
{
return BadRequest();
}
return BadRequest();
}
[HttpDelete]
public async Task<IHttpActionResult> DeleteFriend(FriendViewModel model)
{
var code = await this._friendRepository.Delete(model.AccountAId, model.AccountBId);
if(code == DbAnswerCode.Ok)
{
return Ok();
}
return BadRequest();
}
[HttpGet]
[Route("{accountAId:int}")]
public async Task<IHttpActionResult> GetFriends(int accountAId)
{
var friends = await this._friendRepository.GetFriends(accountAId) as List<AccountFriendViewModel>;
return Ok(friends);
}
}
}
|
using System;
namespace DoublePermutationMethod.Command
{
class DecoderCubeCommand : BaseCommand
{
public override string Name => "decode";
public override void Execute()
{
Console.Write("Enter the cipher to be decrypted: ");
string message = Console.ReadLine();
Console.WriteLine("Enter key-col separated by space:");
string col = Console.ReadLine();
Console.WriteLine("Enter key-row separated by space:");
string row = Console.ReadLine();
int size = col.Split().Length;
while ((size * size) < message.Length)
{
Console.WriteLine("Too short key, try again!");
Console.WriteLine("Enter key-col separated by space:");
col = Console.ReadLine();
Console.WriteLine("Enter key-row separated by space:");
row = Console.ReadLine();
}
Key key = new Key(size);
KeyStringConverter.Key = key;
key = KeyStringConverter.ConvertStringsToKey(row, col);
Cube cube = CubeToStringConverter.StringToCube(message, size);
CubeCrypto.Cube = cube;
CubeCrypto.GetDecode(key);
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace FitnessStore.API.Core.Entities
{
/// <summary>
/// Tabela das refeições do sistema.
/// </summary>
[Table("Refeicoes")]
public class Refeicao
{
/// <summary>
/// Código identificador da refeição.
/// </summary>
[Column("CODIGOREFEICAO"), Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CodigoRefeicao { get; set; }
/// <summary>
/// Descrição da refeição.
/// </summary>
[Column("DESCRICAO"), Required, MaxLength(150, ErrorMessage = "A descrição da refeição deve conter no máximo 150 caracteres.")]
public string Descricao { get; set; }
/// <summary>
/// Total de calorias fornecidos pela refeição.
/// </summary>
[Column("CALORIAS"), Required]
public int Calorias { get; set; }
/// <summary>
/// Data na qual a refeição foi realizada.
/// </summary>
[Column("DATAREALIZADA"), Required]
public DateTimeOffset DataRealizada { get; set; }
/// <summary>
/// Data de inclusão da refeição no sistema.
/// </summary>
[Column("DATAINCLUSAO"), Required]
public DateTimeOffset DataInclusao { get; set; }
/// <summary>
/// Flag identificador de exclusão lógica da refeição.
/// </summary>
[Column("EXCLUIDO"), Required]
public bool Excluido { get; set; }
/// <summary>
/// Codigo identificador do usuário ao qual a refeição pertence.
/// </summary>
[Column("CODIGOUSUARIO"), Required]
public int CodigoUsuario { get; set; }
/// <summary>
/// Propriedade de navegação do usuário ao qual a refeição pertence.
/// </summary>
public virtual Usuario Usuario { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrcMove : Monster
{
[SerializeField]
public float speed = 1;
public bool moveRight;
private Character character;
private AudioSource audioSource;
public AudioClip audioClip;
protected override void Start()
{
character = FindObjectOfType<Character>();
audioSource = character.GetComponent<AudioSource>();
}
// Update is called once per frame
protected override void Update()
{
if (moveRight)
{
transform.Translate(2 * Time.deltaTime * speed, 0, 0);
transform.localScale = new Vector2(0.36f, 0.36f);
}
else
{
transform.Translate(-2 * Time.deltaTime * speed, 0, 0);
transform.localScale = new Vector2(-0.36f, 0.36f);
}
}
public int orcsValue = 1;
protected override void OnTriggerEnter2D(Collider2D trig)
{
if (trig.gameObject.CompareTag("Turn"))
{
if (moveRight)
{
moveRight = false;
}
else
{
moveRight = true;
}
}
Unit unit = trig.GetComponent<Unit>();
if (unit && unit is Character)
{
if (Mathf.Abs(unit.transform.position.x - transform.position.x) < 0.85F)
{
ReceiveDamage();
audioSource.PlayOneShot(audioClip);
ScoreOrcsManager.instance.ChangeScore(orcsValue);
}
else
{
unit.ReceiveDamage();
}
}
}
}
|
using MixErp.Data;
using MixErp.Fonksiyonlar;
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 MixErp.Bilgi
{
public partial class frmUrun : Form
{
MixErpDbEntities db = new MixErpDbEntities();
Numaralar N = new Numaralar();
int secimId = -1;
bool edit = false;
public frmUrun()
{
InitializeComponent();
}
private void frmUrun_Load(object sender, EventArgs e)
{
Combo();
Listele();
}
private void Listele()
{
liste.Rows.Clear();
int i = 0;
var srg = (from s in db.tblUrunlers
where s.UrunKodu.Contains(txtBul.Text) || s.UrunAciklama.Contains(txtBul.Text) || s.bKategori.KategoriAdi.Contains(txtBul.Text) || s.tblCari.CariAdi.Contains(txtBul.Text) // contains: içermek
select s).ToList(); // sorgu sonucunu liste haline getirip srg nesnesinin içine atar.
foreach (var k in srg)
{
liste.Rows.Add(); // her döngüye girdiğinde bir satır oluşturur.
liste.Rows[i].Cells[0].Value = k.Id;
liste.Rows[i].Cells[1].Value = k.UrunKodu;
liste.Rows[i].Cells[2].Value = k.UrunAciklama;
liste.Rows[i].Cells[3].Value = k.tblCari.CariAdi;
liste.Rows[i].Cells[4].Value = k.bKategori.KategoriAdi;
i++;
}
// kullanıcı yeni bir satır eklemesin
liste.AllowUserToAddRows = false;
}
private void Combo()
{
txtCariId.Items.Clear();
txtCariId.DataSource = db.tblCaris.ToList();
txtCariId.ValueMember = "Id";
txtCariId.DisplayMember = "CariAdi";
txtCariId.SelectedIndex = 0;
txtMenseiId.Items.Clear();
txtMenseiId.DataSource = db.bMenseis.ToList();
txtMenseiId.ValueMember = "Id";
txtMenseiId.DisplayMember = "MenseiAdi";
txtMenseiId.SelectedIndex = 0;
txtKategoriId.Items.Clear();
txtKategoriId.DataSource = db.bKategoris.ToList();
txtKategoriId.ValueMember = "Id";
txtKategoriId.DisplayMember = "KategoriAdi";
txtKategoriId.SelectedIndex = 0;
txtBirimId.Items.Clear();
txtBirimId.DataSource = db.bBirims.ToList();
txtBirimId.ValueMember = "Id";
txtBirimId.DisplayMember = "BirimAdi";
txtBirimId.SelectedIndex = 0;
}
private void btnKaydet_Click(object sender, EventArgs e)
{
if (edit && secimId > 0)
{
Guncelle();
}
else if (edit == false)
{
YeniKaydet();
}
}
private void YeniKaydet()
{
var uKontrol = db.tblUrunlers.Where(x => x.UrunKodu.ToLower() == txtUrunKodu.Text.ToLower()).ToList();
if (uKontrol.Count()==0)
{
tblUrunler urn = new tblUrunler(); // nesne oluşturduk.
urn.UrunKodu = txtUrunKodu.Text;
urn.UrunAciklama = txtUrunAciklama.Text;
urn.CariId = db.tblCaris.First(x => x.CariAdi == txtCariId.Text).Id; // x artık departman tablosundaki id ve adına ulaşabiliyor. First tek kayıt getir demek. landa experision
urn.MenseiId = db.bMenseis.First(x => x.MenseiAdi == txtMenseiId.Text).Id;
urn.KategoriId = db.bKategoris.First(x => x.KategoriAdi == txtKategoriId.Text).Id;
urn.BirimId = db.bBirims.First(x => x.BirimAdi == txtBirimId.Text).Id;
// db de oluşturduğum nesneyi doldurdum
db.tblUrunlers.Add(urn);
db.SaveChanges();
tblStokDurum stk = new tblStokDurum();
stk.Ambar = 0;
stk.Barkod = txtUrunKodu.Text + "/" + txtUrunAciklama.Text;
stk.Depo = 0;
stk.Raf = 0;
stk.StokKodu = N.StokKod();
stk.UrunId = db.tblUrunlers.First(x => x.UrunKodu == txtUrunKodu.Text).Id;
db.tblStokDurums.Add(stk);
db.SaveChanges();
MessageBox.Show("Kayıt Başarılı");
Listele();
Temizle();
}
else
{
MessageBox.Show("Bu ürün daha önce kaydedilmiş.Lütfen kontrol ediniz.");
txtUrunKodu.Text = "";
return;
}
}
private void Temizle()
{
foreach (Control con in splitContainer2.Panel1.Controls) // textbox lar control sınıfının elemanıdır. Control sınıfından bir nesne türettik. Hangi alandaki kontrollerde işlem yapacağımızı belirttik.
{
if (con is TextBox || con is ComboBox)
{
con.Text = "";
}
}
secimId = -1;
edit = false;
txtCariId.SelectedIndex = 0;
txtBirimId.SelectedIndex = 0;
txtKategoriId.SelectedIndex = 0;
txtMenseiId.SelectedIndex = 0;
}
private void Guncelle()
{
tblUrunler urn = new tblUrunler(); // nesne oluşturduk.
urn.UrunKodu = txtUrunKodu.Text;
urn.UrunAciklama = txtUrunAciklama.Text;
urn.CariId = db.tblCaris.First(x => x.CariAdi == txtCariId.Text).Id; // x artık departman tablosundaki id ve adına ulaşabiliyor. First tek kayıt getir demek. landa experision
urn.MenseiId = db.bMenseis.First(x => x.MenseiAdi == txtMenseiId.Text).Id;
urn.KategoriId = db.bKategoris.First(x => x.KategoriAdi == txtKategoriId.Text).Id;
urn.BirimId = db.bBirims.First(x => x.BirimAdi == txtBirimId.Text).Id;
// db de oluşturduğum nesneyi doldurdum
db.SaveChanges();
MessageBox.Show("Güncelleme Başarılı Başarılı");
Listele();
Temizle();
}
private void liste_DoubleClick(object sender, EventArgs e)
{
Sec();
if (secimId > 0)
{
Ac(secimId);
}
}
private void Ac(int secimId)
{
edit = true;
tblUrunler urn = db.tblUrunlers.Find(secimId);
txtUrunKodu.Text = urn.UrunKodu;
txtUrunAciklama.Text = urn.UrunAciklama;
txtBirimId.Text = urn.bBirim.BirimAdi;
txtKategoriId.Text = urn.bKategori.KategoriAdi;
txtMenseiId.Text = urn.bMensei.MenseiAdi;
txtCariId.Text = urn.tblCari.CariAdi;
}
private void Sec()
{
try
{
secimId = Convert.ToInt32(liste.CurrentRow.Cells[0].Value.ToString());
}
catch (Exception)
{
secimId = -1;
}
}
private void btnKapat_Click(object sender, EventArgs e)
{
Close();
}
private void btnSil_Click(object sender, EventArgs e)
{
if (edit && secimId > 0)
{
Sil();
}
}
private void Sil()
{
db.tblUrunlers.Remove(db.tblUrunlers.Find(secimId));
db.SaveChanges();
MessageBox.Show($"{secimId} nolu kayıt Silinmiştir.");
Listele();
Temizle();
}
private void btnBul_Click(object sender, EventArgs e)
{
Listele();
}
}
}
|
namespace Sentry.PlatformAbstractions;
internal static class DeviceInfo
{
#if ANDROID
public const string PlatformName = "Android";
#elif IOS
public const string PlatformName = "iOS";
#elif MACCATALYST
public const string PlatformName = "Mac Catalyst";
#endif
}
|
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Neuronal_Net_Test.Models;
using Neuronal_Net_Test.NeuralNet;
using Neuronal_Net_Test.NeuralNet.Neurons;
using System;
using System.Text;
namespace Neuronal_Net_Test
{
public partial class Form1 : Form
{
private Point? _lastPoint;
private List<Point?> _points = new List<Point?>();
private Graphics _gp1;
private Graphics _gp2;
private List<Partition> _partitions;
private int _mostMatch = 0;
private NeuralNetwork net = new NeuralNetwork();
private List<char> values = new List<char>
{
'a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','x','y','z'
};
public Form1()
{
InitializeComponent();
_gp1 = panel1.CreateGraphics();
_gp2 = panel2.CreateGraphics();
SetPartitions(20, 24);
for (int i = 0; i < 20*24; i++)
{
net.AddInputNeuron(new InputNeuron());
}
var rand = new Random();
for (int i = 0; i < 20 * 24; i++)
{
net.AddHiddenNeuron(new WorkingNeuron());
}
for (int i = 0; i < 52; i++)
{
net.AddOutputNeuron(new WorkingNeuron());
}
net.GenerateFullMesh();
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
_lastPoint = new Point(e.X, e.Y);
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
_points.Add(_lastPoint);
_lastPoint = null;
simplify_Panel1();
var data = new List<float>();
foreach (var part in _partitions)
{
data.Add((float)part.IncludesPoint / (float)_mostMatch);
}
net.CalculateValue(data);
var max = net.GetMaxValue();
label2.Text = values[max].ToString();
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (_lastPoint != null)
{
_points.Add(_lastPoint);
var newPoint = new Point(e.X, e.Y);
if (_lastPoint != null)
{
_gp1.DrawLine(new Pen(Color.Black), (Point)_lastPoint, newPoint);
}
_lastPoint = newPoint;
}
}
private void simplify_Panel1()
{
FindPointsIncluded();
DrawRectangles();
}
private void SetPartitions(int xPartitions, int yPartitions)
{
_partitions = new List<Partition>();
_points = new List<Point?>();
var xL = panel1.Width / xPartitions;
var yL = panel1.Height / yPartitions;
for (var dY = 0; dY < yPartitions; dY++)
{
for (var dX = 0; dX < xPartitions; dX++)
{
_partitions.Add(new Partition
{
Part = new Rectangle(dX * xL, dY * yL, xL, yL)
});
}
}
}
private void FindPointsIncluded()
{
foreach (var partition in _partitions)
{
foreach (var point in _points)
{
if (partition.Part.Contains(point??new Point()))
{
partition.IncludesPoint += 1;
}
}
if (partition.IncludesPoint > _mostMatch)
{
_mostMatch = partition.IncludesPoint;
}
}
_points = new List<Point?>();
}
private void DrawRectangles()
{
foreach (var partition in _partitions)
{
_gp2.FillRectangle( new SolidBrush(Color.FromArgb(Convert.ToInt32(((float)partition.IncludesPoint / (float)_mostMatch * 255)),0,0,0)), partition.Part);
}
}
private void RePantRectangles()
{
foreach (var partition in _partitions)
{
_gp2.FillRectangle(new SolidBrush(Color.White), partition.Part);
}
}
private void button1_Click(object sender, EventArgs e)
{
var input = textBox1.Text;
var code = Encoding.ASCII.GetBytes(input)[0];
if (code > 96)
{
code -= 96;
}
else
{
code -= 38;
}
var data = new float[20 * 24];
for (var i = 0;i < _partitions.Count; i++)
{
data[i] = ((float)_partitions[i].IncludesPoint / (float)_mostMatch);
}
net.TrainNeuralNet(data, code);
SetPartitions(20, 24);
RePantRectangles();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace NStandard
{
internal class IndicesStepper : IEnumerable<int[]>
{
public int Rank { get; set; }
public int[] Lengths { get; set; }
public int Offset { get; set; }
public IndicesStepper(int offset, int[] lengths)
{
if (lengths.Any(x => x <= 0)) throw new ArgumentException("All lengths must be greater than 0.", nameof(lengths));
Offset = offset;
Rank = lengths.Length;
Lengths = lengths;
}
public IEnumerator<int[]> GetEnumerator()
{
var current = new int[Rank];
var index = Rank - 1;
var value = Offset;
current[index] = value;
Normalize(index, value);
yield return current;
bool MoveNext()
{
var index = Rank - 1;
var value = current[index] + 1;
current[index] = value;
return Normalize(index, value);
}
bool Normalize(int index, int value)
{
if (value >= Lengths[index])
{
if (index == 0) return false;
var prevIndex = index - 1;
current[index] = value % Lengths[index];
current[prevIndex] += value / Lengths[index];
return Normalize(prevIndex, current[prevIndex]);
}
else return true;
}
while (MoveNext())
{
yield return current;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Restaurant.Models;
using Restaurant.Repositories;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Restaurant.Controllers
{
public class NewMessageController : Controller
{
private IMessageRepository NMRepo;
public NewMessageController(IMessageRepository repo)
{
NMRepo = repo;
}
// GET: /<controller>/
[HttpGet]
public ViewResult Forum(string subject, int id)
{
var Nmes = new NMViewModel();
Nmes.Subject = subject;
Nmes.MessageID = id;
Nmes.newmes = new NewMessage();
return View(Nmes);
}
[HttpPost]
public IActionResult Forum(NMViewModel nmv)
{
//if (nmv.newmes.Body.IndexOf(" ", StringComparison.Ordinal) < 1)
//{
// string prop = "newmes.Body";
// ModelState.AddModelError(prop, "Please enter at least two words");
//}
//if (ModelState.IsValid)
//{
// Message message = (from m in NMRepo.GetAllMessages()
// where m.MessageID == nmv.MessageID
// select m).FirstOrDefault<Message>();
// message.NewMessage.Add(nmv.nm);
// NMRepo.Update(message);
// return RedirectToAction("Messages", "Message");
Message message = (from m in NMRepo.GetAllMessages()
where m.MessageID == nmv.MessageID
select m).FirstOrDefault<Message>();
message.NewMessage.Add(nmv.newmes);
NMRepo.Update(message);
return RedirectToAction("Messages", "Message");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MODEL.ViewModel
{
public partial class VIEW_FW_MODULEPERMISSION : VIEW_FW_MODULEPERMISSION_P
{
public string PERMISSION_PID { get; set; }
public string MODULE_NAME { get; set; }
public string NAME { get; set; }
public string ICON { get; set; }
public int SEQ_NO { get; set; }
public string ISLINK { get; set; }
public string LINKURL { get; set; }
public string REMARK { get; set; }
public List<VIEW_FW_MODULEPERMISSION> children { get; set; }
}
}
|
using Sirenix.OdinInspector;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DChild.Gameplay.Player
{
public abstract class MagicConsumingAbility : MonoBehaviour , IPlayerBehaviour
{
[SerializeField]
[MinValue(0f)]
private int m_requiredMagicPoints;
private IMagicPoint m_playerMagicPoint;
public virtual void Initialize(IPlayer player) => m_playerMagicPoint = player.magicPoint;
public bool UseAbility()
{
if (m_playerMagicPoint.IsSufficient(m_requiredMagicPoints))
{
DoAbility();
}
return false;
}
protected abstract bool DoAbility();
}
}
|
namespace AutoTests.Framework.Web
{
public abstract class Element : PageObject
{
protected Element(WebDependencies dependencies) : base(dependencies)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PhobiaX.Actions;
using PhobiaX.Ai;
using PhobiaX.Assets;
using PhobiaX.Cleanups;
using PhobiaX.Game.GameLoops;
using PhobiaX.Game.GameObjects;
using PhobiaX.Game.UserInteface;
using PhobiaX.Game.UserInterface;
using PhobiaX.Graphics;
using PhobiaX.Physics;
using PhobiaX.SDL2;
using PhobiaX.SDL2.Options;
using PhobiaX.SDL2.Wrappers;
using SDL2;
namespace PhobiaX
{
class Program
{
private readonly TimeSpan renderingDelay = TimeSpan.FromMilliseconds(15);
private readonly SDLApplication application;
private readonly SDLEventProcessor eventProcessor;
private readonly GameGarbageObserver gameGarbageObserver;
private readonly UserIntefaceFactory userIntefaceFactory;
private readonly GameLoopFactory gameLoopFactory;
private readonly EnemyAiObserver enemyAiObserver;
private readonly GameObjectFactory gameObjectFactory;
private readonly Renderer renderer;
private readonly CollissionObserver collissionObserver;
private GameLoop gameLoop;
public Program(SDLApplication application, SDLEventProcessor eventProcessor, GameGarbageObserver gameGarbageObserver, UserIntefaceFactory userIntefaceFactory, GameLoopFactory gameLoopFactory, EnemyAiObserver enemyAiObserver, GameObjectFactory gameObjectFactory, Renderer renderer, CollissionObserver collissionObserver)
{
this.application = application ?? throw new ArgumentNullException(nameof(application));
this.eventProcessor = eventProcessor ?? throw new ArgumentNullException(nameof(eventProcessor));
this.gameGarbageObserver = gameGarbageObserver ?? throw new ArgumentNullException(nameof(gameGarbageObserver));
this.userIntefaceFactory = userIntefaceFactory ?? throw new ArgumentNullException(nameof(userIntefaceFactory));
this.gameLoopFactory = gameLoopFactory ?? throw new ArgumentNullException(nameof(gameLoopFactory));
this.enemyAiObserver = enemyAiObserver ?? throw new ArgumentNullException(nameof(enemyAiObserver));
this.gameObjectFactory = gameObjectFactory ?? throw new ArgumentNullException(nameof(gameObjectFactory));
this.renderer = renderer ?? throw new ArgumentNullException(nameof(renderer));
this.collissionObserver = collissionObserver ?? throw new ArgumentNullException(nameof(collissionObserver));
Restart();
}
private void Restart()
{
gameObjectFactory.ClearCallbacks();
gameGarbageObserver.CleanupAll();
gameGarbageObserver.AddCleanableObject(renderer);
gameGarbageObserver.AddCleanableObject(collissionObserver);
gameGarbageObserver.AddCleanableObject(enemyAiObserver);
renderer.DestroyCallback = (gameObject) => gameGarbageObserver.Observe(gameObject);
gameObjectFactory.OnCreateCallback((gameObject) => {
collissionObserver.ObserveCollission(gameObject);
renderer.Add(gameObject);
if (gameObject is EnemyGameObject)
{
enemyAiObserver.Observe(gameObject as EnemyGameObject);
}
if (gameObject is PlayerGameObject)
{
enemyAiObserver.AddTarget(gameObject);
}
});
var scoreUI = userIntefaceFactory.CreateScoreUI(0, 100);
scoreUI.SetPlayerLife(0, 100);
gameLoop = gameLoopFactory.CreateGameLoop();
gameLoop.ActionBinder.AssignKeysToGameAction(GameAction.Quit, false, SDL.SDL_Scancode.SDL_SCANCODE_Q);
gameLoop.ActionBinder.AssignKeysToGameAction(GameAction.Restart, false, SDL.SDL_Scancode.SDL_SCANCODE_F2);
gameLoop.ActionBinder.RegisterPressAction(GameAction.Quit, () => application.Quit());
gameLoop.ActionBinder.RegisterPressAction(GameAction.Restart, () => Restart());
collissionObserver.OnCollissionCallback((gameObject, colliders) => {
if (!colliders.OfType<MapGameObject>().Any())
{
if (gameObject is RocketGameObject)
{
gameGarbageObserver.Observe(gameObject);
}
}
colliders = colliders.Where(i => i.ColladableObject != null).ToList();
if (gameObject.ColladableObject == null || !colliders.Any())
{
return;
}
if (gameObject is PlayerGameObject && colliders.OfType<EnemyGameObject>().Any())
{
(gameObject as PlayerGameObject).Hit();
var player = (gameObject as PlayerGameObject);
scoreUI.SetPlayerLife(player.PlayerNumber, player.Life);
}
else if (gameObject is EnemyGameObject && colliders.OfType<RocketGameObject>().Any())
{
(gameObject as EnemyGameObject).Hit();
foreach (var rocket in colliders.OfType<RocketGameObject>())
{
var castedRocket = rocket as RocketGameObject;
var player = (castedRocket.Owner as PlayerGameObject);
player.Score++;
scoreUI.SetPlayerScore(player.PlayerNumber, player.Score);
rocket.Hit();
}
}
if (gameObject is RocketGameObject)
{
if (gameObject.ColladableObject != null)
{
(gameObject as RocketGameObject).MoveForward();
}
}
if (gameObject is EnemyGameObject)
{
(gameObject as EnemyGameObject).Stop();
}
});
}
public void StartGameLoop()
{
while (!application.ShouldQuit)
{
DoGameLoop();
}
}
private void DoGameLoop()
{
gameLoop.Evaluate();
eventProcessor.Evaluate();
renderer.Evaluate();
gameGarbageObserver.Evaluate();
application.Delay(renderingDelay);
}
static void Main(string[] args)
{
using (var serviceProvider = InitServiceProvider())
{
var program = serviceProvider.GetService<Program>();
program.StartGameLoop();
}
}
private static ServiceProvider InitServiceProvider()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging((builder) => builder.AddConsole().SetMinimumLevel(LogLevel.Debug));
serviceCollection.AddSingleton((sc) => new WindowOptions { Title = "PhobiaX", X = 0, Y = 0, Width = 1024, Height = 768, WindowFlags = SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL | SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI });
serviceCollection.AddSingleton((sc) => new RendererOptions { Index = -1, RendererFlags = SDL.SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC | SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED });
serviceCollection.AddSingleton<Program>();
serviceCollection.AddSingleton<ISDL2, SDL2Wrapper>();
serviceCollection.AddSingleton<ISDL2Image, SDL2ImageWrapper>();
serviceCollection.AddSingleton<SDLApplication>();
serviceCollection.AddSingleton<AssetProvider>();
serviceCollection.AddSingleton<SDLEventProcessor>();
serviceCollection.AddSingleton<SDLWindow>();
serviceCollection.AddSingleton<SDLRenderer>();
serviceCollection.AddSingleton<SDLSurfaceFactory>();
serviceCollection.AddSingleton<SDLTextureFactory>();
serviceCollection.AddSingleton<Renderer>();
serviceCollection.AddSingleton<CollissionObserver>();
serviceCollection.AddSingleton<UserIntefaceFactory>();
serviceCollection.AddSingleton<GameLoopFactory>();
serviceCollection.AddSingleton<GameObjectFactory>();
serviceCollection.AddSingleton<PathFinder>();
serviceCollection.AddSingleton<TimeThrottler>();
serviceCollection.AddSingleton<EnemyAiObserver>();
serviceCollection.AddSingleton<GameGarbageObserver>();
return serviceCollection.BuildServiceProvider();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
using System.Xml.Serialization;
namespace AxiReports
{
public class TareReportViewSettings : Entity
{
[XmlIgnore]
public override string FriendlyName
{
get { return "Настройки отчета оборот тары"; }
}
public List<Warehouse> SelectedWarehouses;
public DateTime DateBegin;
public DateTime DateEnd;
}
}
|
namespace SelectionCommittee.BLL.DataTransferObject
{
public class MarkSubjectDTO
{
public int SubjectId { get; set; }
public int Mark { get; set; }
public string EnrolleeId { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IRAP.Entity.SSO
{
/// <summary>
/// 站点的系统登录信息
/// </summary>
public class StationLogin
{
/// <summary>
/// 系统登录标识,0-该站点尚无登录信息
/// </summary>
public long SysLogID
{
get; set;
}
/// <summary>
/// 机构叶标识
/// </summary>
public int AgencyLeaf
{
get; set;
}
/// <summary>
/// 机构名称
/// </summary>
public string AgencyName
{
get; set;
}
/// <summary>
/// 社区标识,请保存为 Session 变量以备用
/// </summary>
public int CommunityID
{
get; set;
}
/// <summary>
/// 错误信息文本
/// </summary>
public string ErrText
{
get; set;
}
/// <summary>
/// 站点主机名
/// </summary>
public string HostName
{
get; set;
}
/// <summary>
/// 站点 IP 地址
/// </summary>
public string IPAddress
{
get; set;
}
/// <summary>
/// 语言标识
/// </summary>
public int LanguageID
{
get; set;
}
/// <summary>
/// 角色叶标识
/// </summary>
public int RoleLeaf
{
get; set;
}
/// <summary>
/// 角色名称
/// </summary>
public string RoleName
{
get; set;
}
/// <summary>
/// 站点组标识
/// </summary>
public int StationGroupID
{
get; set;
}
/// <summary>
/// 用户代码
/// </summary>
public string UserCode
{
get; set;
}
/// <summary>
/// 用户名称
/// </summary>
public string UserName
{
get; set;
}
public StationLogin Clone()
{
return MemberwiseClone() as StationLogin;
}
}
} |
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using ChoiceCenium.Services;
using DevExpress.Web;
namespace ChoiceCenium
{
public partial class View : Page
{
private IList<KjedeInfoes> _kjedelist;
protected void Page_Load(object sender, EventArgs e)
{
// ugle : page postback handling...
FillKjedeList();
var username = HttpContext.Current.User.Identity.Name;
bool isAuth = Request.IsAuthenticated;
if (username == LoginService.CeniumUsername)
{
HotelList.Columns[0].Visible = true;
HotelList.Columns[5].Visible = true;
HotelList.Columns[6].Visible = true;
HotelList.Columns[7].Visible = true;
HotelList.Columns[8].Visible = true;
HotelList.Columns[10].Visible = true;
HotelList.Columns[11].Visible = true;
HotelList.Columns[12].Visible = true;
}
else if (username == LoginService.DefaultUser)
{
HotelList.Columns[0].Visible = true;
HotelList.Columns[5].Visible = true;
HotelList.Columns[6].Visible = true;
HotelList.Columns[7].Visible = true;
HotelList.Columns[8].Visible = true;
HotelList.Columns[9].Visible = false;
HotelList.Columns[10].Visible = false;
HotelList.Columns[11].Visible = false;
HotelList.Columns[12].Visible = true;
}
lnkLogout.Visible = isAuth;
lnkLogin.Visible = !isAuth;
}
private void FillKjedeList()
{
_kjedelist = KjedeService.GetKjeder();
}
protected void ValidateUser_Click(object sender, EventArgs e)
{
var username = txtUsername.Text;
var password = txtPassword.Text;
var srv = new LoginService();
var loginSuccess = srv.ValidateUser(username, password);
if (!loginSuccess) return;
FormsAuthentication.SetAuthCookie(username, true);
Response.Redirect("view.aspx", false);
}
protected void lnkLogout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("view.aspx", false);
}
protected void HotelList_CommandButtonInitialize(object sender, ASPxGridViewCommandButtonEventArgs e)
{
if (e.ButtonType == ColumnCommandButtonType.New && e.VisibleIndex != -1)
{
e.Text = "";
}
if (e.ButtonType == ColumnCommandButtonType.Edit || e.ButtonType == ColumnCommandButtonType.Delete)
{
e.Text = "";
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using radisutm.Models;
using System.Data;
using radisutm.ClassFunction;
namespace radisutm.Controllers
{
public class GrantController : Controller
{
// GET: Grant
public ActionResult Index()
{
return View();
}
public ActionResult GrantProfile(string id)
{
GrantDB modelGrant = new GrantDB();
return View("GrantProfile", modelGrant.GetGrantInfo(id));
}
public ActionResult Proposal()
{
return View("GrantProfile");
}
public ActionResult FinancialInfo(string id)
{
GrantDB modelGrant = new GrantDB();
return View("FinancialInfo", modelGrant.GetGrantInfo(id));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GDS.Entity.Enum
{
/// <summary>
/// 菜单类型
/// </summary>
public enum EMenuType
{
/// <summary>
/// 内嵌菜单
/// </summary>
Menu = 1,
/// <summary>
/// 弹出菜单
/// </summary>
PopMenu = 2,
/// <summary>
/// 目录
/// </summary>
Directory = 3
}
/// <summary>
/// 地址类型
/// </summary>
public enum EUrlType
{
/// <summary>
/// 内部地址
/// </summary>
Inner = 1,
/// <summary>
/// 外部地址
/// </summary>
Outer = 2
}
/// <summary>
/// 功能类型
/// </summary>
public enum EFuncType
{
/// <summary>
/// 按钮
/// </summary>
Button = 1,
/// <summary>
/// 数据项
/// </summary>
DataItem = 2,
/// <summary>
/// 数据访问链接
/// </summary>
DataLink = 3
}
/// <summary>
/// 权限类型
/// </summary>
public enum ERightType
{
/// <summary>
/// 菜单权限
/// </summary>
Menu = 1,
/// <summary>
/// 功能权限
/// </summary>
Function = 2
}
/// <summary>
/// 前台用户类型
/// </summary>
public enum ELoginUserType
{
/// <summary>
/// 签约主账号
/// </summary>
SignedUser = 1,
/// <summary>
/// 子账号
/// </summary>
ChildUser = 2,
/// <summary>
/// 电商VIP用户
/// </summary>
EBusinessUser = 3,
}
/// <summary>
/// 后台用户类型
/// </summary>
public enum EBackLoginUserType
{
/// <summary>
/// 平台方
/// </summary>
Platform = 1,
/// <summary>
/// 物流商
/// </summary>
RegularBusAdmin = 2,
}
}
|
using System.Collections;
using System.Collections.Generic;
namespace NStandard.Collections
{
public class Flated<T> : IEnumerable<T>
{
private readonly List<IEnumerable<T>> list = new();
public void Add(T value)
{
list.Add(new[] { value });
}
public void Add(IEnumerable<T> value)
{
list.Add(value);
}
public void Add(IEnumerable<IEnumerable<T>> value)
{
foreach (var item in value)
{
list.Add(item);
}
}
private IEnumerable<T> GetItems()
{
foreach (var enumerable in list)
{
foreach (var item in enumerable)
{
yield return item;
}
}
}
public IEnumerator<T> GetEnumerator()
{
return GetItems().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
using System;
namespace RobX.Library.Communication
{
/// <summary>
/// Defines an interface for communication (network, hardware, etc.) client classes.
/// </summary>
public interface IClientInterface
{
# region Event Handlers
/// <summary>
/// This event is invoked after data is received from the remote client.
/// </summary>
event CommunicationEventHandler ReceivedData;
/// <summary>
/// This event is invoked after data was sent to the server.
/// </summary>
event CommunicationEventHandler SentData;
/// <summary>
/// This event is invoked when client is ready to send data to the remote client.
/// </summary>
event CommunicationEventHandler BeforeSendingData;
/// <summary>
/// This event is invoked when anything new happens in the client.
/// </summary>
event CommunicationStatusEventHandler StatusChanged;
/// <summary>
/// This event is invoked when an error occures in the connection with the remote client.
/// </summary>
event EventHandler ErrorOccured;
# endregion
# region Public Methods
/// <summary>
/// Send data to the remote client.
/// </summary>
/// <param name="data">Array of bytes to send.</param>
/// <param name="timeout">Timeout for send operation (in milliseconds).
/// The operation fails if sending the data could not start for the specified amount of time.
/// Value 0 indicates a blocking operation (no timeout).</param>
/// <returns>Returns true if successfully sent data; false indicates connection error.</returns>
bool SendData(byte[] data, int timeout = 1000);
/// <summary>
/// Receive data from the remote client.
/// </summary>
/// <param name="numOfBytes">Number of bytes to read.</param>
/// <param name="readBuffer">Buffer to put read data.</param>
/// <param name="checkAvailableData"><para>Check if data is available before trying to read data.</para>
/// <para>Warning: Setting this parameter to true results in non-blocking operation.</para></param>
/// <param name="timeout">Timeout for reading operation (in milliseconds).
/// The operation fails if reading the data could not start for the specified amount of time.
/// Value 0 indicates a blocking operation (no timeout).</param>
/// <returns>Returns true if successfully read any data; otherwise returns false.</returns>
bool ReceiveData(int numOfBytes, out byte[] readBuffer, bool checkAvailableData = false, int timeout = 1000);
# endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
public class PlayerModelIndex : MonoBehaviour
{
public Transform bugTailRef;
public Transform[] playerModelsByPlayerCam;
[Header("Player meshes by camera model")]
//These are the actual mesh renderer lists
public List<MeshRenderer> Player1CamMeshRenderers = new List<MeshRenderer>();
public List<MeshRenderer> Player2CamMeshRenderers = new List<MeshRenderer>();
public List<MeshRenderer> Player3CamMeshRenderers = new List<MeshRenderer>();
public List<MeshRenderer> Player4CamMeshRenderers = new List<MeshRenderer>();
[Header("Spit Sacs")]
public List<MeshRenderer> spitSacs1 = new List<MeshRenderer>();
public List<MeshRenderer> spitSacs2 = new List<MeshRenderer>();
public List<MeshRenderer> spitSacs3 = new List<MeshRenderer>();
public List<MeshRenderer> spitSacs4 = new List<MeshRenderer>();
public List<MeshRenderer> spitSacs5 = new List<MeshRenderer>();
[Header("DoTween Animations")]
public DOTweenAnimation ScaleAnimation;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace DPYM
{
public class SceneFactory
{
public DScene Produce(EUID productID)
{
return Produce((ESceneType) productID);
}
public DScene Produce(ESceneType sceneType)
{
return null;
}
public void Destroy(DScene elmt)
{
if (null != elmt) GameObject.Destroy(elmt.gameObject);
}
}
}
|
using System.Globalization;
using System.Linq;
namespace SnowBLL.Models.Geo
{
public class GeoPoint
{
public GeoPoint() { }
public GeoPoint(string pointsWithSeparator)
{
var values = pointsWithSeparator.TrimStart(' ').TrimEnd(' ').Split(' ').Where(ps => !string.IsNullOrEmpty(ps)).ToArray();
Lat = decimal.Parse(values[0], CultureInfo.InvariantCulture);
Lng = decimal.Parse(values[1], CultureInfo.InvariantCulture);
}
public decimal? Lat { get; set; }
public decimal? Lng { get; set; }
}
} |
using System;
using System.Globalization;
using System.Threading;
using System.Web.Mvc;
namespace KendoLanguage.Controllers
{
public class HomeController : Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
var culture = string.IsNullOrEmpty(requestContext.HttpContext.Request["culture"])
? "en-US"
: requestContext.HttpContext.Request["culture"];
Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
base.Initialize(requestContext);
}
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(DateTime.Now);
}
}
} |
namespace Merchello.UkFest.Web.Models.PublishedContent
{
using System.Web;
using Our.Umbraco.Ditto;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
/// <summary>
/// The category.
/// </summary>
public class CategoryNavItem : PublishedContentModel
{
/// <summary>
/// Initializes a new instance of the <see cref="CategoryNavItem"/> class.
/// </summary>
/// <param name="content">
/// The content.
/// </param>
public CategoryNavItem(IPublishedContent content)
: base(content)
{
}
/// <summary>
/// Gets or sets the image.
/// </summary>
public Image Image { get; set; }
}
} |
using EmailExtractor.DatabaseModel;
using MailKit;
using MailKit.Net.Imap;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using MimeKit;
using Newtonsoft.Json;
using System.IO;
using System.Text;
namespace EmailExtractor.ImapConnector
{
public class Connector : IConnector
{
private readonly ILogger<Connector> logger;
//private readonly ImapClient client;
private readonly string username;
private readonly string password;
private readonly int port;
private readonly bool imapSecure;
private readonly string server;
public string ServerKey => $"{username}@{server}";
public Connector(IConfiguration configuration, ILoggerFactory loggerFactory)
{
logger = loggerFactory.CreateLogger<Connector>();
logger.LogTrace($"Constructor Called");
logger.LogDebug($"Imap:Credentials : {configuration["Imap:Credentials"]}");
var userpass = configuration["Imap:Credentials"].Split("::", 2, StringSplitOptions.RemoveEmptyEntries);
username = userpass[0];
logger.LogDebug($"Imap:Credentials->Username : {username}");
password = userpass[1];
logger.LogDebug($"Imap:Credentials->Password : {password}");
server = configuration["Imap:Server"];
logger.LogDebug($"Imap:Server : {server}");
if (!bool.TryParse(configuration["Imap:SSL"], out imapSecure))
imapSecure = false;
if (!Int32.TryParse(configuration["Imap:Port"], out port))
port = imapSecure ? 993 : 143;
logger.LogDebug($"Imap:SSL : {imapSecure}");
logger.LogDebug($"Imap:Port : {port}");
}
private void Connect(ImapClient client)
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
if (!client.IsConnected)
{
logger.LogTrace($"Connecting");
client.Connect(server, port, imapSecure);
logger.LogInformation($"Connected");
}
if (!client.IsAuthenticated)
{
logger.LogTrace($"Authenticating");
client.Authenticate(username, password);
logger.LogInformation($"Authenticated");
}
}
public IEnumerable<IMailFolder> Folders(IMailFolder rootFolder, bool recursive)
=> Folders(rootFolder, recursive, null);
private IEnumerable<IMailFolder> Folders(IMailFolder rootFolder, bool recursive, ImapClient client)
{
if (client == null)
{
client = new ImapClient();
Connect(client);
}
IMailFolder parentFolder = rootFolder ?? client.GetFolder(client.PersonalNamespaces[0]);
foreach (var folder in parentFolder.GetSubfolders(false))
{
logger.LogTrace($"return folder: {folder.FullName}");
yield return folder;
if (recursive)
{
var internalFolders = Folders(folder, recursive, client);
foreach (var internalFolder in internalFolders)
{
logger.LogTrace($"return folder: {internalFolder.FullName}");
yield return internalFolder;
}
}
}
}
public List<MailItem> ExtractMailItems(IMailFolder folder, int pageSize, int page, List<uint> existingUids)
{
try
{
using (var client = new ImapClient())
{
Connect(client);
if (!folder.IsOpen)
{
logger.LogTrace("Open Folder");
folder.Open(FolderAccess.ReadOnly);
}
logger.LogInformation($"Fetch summaries [{folder.FullName}] - \tPage: {page} - Page Size: {pageSize}");
var summaries = folder.Fetch(page * pageSize, (page + 1) * pageSize - 1, MessageSummaryItems.UniqueId);
logger.LogInformation($"Got summaries [{folder.FullName}] - Count: {summaries.Count}");
if (summaries.Count == 0)
return null;
var result = new List<MailItem>();
logger.LogTrace("Extract Mail Addresses");
foreach (var summary in summaries)
{
if (!existingUids.Contains(summary.UniqueId.Id))
{
var message = folder.GetMessage(summary.UniqueId);
result.AddRange(CreateMailItems(logger, message, this, folder, summary.UniqueId));
}
}
if (folder.IsOpen)
{
logger.LogTrace("Close Folder");
folder.Close(false);
}
return result;
}
}
catch (Exception e)
{
logger.LogError(e, $"Error in folder: {folder.FullName} \r\n {e.Message}");
return null;
}
}
private static IEnumerable<MailItem> CreateMailItems(ILogger logger, MimeMessage message, IConnector connector, IMailFolder folder, UniqueId uniqueId)
{
string messageEml = null;
try
{
var stream = new MemoryStream();
message.WriteTo(stream);
stream.Position = 0;
//var reader = new StreamReader(stream,Encoding.UTF8, true);
var reader = new StreamReader(stream);
messageEml = reader.ReadToEnd();
}
catch (Exception e)
{
logger.LogError(e, "Serialization failed");
}
DateTimeOffset date = DateTimeOffset.MinValue;
try
{
date = message.Date;
}
catch
{
}
foreach (var address in message.From)
{
if (address is MailboxAddress mailboxAddress)
yield return MailItem.CreateMailItem(mailboxAddress.Address, mailboxAddress.Name,
connector.ServerKey, folder.FullName, uniqueId.Id, messageEml, date);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CheckAchievement : MonoBehaviour {
public GameObject[] panelPic;
public GameObject bonusPic;
// Use this for initialization
void Start ()
{
int totalAchievement = 0;
for(int i=0; i<panelPic.Length; i++)
{
var tempCount = 0;
for(int j=0; j<PlayerPrefsX.GetIntArray("achievementLevel" + (i+1)).Length; j++)
{
if(PlayerPrefsX.GetIntArray("achievementLevel" + (i+1))[j] == 1)
{
tempCount++;
}
}
if(tempCount == PlayerPrefsX.GetIntArray("achievementLevel" + (i+1)).Length) //Achievement complete 100%
{
panelPic[i].transform.GetChild(0).GetComponent<Image>().overrideSprite = Resources.Load<Sprite>("Picture/pic" + i);
panelPic[i].transform.GetChild(2).gameObject.SetActive(false);
panelPic[i].transform.GetChild(3).gameObject.SetActive(false);
totalAchievement++;
}
else
{
panelPic[i].transform.GetChild(2).GetComponent<Text>().text = tempCount.ToString();
}
}
if(totalAchievement == 5)
{
bonusPic.transform.GetChild(0).GetComponent<Image>().overrideSprite = Resources.Load<Sprite>("Picture/pic5");
bonusPic.transform.GetChild(2).gameObject.SetActive(false);
}
}
// Update is called once per frame
void Update () {
}
}
|
namespace MvcApp.Web.ViewModels
{
using System.Collections.Generic;
using System.Text;
public class AllViewModel
{
public IEnumerable<CategoryViewModel> Categories { get; set; }
public override string ToString()
{
StringBuilder builder = new StringBuilder();
foreach (CategoryViewModel categoryViewModel in this.Categories)
{
builder.Append(categoryViewModel);
}
return builder.ToString();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.Runtime.CompilerServices;
public class Workbench2 : MonoBehaviour
{
public GameObject craftScreen;
public Canvas insuffMats;
public GameObject pressSpace;
public GunpowderBool gunpowderBool;
public RocketBool rocketBool;
public GameObject fireworks;
private float cooldownsMats;
private int fireWorksActive;
private float spaceActive;
private void Start()
{
fireworks.SetActive(false);
craftScreen.SetActive(false);
pressSpace.SetActive(true);
fireWorksActive = 0;
spaceActive = 0;
}
void OnTriggerStay2D(Collider2D collision)
{
//If you're lacking both materials
if (collision.gameObject.tag == "Player" && gunpowderBool.isActive == true && rocketBool.isActive == true)
{
insuffMats.gameObject.SetActive(true);
cooldownsMats = 2;
Debug.Log("Insufficient Materials");
}
//If you have one material
if (collision.gameObject.tag == "Player" && gunpowderBool.isActive == true && rocketBool.isActive == false)
{
insuffMats.gameObject.SetActive(true);
cooldownsMats = 2;
Debug.Log("Insufficient Materials");
}
//If you have one material
if (collision.gameObject.tag == "Player" && gunpowderBool.isActive == false && rocketBool.isActive == true)
{
insuffMats.gameObject.SetActive(true);
cooldownsMats = 2;
Debug.Log("Insufficient Materials");
}
//if you have both materials
if (collision.gameObject.tag == "Player" && gunpowderBool.isActive == false && rocketBool.isActive == false && fireWorksActive == 0)
{
craftScreen.SetActive(true);
insuffMats.gameObject.SetActive(false);
if (Input.GetKeyDown(KeyCode.E))
{
fireWorksActive++;
//fireworks.fireworksCraft = true;
craftScreen.SetActive(false);
pressSpace.SetActive(true);
spaceActive = 5;
Debug.Log("CraftClick done");
}
Debug.Log("CraftScreen active");
}
}
public void CraftClick()
{
fireworks.SetActive(true);
craftScreen.SetActive(false);
pressSpace.SetActive(true);
spaceActive = 10;
Debug.Log("CraftClick done");
}
private void Update()
{
cooldownsMats = cooldownsMats - Time.deltaTime;
spaceActive = spaceActive - Time.deltaTime;
if (spaceActive <= 0)
{
pressSpace.SetActive(false);
}
if (cooldownsMats <= 0)
{
insuffMats.gameObject.SetActive(false);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace DesktopInterface
{
public class ClippingPlaneDisplayButton : IButtonScript
{
private static bool MultiClipPlaneactivated = true;
public void Awake()
{
button = GetComponent<Button>();
initializeClickEvent();
if(MultiClipPlaneactivated == true)
{
GetComponent<Image>().color = Color.green;
}
}
public override void Execute()
{
if (MultiClipPlaneactivated == false)
{
Shader.EnableKeyword("FIXED_CLIPPING_PLANE_1");
Shader.EnableKeyword("FIXED_CLIPPING_PLANE_2");
Shader.EnableKeyword("FIXED_CLIPPING_PLANE_3");
Shader.EnableKeyword("FIXED_CLIPPING_PLANE_4");
Shader.EnableKeyword("FIXED_CLIPPING_PLANE_5");
Shader.EnableKeyword("FIXED_CLIPPING_PLANE_6");
Shader.EnableKeyword("FIXED_CLIPPING_PLANE_7");
Shader.EnableKeyword("FIXED_CLIPPING_PLANE_8");
Shader.EnableKeyword("FIXED_CLIPPING_PLANE_9");
Shader.EnableKeyword("FIXED_CLIPPING_PLANE_10");
MultiClipPlaneactivated = true;
GetComponent<Image>().color = Color.green;
}
else
{
Shader.DisableKeyword("FIXED_CLIPPING_PLANE_1");
Shader.DisableKeyword("FIXED_CLIPPING_PLANE_2");
Shader.DisableKeyword("FIXED_CLIPPING_PLANE_3");
Shader.DisableKeyword("FIXED_CLIPPING_PLANE_4");
Shader.DisableKeyword("FIXED_CLIPPING_PLANE_5");
Shader.DisableKeyword("FIXED_CLIPPING_PLANE_6");
Shader.DisableKeyword("FIXED_CLIPPING_PLANE_7");
Shader.DisableKeyword("FIXED_CLIPPING_PLANE_8");
Shader.DisableKeyword("FIXED_CLIPPING_PLANE_9");
Shader.DisableKeyword("FIXED_CLIPPING_PLANE_10");
MultiClipPlaneactivated = false;
GetComponent<Image>().color = Color.white;
}
}
}
} |
using BattleEngine.Actors.Units;
using BattleEngine.Engine;
using BattleEngine.Utils;
using Common.Composite;
namespace BattleEngine.Components.Units
{
public class UnitMoveComponent : BattleComponent
{
private Vector<Component> _temp = new Vector<Component>();
private BattleTransform _moveTo;
public UnitMoveComponent()
{
}
override public bool needRemove
{
get { return false; }
}
public double distancePerTick
{
get
{
double currentDistancePerTick = ((BattleUnit)target).info.Speed;
_temp.length = 0;
GetComponents(typeof(IMoveModifier), false, _temp);
foreach (IMoveModifier item in _temp)
{
currentDistancePerTick *= item.moveModifierPercent;
}
var player = engine.players.getPlayer(target.ownerId);
if (player != null)
{
currentDistancePerTick = player.modifier.calculate(Modifiers.ModifierType.UNITS_SPEED, currentDistancePerTick, ((BattleUnit)target).unitId);
}
return currentDistancePerTick;
}
}
public BattleTransform targetBuilding
{
get { return _moveTo; }
}
public bool moveCompleted
{
get { return target.transform.positionDistance(_moveTo) <= 0; }
}
public void moveTo(BattleTransform transform)
{
_moveTo = transform;
}
public bool updatePosition(int deltaTick)
{
var distance = distancePerTick * deltaTick;
var fromX = target.transform.x;
var fromY = target.transform.y;
var toX = _moveTo.x;
var toY = _moveTo.y;
var totalDistance = Math2.distance(fromX, fromY, toX, toY);
if (totalDistance == 0)
{
return false;
}
if (distance > totalDistance)
{
distance = totalDistance;
}
var ratio = distance / totalDistance;
var newX = Math2.interpolate(fromX, toX, ratio);
var newY = Math2.interpolate(fromY, toY, ratio);
target.transform.setPosition(newX, newY);
return newX != fromX || newY != fromY;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MoneyWeb.Contexts;
using MoneyWeb.Extensions;
using MoneyWeb.Models;
using MoneyWeb.ViewModels;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MoneyWeb.Api
{
public class EstruturaApiController : Controller
{
private readonly MoneyDbContext _db;
public EstruturaApiController(MoneyDbContext db)
{
this._db = db;
}
[HttpPost]
public JsonResult GetList([FromBody] EstruturaFilterModel filter)
{
IQueryable<ClassificacaoModel> queryClassificacao = _db.Classificacao;
if (!string.IsNullOrEmpty(filter.Nome))
queryClassificacao = queryClassificacao.Where(s => s.Nome.Contains(filter.Nome));
queryClassificacao = queryClassificacao.OrderBy(s => s.Ordem);
IQueryable<CategoriaModel> queryCategoria = _db.Categoria.Include(p => p.Classificacao);
if (!string.IsNullOrEmpty(filter.Nome))
queryCategoria = queryCategoria.Where(s => s.Nome.Contains(filter.Nome));
queryCategoria = queryCategoria.OrderBy(s => s.Ordem);
IQueryable<ItemModel> queryItem = _db.Item.Include(p => p.Categoria);
if (!string.IsNullOrEmpty(filter.Nome))
queryItem = queryItem.Where(s => s.Nome.Contains(filter.Nome));
queryCategoria = queryCategoria.OrderBy(s => s.Ordem);
EstruturaListModel list = new EstruturaListModel()
{
ListClassificacao = queryClassificacao.ToList(),
ListCategoria = queryCategoria.ToList(),
ListItem = queryItem.ToList()
};
var json = JsonConvert.SerializeObject(list);
return Json(json);
}
}
}
|
using System;
public class GClass13
{
private int int_0;
private bool bool_0;
private int int_1;
private long long_0;
private GClass18 gclass18_0;
private GClass15 gclass15_0;
public GClass13(int int_2, bool bool_1)
{
if (int_2 == -1)
{
int_2 = 6;
}
else if (int_2 < 0 || int_2 > 9)
{
throw new ArgumentOutOfRangeException("level");
}
this.gclass18_0 = new GClass18();
this.gclass15_0 = new GClass15(this.gclass18_0);
this.bool_0 = bool_1;
this.method_7(GEnum0.const_0);
this.method_6(int_2);
this.method_0();
}
public void method_0()
{
this.int_1 = (this.bool_0 ? 16 : 0);
this.long_0 = 0L;
this.gclass18_0.method_0();
this.gclass15_0.method_3();
}
public void method_1()
{
this.int_1 |= 4;
}
public void method_2()
{
this.int_1 |= 12;
}
public bool method_3()
{
return this.int_1 == 30 && this.gclass18_0.method_7();
}
public bool method_4()
{
return this.gclass15_0.method_2();
}
public void method_5(byte[] byte_0, int int_2, int int_3)
{
if ((this.int_1 & 8) != 0)
{
throw new InvalidOperationException("Finish() already called");
}
this.gclass15_0.method_1(byte_0, int_2, int_3);
}
public void method_6(int int_2)
{
if (int_2 == -1)
{
int_2 = 6;
}
else if (int_2 < 0 || int_2 > 9)
{
throw new ArgumentOutOfRangeException("level");
}
if (this.int_0 != int_2)
{
this.int_0 = int_2;
this.gclass15_0.method_7(int_2);
}
}
public void method_7(GEnum0 genum0_0)
{
this.gclass15_0.method_6(genum0_0);
}
public int method_8(byte[] byte_0, int int_2, int int_3)
{
int num = int_3;
if (this.int_1 == 127)
{
throw new InvalidOperationException("Deflater closed");
}
if (this.int_1 < 16)
{
int num2 = 30720;
int num3 = this.int_0 - 1 >> 1;
if (num3 < 0 || num3 > 3)
{
num3 = 3;
}
num2 |= num3 << 6;
if ((this.int_1 & 1) != 0)
{
num2 |= 32;
}
num2 += 31 - num2 % 31;
this.gclass18_0.method_6(num2);
if ((this.int_1 & 1) != 0)
{
int num4 = this.gclass15_0.method_5();
this.gclass15_0.method_4();
this.gclass18_0.method_6(num4 >> 16);
this.gclass18_0.method_6(num4 & 65535);
}
this.int_1 = (16 | (this.int_1 & 12));
}
while (true)
{
int num5 = this.gclass18_0.method_8(byte_0, int_2, int_3);
int_2 += num5;
this.long_0 += (long)num5;
int_3 -= num5;
if (int_3 == 0 || this.int_1 == 30)
{
goto IL_1F0;
}
if (!this.gclass15_0.method_0((this.int_1 & 4) != 0, (this.int_1 & 8) != 0))
{
if (this.int_1 == 16)
{
break;
}
if (this.int_1 == 20)
{
if (this.int_0 != 0)
{
for (int i = 8 + (-this.gclass18_0.method_3() & 7); i > 0; i -= 10)
{
this.gclass18_0.method_5(2, 10);
}
}
this.int_1 = 16;
}
else if (this.int_1 == 28)
{
this.gclass18_0.method_4();
if (!this.bool_0)
{
int num6 = this.gclass15_0.method_5();
this.gclass18_0.method_6(num6 >> 16);
this.gclass18_0.method_6(num6 & 65535);
}
this.int_1 = 30;
}
}
}
return num - int_3;
IL_1F0:
return num - int_3;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace RSS.WebApi.DTOs
{
public class SupplierDTO
{
[Key]
public Guid Id { get; set; }
[Required(ErrorMessage = "O campo {0} é obrigatório")]
[StringLength(100, ErrorMessage = "o campo {0} precisa ter entre {2} e {1}", MinimumLength = 2)]
public string Name { get; set; }
[Required(ErrorMessage = "O campo {0} é obrigatório")]
[StringLength(14, ErrorMessage = "o campo {0} precisa ter entre {2} e {1}", MinimumLength = 11)]
public string IdentificationDocument { get; set; }
public int SupplierType { get; set; }
public bool Active { get; set; }
/*EF Relations*/
public AddressDTO Address { get; set; }
public IEnumerable<ProductDTO> Products { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EBS.Domain.Entity
{
public class StoreInventoryBatchUpdate:BaseEntity
{
//public StoreInventoryBatchUpdate(int id, int quantity)
//{
// this.Id = id;
// this.Quantity = quantity;
//}
//public StoreInventoryBatchUpdate(int id, int quantity,int sourceQuantity):this(id,quantity)
//{
// this.SourceQuantity = sourceQuantity;
//}
/// <summary>
/// 新库存数
/// </summary>
public int Quantity { get; set; }
/// <summary>
/// 原库存数
/// </summary>
public int SourceQuantity { get; set; }
}
}
|
using System;
using Windows.UI.Popups;
namespace Pane
{
public class Loaf
{
// Variables for name and database key
private string recipeName;
private int key;
// Ingredient variables
private float flourWeight;
private float waterWeight;
private float saltWeight;
private float otherDryWeight;
private float otherWetWeight;
private float ratio;
private float saltPercent;
private float otherDryPercent;
// Totals variables
private float totalWeight;
private float totalDryWeight;
private float totalWetWeight;
// Keep track of notes:
private string notes = "";
//Track priority of calculation (to prioritize ratio or weights)
private bool _calculateByRatio;
public float FlourWeight { get => flourWeight; set => flourWeight = value; }
public float TotalWeight { get => totalWeight; set => totalWeight = value; }
public float WaterWeight { get => waterWeight; set => waterWeight = value; }
public float SaltWeight { get => saltWeight; set => saltWeight = value; }
public float OtherDryWeight { get => otherDryWeight; set => otherDryWeight = value; }
public float OtherWetWeight { get => otherWetWeight; set => otherWetWeight = value; }
public float Ratio { get => ratio; set => ratio = value; }
public float SaltPercent { get => saltPercent; set => saltPercent = value; }
public float OtherDryPercent { get => otherDryPercent; set => otherDryPercent = value; }
public string Notes { get => notes; set => notes = value; }
public float TotalDryWeight { get => totalDryWeight; set => totalDryWeight = value; }
public float TotalWetWeight { get => totalWetWeight; set => totalWetWeight = value; }
public string RecipeName { get => recipeName; set => recipeName = value; }
public int Key { get => key; set => key = value; }
public bool CalculateByRatio { get => _calculateByRatio; set => _calculateByRatio = value; }
// Basic constructor
public Loaf()
{
//Set empty loaf
Key = -1;
RecipeName = "None";
TotalWeight = 0.00F;
FlourWeight = 0.00F;
WaterWeight = 0.00F;
SaltWeight = 0.00F;
OtherDryWeight = 0.00F;
OtherWetWeight = 0.00F;
Ratio = 0.00F;
SaltPercent = 0.00F;
OtherDryPercent = 0.00F;
notes = "";
CalculateByRatio = true;
}
// Normal constructor
public Loaf(string recipeName, float flourWeight, float totalWeight, float waterWeight,
float saltWeight, float otherDryWeight, float otherWetWeight, float ratio,
float saltPercent, float otherDryPercent, string notes, bool calculateByRatio)
{
if (Key < 0)
{
// This only gets set when added to the database.
Key = -1;
}
RecipeName = recipeName;
FlourWeight = flourWeight;
TotalWeight = totalWeight;
WaterWeight = waterWeight;
SaltWeight = saltWeight;
OtherDryWeight = otherDryWeight;
OtherWetWeight = otherWetWeight;
Ratio = ratio;
SaltPercent = saltPercent;
OtherDryPercent = otherDryPercent;
Notes = notes;
CalculateByRatio = calculateByRatio;
this.InitializeLoaf();
}
//Complete constructor
public Loaf(int key, string recipeName, float flourWeight, float totalWeight, float waterWeight,
float saltWeight, float otherDryWeight, float otherWetWeight, float ratio, float saltPercent,
float otherDryPercent, string notes, bool calculateByRatio)
{
if (Key < 0)
{
// This only gets set when added to the database.
Key = -1;
}
else
{
// Key is fetched from db
Key = key;
}
RecipeName = recipeName;
FlourWeight = flourWeight;
TotalWeight = totalWeight;
WaterWeight = waterWeight;
SaltWeight = saltWeight;
OtherDryWeight = otherDryWeight;
OtherWetWeight = otherWetWeight;
Ratio = ratio;
SaltPercent = saltPercent;
OtherDryPercent = otherDryPercent;
Notes = notes;
CalculateByRatio = calculateByRatio;
this.InitializeLoaf();
}
public void InitializeLoaf()
{
// Check priority of calculation
// Prioritise ratio over weight
if (CalculateByRatio == true)
{
if (this.IsValidRatios())
{
CalculateWeightsFromRatios();
}
else if (this.IsValidWeights())
{
CalculateRatiosFromWeights();
}
else
{
var messageDialog = new MessageDialog("Invalid weights or ratios.");
}
}
// Prioritise weight over ratio
else
{
if (this.IsValidWeights())
{
CalculateRatiosFromWeights();
}
else if (this.IsValidRatios())
{
CalculateWeightsFromRatios();
}
else
{
//var messageDialog = new MessageDialog("Invalid weights or ratios.");
}
}
}
public void CalculateDryWeight()
{
this.TotalDryWeight = FlourWeight + SaltWeight + OtherDryWeight;
}
public void CalculateWetWeight()
{
this.TotalWetWeight = WaterWeight + OtherWetWeight;
}
public void CalculateTotalWeight()
{
this.CalculateDryWeight();
this.CalculateWetWeight();
this.TotalWeight = TotalDryWeight + TotalWetWeight;
}
public void CalculateRatiosFromWeights()
{
// Calculate values from weights
this.CalculateTotalWeight();
//** Baking note **
// Bakers measure hydration as a ratio of dry to wet ingredients
// Usually flour & salt to water
this.Ratio = (this.FlourWeight * 100) / this.TotalWeight;
//If salt weight is set
if (this.SaltWeight > 0)
{
this.SaltPercent = (this.SaltWeight / this.FlourWeight) * 100;
}
else if (this.SaltPercent > 0)
{
this.SaltWeight = this.FlourWeight * (this.SaltPercent / 100);
}
}
public void CalculateWeightsFromRatios()
{
if (this.TotalWeight == 0 || this.TotalWeight < this.WaterWeight)
{
//Error weights not set!
throw new Exception();
}
if (saltPercent > 0)
{
// Calculate salt by ratio (ratio has been set)
this.FlourWeight = this.TotalWeight * (this.Ratio / 100);
this.SaltWeight = this.FlourWeight * (this.SaltPercent / 100);
if (this.OtherDryPercent > 0)
{
this.OtherDryWeight = this.FlourWeight / (this.OtherDryPercent / 100);
}
this.TotalDryWeight = this.FlourWeight + this.SaltWeight + this.OtherDryWeight;
this.TotalWetWeight = this.TotalWeight - this.TotalDryWeight;
this.WaterWeight = this.totalWetWeight - this.OtherWetWeight;
}
else
{
// Calculate salt by weight (ratio not set)
this.FlourWeight = this.TotalWeight * (this.Ratio / 100);
this.TotalDryWeight = this.FlourWeight + this.SaltWeight + this.OtherDryWeight;
this.TotalWetWeight = this.TotalWeight - this.TotalDryWeight;
this.WaterWeight = this.totalWetWeight - this.OtherWetWeight;
this.SaltPercent = (this.SaltWeight / this.FlourWeight) * 100;
}
}
public bool IsValidWeights()
{
//Check if weights can calculate a ratio. Consider using exceptions to
//return more specific information if values are invalid
if (this.FlourWeight > 0.00 &&
(this.WaterWeight > 0.00 || (this.ratio > 0 && this.ratio < 100)))
{
return true;
}
else if (this.FlourWeight > 0.00 && this.TotalWeight > this.FlourWeight)
{
return true;
}
else return false;
}
public bool IsValidRatios()
{
//Check if given values can calculate weights. Consider using exceptions to
//return more specific information if values are invalid
//
if ((this.TotalWeight > 0 || this.FlourWeight > 0) && (this.Ratio > 0.00 && this.Ratio < 100))
{
return true;
}
else return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Pe.Stracon.Politicas.Aplicacion.Core.ServiceContract;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General;
using Pe.Stracon.SGC.Aplicacion.Adapter.Contractual;
using Pe.Stracon.SGC.Aplicacion.Core.Base;
using Pe.Stracon.SGC.Aplicacion.Core.Message;
using Pe.Stracon.SGC.Aplicacion.Service.Base;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual;
using Pe.Stracon.SGC.Application.Core.ServiceContract;
using Pe.Stracon.SGC.Cross.Core.Base;
using Pe.Stracon.SGC.Cross.Core.Exception;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.Core.QueryContract.Contractual;
using System.Transactions;
using Pe.Stracon.SGC.Infraestructura.Core.CommandContract.Contractual;
using Pe.Stracon.SGC.Infraestructura.Core.Context;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
namespace Pe.Stracon.SGC.Aplicacion.Service.Contractual
{
/// <summary>
/// Servicio que representa las actividades de Flujo Aprobacion
/// </summary>
/// <remarks>
/// Creación: GMD 20150507 <br />
/// Modificación: <br />
/// </remarks>
public class FlujoAprobacionService : GenericService, IFlujoAprobacionService
{
#region Propiedades
/// <summary>
/// Repositorio de manejo de Flujo Aprobacion Logic
/// </summary>
public IFlujoAprobacionLogicRepository flujoAprobacionLogicRepository { get; set; }
/// <summary>
/// Repositorio de manejo de Flujo Aprobacion Entity
/// </summary>
public IFlujoAprobacionEntityRepository flujoAprobacionEntityRepository { get; set; }
/// <summary>
/// Repositorio de manejo de Flujo Aprobacion Tipo de Servicio Entity
/// </summary>
public IFlujoAprobacionTipoServicioEntityRepository flujoAprobacionTipoServicioEntityRepository { get; set; }
/// <summary>
/// Repositorio de manejo de Flujo Aprobacion Tipo de Contrato Entity
/// </summary>
public IFlujoAprobacionTipoContratoEntityRepository flujoAprobacionTipoContratoEntityRepository { get; set; }
/// <summary>
/// Repositorio de manejo de Flujo Aprobacion Estadio Entity
/// </summary>
public IFlujoAprobacionEstadioEntityRepository flujoAprobacionEstadioEntityRepository { get; set; }
/// <summary>
/// Servicio de manejo de Unidad Operativa
/// </summary>
public IUnidadOperativaService unidadOperativaService { get; set; }
/// <summary>
/// Servicio de manejo de parametro valor
/// </summary>
public IPoliticaService politicaService { get; set; }
/// <summary>
///
/// </summary>
public IFlujoAprobacionParticipanteEntityRepository flujoAprobacionParticipanteEntityRepository { get; set; }
/// <summary>
/// Servicio de trabajador
/// </summary>
public ITrabajadorService trabajadorService { get; set; }
/// <summary>
/// Interface para obtener el entorno de la aplicación.
/// </summary>
public IEntornoActualAplicacion entornoActualAplicacion { get; set; }
#endregion
/// <summary>
/// Busca Bandeja Flujo Aprobacion
/// </summary>
/// <param name="filtro">Filtro de Flujo de Aprobación</param>
/// <returns>Registros de flujo aprobacion</returns>
public ProcessResult<List<FlujoAprobacionResponse>> BuscarBandejaFlujoAprobacion(FlujoAprobacionRequest filtro)
{
ProcessResult<List<FlujoAprobacionResponse>> resultado = new ProcessResult<List<FlujoAprobacionResponse>>();
List<UnidadOperativaResponse> unidadOperativa = null;
List<CodigoValorResponse> tipoContrato = null;
List<CodigoValorResponse> formaContrato = null;
var listaTrabajador = trabajadorService.BuscarTrabajador(new TrabajadorRequest()).Result;
if (filtro.IndicadorObtenerDescripcion)
{
unidadOperativa = unidadOperativaService.BuscarUnidadOperativa(new FiltroUnidadOperativa() { Nivel = "03" }).Result;
tipoContrato = politicaService.ListarTipoContrato().Result.OrderBy(item => item.Valor.ToString()).ToList();
formaContrato = politicaService.ListarFormaContrato().Result;
}
try
{
Guid? CodigoFlujoAprobacion = (filtro.CodigoFlujoAprobacion != null && filtro.CodigoFlujoAprobacion != "") ? new Guid(filtro.CodigoFlujoAprobacion) : (Guid?)null;
Guid? CodigoUnidadOperativa = (filtro.CodigoUnidadOperativa != null && filtro.CodigoUnidadOperativa != "") ? new Guid(filtro.CodigoUnidadOperativa) : (Guid?)null;
List<FlujoAprobacionLogic> listado = flujoAprobacionLogicRepository.BuscarBandejaFlujoAprobacion(
CodigoFlujoAprobacion,
CodigoUnidadOperativa,
filtro.IndicadorAplicaMontoMinimo,
filtro.EstadoRegistro
);
resultado.Result = new List<FlujoAprobacionResponse>();
//Detalle Flujo Aprobación Tipo de Contrato
List<FlujoAprobacionTipoContratoLogic> listadoFlujoAprobacionTipoServicio = flujoAprobacionLogicRepository.BuscarFlujoAprobacionTipoContrato(
null,
null,
null,//filtro.ListaTipoServicio == null ? null : filtro.ListaTipoServicio.Count == 1 ? filtro.ListaTipoServicio[0] : null,
filtro.EstadoRegistro
);
foreach (var registro in listado)
{
var objlistadoFlujoAprobacionTipoServicio = listadoFlujoAprobacionTipoServicio.FindAll(p => p.CodigoFlujoAprobacion == registro.CodigoFlujoAprobacion);
if (filtro.ListaTipoServicio != null)
{
if (!filtro.ListaTipoServicio.Any(itemAny => objlistadoFlujoAprobacionTipoServicio.Any(itemWhere => itemWhere.CodigoTipoContrato == itemAny)))
{
continue;
}
}
var flujoAprobacion = FlujoAprobacionAdapter.ObtenerFlujoAprobacion(registro, objlistadoFlujoAprobacionTipoServicio, unidadOperativa, tipoContrato);
var primerFirmante = listaTrabajador.Find(p => p.CodigoTrabajador == registro.CodigoPrimerFirmante.Value.ToString());
if (primerFirmante != null)
{
flujoAprobacion.NombrePrimerFirmante = primerFirmante.NombreCompleto;
}
if (registro.CodigoSegundoFirmante != null)
{
var segundoFirmante = listaTrabajador.Find(p => p.CodigoTrabajador == registro.CodigoSegundoFirmante.Value.ToString());
if (segundoFirmante != null)
{
flujoAprobacion.NombreSegundoFirmante = segundoFirmante.NombreCompleto;
}
}
resultado.Result.Add(flujoAprobacion);
}
resultado.Result = (from item in resultado.Result
orderby item.DescripcionUnidadOperativa, item.IndicadorAplicaMontoMinimo, item.DescripcionTipoContrato ascending
select item).ToList();
}
catch (Exception e)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(e);
}
return resultado;
}
/// <summary>
/// Busca Bandeja Flujo Aprobacion participante
/// </summary>
/// <param name="filtro">filtro</param>
/// <returns>Registros de flujo aprobacion participante</returns>
public ProcessResult<List<FlujoAprobacionParticipanteResponse>> BuscarFlujoAprobacionParticipante(FlujoAprobacionRequest filtro)
{
ProcessResult<List<FlujoAprobacionParticipanteResponse>> resultado = new ProcessResult<List<FlujoAprobacionParticipanteResponse>>();
try
{
resultado.Result = new List<FlujoAprobacionParticipanteResponse>();
var lstUOs = flujoAprobacionLogicRepository.BuscarFlujoAprobacionParticipante(new Guid(filtro.CodigoFlujoAprobacion));
foreach (var item in lstUOs)
{
resultado.Result.Add(FlujoAprobacionParticipanteAdapter.ObtenerFlujoAprobacionParticipanteResponse(item));
}
}
catch (Exception ex)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<ContratoService>(ex);
}
return resultado;
}
/// <summary>
/// Registra / Edita Flujo Aprobacion
/// </summary>
/// <param name="data"></param>
/// <returns>Indicador con el resultado de la operación</returns>
public ProcessResult<FlujoAprobacionRequest> RegistrarFlujoAprobacion(FlujoAprobacionRequest data)
{
ProcessResult<FlujoAprobacionRequest> resultado = new ProcessResult<FlujoAprobacionRequest>();
try
{
FlujoAprobacionEntity entidad = FlujoAprobacionAdapter.RegistrarFlujoAprobacion(data);
//var resultadoRepetido = flujoAprobacionLogicRepository.RepiteFlujoAprobacion(
// new Guid(data.CodigoUnidadOperativa),
// data.CodigoFormaEdicion,
// data.CodigoTipoServicio,
// data.CodigoTipoRequerimiento
//);
bool existeRepetido = false; //resultadoRepetido.Any(e => e.CodigoFlujoAprobacion != entidad.CodigoFlujoAprobacion);
if (existeRepetido)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(MensajesSistema.FlujoAprobacionExiste);
}
else
{
if (data.CodigoFlujoAprobacion == null)
{
flujoAprobacionEntityRepository.Insertar(entidad);
flujoAprobacionEntityRepository.GuardarCambios();
foreach (var item in data.ListaTipoServicio)
{
//FlujoAprobacionTipoServicioEntity entidadFlujoAprobacionTipoServicio = new FlujoAprobacionTipoServicioEntity();
//entidadFlujoAprobacionTipoServicio.CodigoFlujoAprobacion = entidad.CodigoFlujoAprobacion;
//entidadFlujoAprobacionTipoServicio.CodigoFlujoAprobacionTipoServicio = Guid.NewGuid();
//entidadFlujoAprobacionTipoServicio.CodigoTipoServicio = item;
//flujoAprobacionTipoServicioEntityRepository.Insertar(entidadFlujoAprobacionTipoServicio);
//flujoAprobacionTipoServicioEntityRepository.GuardarCambios();
FlujoAprobacionTipoContratoEntity entidadFlujoAprobacionTipoContrato = new FlujoAprobacionTipoContratoEntity();
entidadFlujoAprobacionTipoContrato.CodigoFlujoAprobacion = entidad.CodigoFlujoAprobacion;
entidadFlujoAprobacionTipoContrato.CodigoFlujoAprobacionTipoContrato = Guid.NewGuid();
entidadFlujoAprobacionTipoContrato.CodigoTipoContrato = item;
flujoAprobacionTipoContratoEntityRepository.Insertar(entidadFlujoAprobacionTipoContrato);
flujoAprobacionTipoContratoEntityRepository.GuardarCambios();
}
var datosDefecto = new FlujoAprobacionEstadioEntity()
{
CodigoFlujoAprobacionEstadio = Guid.NewGuid(),
CodigoFlujoAprobacion = entidad.CodigoFlujoAprobacion,
Orden = 1,
Descripcion = "Edición",
TiempoAtencion = 1,
HorasAtencion = 0,
IndicadorVersionOficial = false,
IndicadorPermiteCarga = false,
IndicadorNumeroContrato = false,
EstadoRegistro = "1"
};
flujoAprobacionEstadioEntityRepository.Insertar(datosDefecto);
//flujoAprobacionEstadioEntityRepository.GuardarCambios();
}
else
{
var entidadSincronizar = flujoAprobacionEntityRepository.GetById(entidad.CodigoFlujoAprobacion);
entidadSincronizar.CodigoFlujoAprobacion = entidad.CodigoFlujoAprobacion;
entidadSincronizar.CodigoUnidadOperativa = entidad.CodigoUnidadOperativa;
entidadSincronizar.CodigoPrimerFirmante = entidad.CodigoPrimerFirmante;
entidadSincronizar.CodigoPrimerFirmanteOriginal = entidad.CodigoPrimerFirmante;
if (entidad.CodigoSegundoFirmante != null)
{
entidadSincronizar.CodigoSegundoFirmante = entidad.CodigoSegundoFirmante;
entidadSincronizar.CodigoSegundoFirmanteOriginal = entidad.CodigoSegundoFirmante;
}
entidadSincronizar.CodigoPrimerFirmanteVinculada = entidad.CodigoPrimerFirmanteVinculada;
entidadSincronizar.CodigoSegundoFirmanteVinculada = entidad.CodigoSegundoFirmanteVinculada;
//Detalle Flujo Aprobación Tipo de Contrato
List<FlujoAprobacionTipoContratoLogic> listadoFlujoAprobacionTipoContrato = flujoAprobacionLogicRepository.BuscarFlujoAprobacionTipoContrato(
null,
entidad.CodigoFlujoAprobacion,
null,
null
);
//Eliminar los tipos de contrato
foreach (var item in listadoFlujoAprobacionTipoContrato.Where(item => item.EstadoRegistro == DatosConstantes.EstadoRegistro.Activo).ToList())
{
flujoAprobacionTipoContratoEntityRepository.Eliminar(item.CodigoFlujoAprobacionTipoContrato);
flujoAprobacionTipoContratoEntityRepository.GuardarCambios();
}
//Editar o registrar tipos de contrato
foreach (var item in data.ListaTipoServicio)
{
FlujoAprobacionTipoContratoEntity entidadFlujoAprobacionTipoContrato = new FlujoAprobacionTipoContratoEntity();
var flujoAprobacionTipoContratoEditar = listadoFlujoAprobacionTipoContrato.Where(itemWhere => itemWhere.CodigoTipoContrato == item).FirstOrDefault();
if (flujoAprobacionTipoContratoEditar != null)
{
entidadFlujoAprobacionTipoContrato = flujoAprobacionTipoContratoEntityRepository.GetById(flujoAprobacionTipoContratoEditar.CodigoFlujoAprobacionTipoContrato);
entidadFlujoAprobacionTipoContrato.EstadoRegistro = DatosConstantes.EstadoRegistro.Activo;
flujoAprobacionTipoContratoEntityRepository.Editar(entidadFlujoAprobacionTipoContrato);
}
else
{
entidadFlujoAprobacionTipoContrato.CodigoFlujoAprobacion = entidad.CodigoFlujoAprobacion;
entidadFlujoAprobacionTipoContrato.CodigoFlujoAprobacionTipoContrato = Guid.NewGuid();
entidadFlujoAprobacionTipoContrato.CodigoTipoContrato = item;
flujoAprobacionTipoContratoEntityRepository.Insertar(entidadFlujoAprobacionTipoContrato);
}
flujoAprobacionTipoServicioEntityRepository.GuardarCambios();
}
entidadSincronizar.IndicadorAplicaMontoMinimo = entidad.IndicadorAplicaMontoMinimo;
entidadSincronizar.EstadoRegistro = entidad.EstadoRegistro;
flujoAprobacionEntityRepository.Editar(entidadSincronizar);
}
flujoAprobacionEstadioEntityRepository.GuardarCambios();
}
resultado.Result = data;
}
catch (Exception e)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(e);
}
return resultado;
}
/// <summary>
/// Elimina flujo de aprobacion
/// </summary>
/// <param name="listaCodigoFlujoAprobacion"></param>
/// <returns>Indicador con el resultado de la operación</returns>
public ProcessResult<Object> EliminarFlujoAprobacion(List<Object> listaCodigoFlujoAprobacion)
{
ProcessResult<Object> resultado = new ProcessResult<Object>();
try
{
foreach (var codigo in listaCodigoFlujoAprobacion)
{
var llaveEntidad = new Guid(codigo.ToString());
flujoAprobacionEntityRepository.Eliminar(llaveEntidad);
}
resultado.Result = flujoAprobacionEntityRepository.GuardarCambios();
}
catch (Exception e)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(e);
}
return resultado;
}
/// <summary>
/// Busca Bandeja Flujo Aprobacion Estadios
/// </summary>
/// <param name="filtro"></param>
/// <returns>Lista Flujo Aprobación Estadio</returns>
public ProcessResult<List<FlujoAprobacionEstadioResponse>> BuscarBandejaFlujoAprobacionEstadio(string codigoFlujoAprobacionEstadio, string codigoFlujoAprobacion, bool obtenerInformacionRepresentante = false)
{
ProcessResult<List<FlujoAprobacionEstadioResponse>> resultado = new ProcessResult<List<FlujoAprobacionEstadioResponse>>();
TrabajadorRequest trabajador = new TrabajadorRequest();
try
{
Guid? CodigoFlujoAprobacionEstadio = (codigoFlujoAprobacionEstadio != null && codigoFlujoAprobacionEstadio.ToString() != "") ? new Guid(codigoFlujoAprobacionEstadio.ToString()) : (Guid?)null;
Guid? CodigoFlujoAprobacion = (codigoFlujoAprobacion != null && codigoFlujoAprobacion.ToString() != "") ? new Guid(codigoFlujoAprobacion.ToString()) : (Guid?)null;
List<FlujoAprobacionEstadioLogic> listado = flujoAprobacionLogicRepository.BuscarBandejaFlujoAprobacionEstadio(
CodigoFlujoAprobacionEstadio,
CodigoFlujoAprobacion
);
int li_indexTrb = -1;
List<Guid?> lstRepresentantes = new List<Guid?>();
List<Guid?> lstInformados = new List<Guid?>();
List<Guid?> lstResponsableVinculadas = new List<Guid?>();
string[] listaRepresentantes;
string[] listaInformados;
string[] listaResponsableVinculadas;
foreach (var item in listado)
{
if (obtenerInformacionRepresentante)
{
listaRepresentantes = item.CodigosRepresentante.Split('/');
if (item.CodigosRepresentante.Trim().Length > 1)
{
for (int li = 1; li < listaRepresentantes.Length; li++)
{
li_indexTrb = lstRepresentantes.FindIndex(x => x.Value.ToString().ToLower() == listaRepresentantes[li].ToLower());
if (li_indexTrb == -1)
{
lstRepresentantes.Add(Guid.Parse(listaRepresentantes[li]));
}
}
}
listaInformados = item.CodigosInformado.Split('/');
if (item.CodigosInformado.Trim().Length > 1)
{
for (int li = 1; li < listaInformados.Length; li++)
{
li_indexTrb = lstInformados.FindIndex(x => x.Value.ToString().ToLower() == listaInformados[li].ToLower());
if (li_indexTrb == -1)
{
lstInformados.Add(Guid.Parse(listaInformados[li]));
}
}
}
if (!string.IsNullOrEmpty(item.CodigosResponsableVinculadas))
{
listaResponsableVinculadas = item.CodigosResponsableVinculadas.Split('/');
for (int li = 1; li < listaResponsableVinculadas.Length; li++)
{
li_indexTrb = lstResponsableVinculadas.FindIndex(x => x.Value.ToString().ToLower() == listaResponsableVinculadas[li].ToLower());
if (li_indexTrb == -1)
{
lstResponsableVinculadas.Add(Guid.Parse(listaResponsableVinculadas[li]));
}
}
}
}
}
List<TrabajadorResponse> listaRepresentante = null;
List<TrabajadorResponse> listaInformado = null;
List<TrabajadorResponse> listaResponsablesVinculadas = null;
if (obtenerInformacionRepresentante)
{
listaRepresentante = trabajadorService.ListarTrabajadores(lstRepresentantes).Result;
listaInformado = trabajadorService.ListarTrabajadores(lstInformados).Result;
listaResponsablesVinculadas = trabajadorService.ListarTrabajadores(lstResponsableVinculadas).Result;
}
resultado.Result = new List<FlujoAprobacionEstadioResponse>();
foreach (var registro in listado)
{
var flujoAprobacionEstadio = FlujoAprobacionEstadioAdapter.ObtenerFlujoAprobacionEstadio(registro, listaRepresentante, listaInformado, listaResponsablesVinculadas);
resultado.Result.Add(flujoAprobacionEstadio);
}
}
catch (Exception e)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(e);
}
return resultado;
}
/// <summary>
/// Registra / Edita Flujo Aprobacion Estadios
/// </summary>
/// <param name="data">Datos de estadio</param>
/// <param name="responsable">Responsable de estadio</param>
/// <param name="informados">Informados de estadio</param>
/// <param name="responsableVinculadas">Responsable de vinculadas</param>
/// <returns>Indicador con el resultado de la operación</returns>
public ProcessResult<FlujoAprobacionEstadioRequest> RegistrarFlujoAprobacionEstadio(FlujoAprobacionEstadioRequest data, List<FlujoAprobacionEstadioRequest> responsable, List<FlujoAprobacionEstadioRequest> informados, List<FlujoAprobacionEstadioRequest> responsableVinculadas)
{
ProcessResult<FlujoAprobacionEstadioRequest> resultado = new ProcessResult<FlujoAprobacionEstadioRequest>();
string flagRegistrar = "I";
try
{
string codigoResponsable = "";
FlujoAprobacionEstadioEntity entidad = FlujoAprobacionEstadioAdapter.RegistrarFlujoAprobacionEstadio(data);
var resultadoRepetidoOrden = flujoAprobacionLogicRepository.RepiteFlujoAprobacionEstadioOrden(
new Guid(data.CodigoFlujoAprobacion),
data.Orden
);
bool existeRepetidoOrden = resultadoRepetidoOrden.Any(e => e.CodigoFlujoAprobacionEstadio != entidad.CodigoFlujoAprobacionEstadio);
var numeroOrden = resultadoRepetidoOrden.Select(e => e.Orden);
var resultadoRepetidoDescripcion = flujoAprobacionLogicRepository.RepiteFlujoAprobacionEstadioDescripcion(
new Guid(data.CodigoFlujoAprobacion),
data.Descripcion
);
bool existeRepetidoDescripcion = resultadoRepetidoDescripcion.Any(e => e.CodigoFlujoAprobacionEstadio != entidad.CodigoFlujoAprobacionEstadio);
if (data.IndicadorVersionOficial)
{
flujoAprobacionEstadioEntityRepository.ActualizaIndicadorVersionOficial(
entidad.CodigoFlujoAprobacion
);
}
if (data.IndicadorNumeroContrato)
{
flujoAprobacionEstadioEntityRepository.ActualizaIndicadorNumeroContrato(
entidad.CodigoFlujoAprobacion
);
}
if (existeRepetidoDescripcion)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(MensajesSistema.FlujoAprobacionEstadioDescripcionExiste);
return resultado;
}
if (data.CodigoFlujoAprobacionEstadio == null)
{
if (numeroOrden.FirstOrDefault() == 1)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(MensajesSistema.FlujoAprobacionOrdenIgualUno);
return resultado;
}
flujoAprobacionEstadioEntityRepository.DesplazarOrden(
entidad,
flagRegistrar
);
flujoAprobacionEstadioEntityRepository.Insertar(entidad);
}
else
{
if (numeroOrden.FirstOrDefault() >= 1)
{
flagRegistrar = "U";
flujoAprobacionEstadioEntityRepository.DesplazarOrden(
entidad,
flagRegistrar
);
var entidadSincronizar = flujoAprobacionEstadioEntityRepository.GetById(entidad.CodigoFlujoAprobacionEstadio);
entidadSincronizar.CodigoFlujoAprobacion = entidad.CodigoFlujoAprobacion;
entidadSincronizar.Orden = entidad.Orden;
entidadSincronizar.Descripcion = entidad.Descripcion;
entidadSincronizar.TiempoAtencion = entidad.TiempoAtencion;
entidadSincronizar.HorasAtencion = entidad.HorasAtencion;
entidadSincronizar.IndicadorNumeroContrato = entidad.IndicadorNumeroContrato;
entidadSincronizar.IndicadorPermiteCarga = entidad.IndicadorPermiteCarga;
entidadSincronizar.IndicadorVersionOficial = entidad.IndicadorVersionOficial;
entidadSincronizar.EstadoRegistro = entidad.EstadoRegistro;
entidadSincronizar.IndicadorIncluirVisto = entidad.IndicadorIncluirVisto;
flujoAprobacionEstadioEntityRepository.Editar(entidadSincronizar);
}
if (existeRepetidoOrden)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(MensajesSistema.FlujoAprobacionOrdenIgualUno);
return resultado;
}
}
flujoAprobacionLogicRepository.EliminaParticipante(
entidad.CodigoFlujoAprobacionEstadio
);
//Registrar Participante Responsable (R)
if (responsable.Count > 0)
{
foreach (var item in responsable)
{
codigoResponsable = item.Responsable;
}
this.RegistrarFlujoAprobacionParticipante(new FlujoAprobacionParticipanteRequest()
{
CodigoFlujoAprobacionEstadio = entidad.CodigoFlujoAprobacionEstadio.ToString(),
CodigoTrabajador = codigoResponsable,
CodigoTipoParticipante = DatosConstantes.FlujoAprobacionTipoParticipante.Responsable
});
}
//Registrar Participante Informador (I)
if (informados.Count > 0)
{
foreach (var item in informados)
{
this.RegistrarFlujoAprobacionParticipante(new FlujoAprobacionParticipanteRequest()
{
CodigoFlujoAprobacionEstadio = entidad.CodigoFlujoAprobacionEstadio.ToString(),
CodigoTrabajador = item.Informados,
CodigoTipoParticipante = DatosConstantes.FlujoAprobacionTipoParticipante.Informado
});
}
}
//Registrar Participante Responsable de Vinculadas (V)
if (responsableVinculadas != null)
{
foreach (var item in responsableVinculadas)
{
this.RegistrarFlujoAprobacionParticipante(new FlujoAprobacionParticipanteRequest()
{
CodigoFlujoAprobacionEstadio = entidad.CodigoFlujoAprobacionEstadio.ToString(),
CodigoTrabajador = item.Responsable,
CodigoTipoParticipante = DatosConstantes.FlujoAprobacionTipoParticipante.ResponsableVinculadas
});
}
}
flujoAprobacionEstadioEntityRepository.GuardarCambios();
resultado.Result = data;
}
catch (Exception e)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(e);
}
return resultado;
}
/// <summary>
/// Eliminar Flujo AprobacionEstadio
/// </summary>
/// <param name="listaCodigoFlujoAprobacionEstadio"></param>
/// <returns>Indicador con el resultado de la operación</returns>
public ProcessResult<Object> EliminarFlujoAprobacionEstadio(List<Object> listaCodigoFlujoAprobacionEstadio)
{
ProcessResult<Object> resultado = new ProcessResult<Object>();
try
{
var flagRegistrar = "D";
foreach (var codigo in listaCodigoFlujoAprobacionEstadio)
{
var llaveEntidad = new Guid(codigo.ToString());
flujoAprobacionEstadioEntityRepository.DesplazarOrden(
new FlujoAprobacionEstadioEntity()
{
CodigoFlujoAprobacionEstadio = llaveEntidad
},
flagRegistrar
);
flujoAprobacionEstadioEntityRepository.Eliminar(llaveEntidad);
}
//EliminarFlujoAprobacionParticipante(listaCodigoFlujoAprobacionEstadio);
var OrdenContinua = new Guid(listaCodigoFlujoAprobacionEstadio.FirstOrDefault().ToString());
var totalEliminar = listaCodigoFlujoAprobacionEstadio.Count();
resultado.Result = flujoAprobacionEstadioEntityRepository.GuardarCambios();
}
catch (Exception e)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(e);
}
return resultado;
}
/// <summary>
/// Registra / Edita Flujo Aprobacion Participante
/// </summary>
/// <param name="data"></param>
/// <returns>Indicador con el resultado de la operación</returns>
public ProcessResult<FlujoAprobacionParticipanteRequest> RegistrarFlujoAprobacionParticipante(FlujoAprobacionParticipanteRequest data)
{
ProcessResult<FlujoAprobacionParticipanteRequest> resultado = new ProcessResult<FlujoAprobacionParticipanteRequest>();
try
{
FlujoAprobacionParticipanteEntity entidad = FlujoAprobacionParticipanteAdapter.RegistrarFlujoAprobacionParticipante(data);
flujoAprobacionParticipanteEntityRepository.Insertar(entidad);
flujoAprobacionParticipanteEntityRepository.GuardarCambios();
resultado.Result = data;
}
catch (Exception e)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(e);
}
return resultado;
}
/// <summary>
/// Eliminar Flujo Aprobacion Participante
/// </summary>
/// <param name="listaCodigoFlujoAprobacionEstadio"></param>
/// <returns>Indicador con el resultado de la operación</returns>
public ProcessResult<Object> EliminarFlujoAprobacionParticipante(List<Object> listaCodigoFlujoAprobacionEstadio)
{
ProcessResult<Object> resultado = new ProcessResult<Object>();
try
{
foreach (var codigo in listaCodigoFlujoAprobacionEstadio)
{
var llaveEntidad = new Guid(codigo.ToString());
flujoAprobacionParticipanteEntityRepository.Eliminar(llaveEntidad);
}
resultado.Result = flujoAprobacionParticipanteEntityRepository.GuardarCambios();
}
catch (Exception e)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(e);
}
return resultado;
}
///// <summary>
///// Copia Estadio
///// </summary>
///// <param name="data">Datos a Copiar</param>
///// <returns>Indicador con el resultado de la operación</returns>
//public ProcessResult<List<FlujoAprobacionEstadioResponse>> CopiarEstadio(FlujoAprobacionRequest data)
//{
// ProcessResult<List<FlujoAprobacionEstadioResponse>> resultado = new ProcessResult<List<FlujoAprobacionEstadioResponse>>();
// try
// {
// var resultadoAcopiarEncontrado = flujoAprobacionLogicRepository.RepiteFlujoAprobacion(
// new Guid(data.CodigoUnidadOperativa),
// null,
// data.CodigoTipoContrato
// );
// bool existeEncontrado = resultadoAcopiarEncontrado.Any(e => e.CodigoFlujoAprobacion != new Guid(data.CodigoFlujoAprobacion));
// bool esIgual = resultadoAcopiarEncontrado.Any(e => e.CodigoFlujoAprobacion == new Guid(data.CodigoFlujoAprobacion));
// if (!existeEncontrado)
// {
// if (esIgual)
// {
// resultado.IsSuccess = false;
// resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(MensajesSistema.CopiarEstadioIgual);
// }
// else
// {
// resultado.IsSuccess = false;
// resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(MensajesSistema.CopiarEstadioNoExiste);
// }
// }
// else
// {
// var codigoFlujoAprobacionHasta = data.CodigoFlujoAprobacion;
// var codigoFlujoAprobacionADesde = resultadoAcopiarEncontrado.Select(e => e.CodigoFlujoAprobacion).FirstOrDefault().ToString();
// var resultadoCopiarEstadio = BuscarBandejaFlujoAprobacionEstadio(null, codigoFlujoAprobacionADesde);
// if (resultadoCopiarEstadio.Result.Count == 0)
// {
// resultado.IsSuccess = false;
// resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(MensajesSistema.CopiarEstadioNoTiene);
// }
// else
// {
// flujoAprobacionLogicRepository.CopiarEstadio(
// new Guid(codigoFlujoAprobacionHasta),
// new Guid(codigoFlujoAprobacionADesde),
// entornoActualAplicacion.UsuarioSession,
// entornoActualAplicacion.Terminal
// );
// }
// }
// }
// catch (Exception e)
// {
// resultado.IsSuccess = false;
// resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(e);
// }
// return resultado;
//}
/// <summary>
/// Busca Estadios de Flujo de Aprobación de Estadio
/// </summary>
/// <param name="filtro">Filtro de Flujo de Aprobación</param>
/// <returns>Lista de Estadios de Flujo de Aprobación</returns>
public ProcessResult<List<FlujoAprobacionEstadioResponse>> BuscarFlujoAprobacionEstadioDescripcion(FlujoAprobacionEstadioRequest filtro)
{
ProcessResult<List<FlujoAprobacionEstadioResponse>> resultado = new ProcessResult<List<FlujoAprobacionEstadioResponse>>();
try
{
List<FlujoAprobacionEstadioLogic> listado = flujoAprobacionLogicRepository.BuscarFlujoAprobacionEstadioDescripcion(
filtro.Descripcion,
DatosConstantes.EstadoRegistro.Activo
);
resultado.Result = new List<FlujoAprobacionEstadioResponse>();
foreach (var registro in listado)
{
var flujoAprobacion = FlujoAprobacionEstadioAdapter.ObtenerFlujoAprobacionEstadioDescripcion(registro);
resultado.Result.Add(flujoAprobacion);
}
}
catch (Exception e)
{
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<FlujoAprobacionService>(e);
}
return resultado;
}
/// <summary>
/// Actualiza el reemplazo al trabajador original
/// </summary>
/// <param name="codigoTrabajador">Codigo de trabajador</param>
/// <returns>Indicador con el resultado de la operación</returns>
public ProcessResult<string> ActualizarTrabajadorOriginalFlujo(Guid codigoTrabajador)
{
ProcessResult<string> resultado = new ProcessResult<string>();
try
{
flujoAprobacionLogicRepository.ActualizarTrabajadorOriginalFlujo(codigoTrabajador);
resultado.Result = "1";
}
catch (Exception e)
{
throw e;
}
return resultado;
}
}
}
|
using System.ComponentModel.DataAnnotations;
using Alabo.Web.Mvc.Attributes;
namespace Alabo.Industry.Shop.Orders.Domain.Enums
{
/// <summary>
/// 订单状态,订单状态足够,不需要再加额外业务处理
/// 状态能够处理各种复杂的订单业务逻辑
/// </summary>
[ClassProperty(Name = "订单状态")]
public enum OrderStatus
{
/// <summary>
/// 等待付款,可取消
/// </summary>
[Display(Name = "待付款")] [LabelCssClass(BadgeColorCalss.Danger)] [Field(Icon = "flaticon-apps")]
WaitingBuyerPay = 1,
/// <summary>
/// 等待审核,可退款
/// 财务审核订单,支付给商户后订单状态改为待发货
/// </summary>
[Display(Name = "审核中")] [LabelCssClass("m-badge--brand")] [Field(Icon = "la la-check-circle-o")]
WaitingSellerReview = 0,
/// <summary>
/// 等待发货,可退款
/// 如果线下商品,改状态表示未消费
/// 部分发货,为等待发货
/// </summary>
[Display(Name = "待发货")] [LabelCssClass("m-badge--brand")] [Field(Icon = "la la-check-circle-o")]
WaitingSellerSendGoods = 2,
/// <summary>
/// 待收货,等待确认
/// </summary>
[Display(Name = "待收货")] [LabelCssClass(BadgeColorCalss.Primary)] [Field(Icon = "la la-check-circle-o")]
WaitingReceiptProduct = 3,
/// <summary>
/// 待评价
/// </summary>
[Display(Name = "待评价")] [LabelCssClass(BadgeColorCalss.Metal)] [Field(Icon = "la la-check-circle-o")]
WaitingEvaluated = 4,
/// <summary>
/// 待分享
/// 拼团商品时候,需要使用拼团流程:待付款->待分享->代发货
/// 在代发货之前,有个待分享流程
/// </summary>
[Display(Name = "待分享")] [LabelCssClass(BadgeColorCalss.Primary)] [Field(Icon = "la la-check-circle-o")]
WaitingShared = 10,
/// <summary>
/// 已发货
/// 申请退货中,退款/售后
/// </summary>
[Display(Name = "退款/退货")] [LabelCssClass(BadgeColorCalss.Info)] [Field(Icon = "la la-check-circle-o")]
AfterSale = 50,
/// <summary>
/// 未发货
/// 申请退货中,退款/售后
/// </summary>
[Display(Name = "待退款")] [LabelCssClass(BadgeColorCalss.Info)] [Field(Icon = "la la-check-circle-o")]
Refund = 51,
/// <summary>
/// 已完成
/// </summary>
[Display(Name = "订单完成")] [Field(Icon = "la la-check-circle-o")] [LabelCssClass(BadgeColorCalss.Success)]
Success = 100,
/// <summary>
/// 已关闭
/// 指买家操作取消,或管理员关闭,或计划任务自动关闭
/// 订单关闭后,库存恢复
/// </summary>
[Display(Name = "订单关闭")] [LabelCssClass(BadgeColorCalss.Default)] [Field(Icon = "la la-check-circle-o")]
Closed = 200,
/// <summary>
/// 已关闭
/// 退款后的状态
/// </summary>
[Display(Name = "订单关闭,已退款")] [LabelCssClass(BadgeColorCalss.Default)] [Field(Icon = "la la-check-circle-o")]
Refunded = 201,
/// <summary>
/// 已关闭
/// 退款后的状态
/// </summary>
[Display(Name = "下架")] [LabelCssClass(BadgeColorCalss.Default)] [Field(Icon = "la la-check-circle-o")]
UnderShelf = 300,
/// <summary>
/// 已打款
/// 财务已打款 待供应商发货的状态
/// </summary>
[Display(Name = "待出库")] [LabelCssClass(BadgeColorCalss.Default)] [Field(Icon = "la la-check-circle-o")]
Remited = 400
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BikeRaceApp
{
public class Rider
{
//Creating inital variables
private string name;
private string surname;
private string school;
private bool active = true;
private int id;
//Creating a list that will store all the riders races
private List<Race> races = new List<Race>() {new Race(), new Race(), new Race(), new Race()};
//Creating the rider
public Rider(string name,string surname, string school, int id)
{
this.name = name;
this.surname = surname;
this.school = school;
this.id = id;
}
//Setting a rider active or inactive
public void SetActive()
{
if (active == true)
{
active = false;
}
else
{
active = true;
}
}
//Entering a rider into a race
public void EnterRace(int raceNum)
{
races[raceNum].SetRaceStatus(true);
}
//Producing a rider summary
public string RiderSummary()
{
string summary = "Name: "+name+" "+surname+"\nSchool: "+school+"\n";
for (int i = 1; i < 5; i++)
{
summary += $"Race {i}: ";
string entryStatus = "Not Entered";
if (races[i - 1].GetRaceStatus())
{
entryStatus = "Entered";
}
summary += entryStatus+"\n";
}
return summary;
}
//Storing a rider
public string StoreRider()
{
string storeRider = name + "," + surname + "," + school + ","+id+",";
string rStatus = "";
string fTime = "";
foreach (Race race in races)
{
rStatus += race.GetRaceStatus() + "#";
fTime += race.GetFinishTime() + "#";
}
rStatus += ",";
storeRider += rStatus + fTime;
if (active == true)
{
storeRider += ",Active";
}
else
{
storeRider += ",Inactive";
}
return storeRider;
}
//Getting rider name
public string GetName()
{
return name;
}
//Getting rider surname
public string GetSurname()
{
return surname;
}
//Getting rider school
public string GetSchool()
{
return school;
}
//Getting rider id
public int GetID()
{
return id;
}
//Seeing if rider is active
public bool GetActive()
{
return active;
}
//Getting race entry status for a single race
public bool GetSingleEntryStatus(int raceIndex)
{
return races[raceIndex].GetRaceStatus();
}
//Getting race entry status for all races
public List<bool> GetEntryStatus()
{
List<bool> entryStatus = new List<bool>();
foreach (var race in races)
{
entryStatus.Add(race.GetRaceStatus());
}
return entryStatus;
}
//Setting Finish Time
public void SetFinishTime(int raceIndex, string finishTime)
{
races[raceIndex].SetFinishTime(finishTime);
}
//Passing Race time through classes
public string GetCalculateRaceTime(int raceID)
{
return races[raceID].CalculateRaceTime();
}
//Passing int version of race time through classes
public int GetCheckedRaceTime(int raceID)
{
return races[raceID].CheckRaceTime();
}
//Getting Finish time
public string GetFinishTime(int raceIndex)
{
return races[raceIndex].GetFinishTime();
}
}
}
|
using Client.Helpers.System;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System.Windows;
using System.Windows.Controls;
using WPF.NewClient.ViewModel;
using WPF.NewClientl.Model;
namespace Meeting.NewClient.UI
{
/// <summary>
/// Description for Welcome.
/// </summary>
public partial class VoteStatisticsWindow : MetroWindow
{
/// <summary>
/// Initializes a new instance of the Welcome class.
/// </summary>
public VoteStatisticsWindow()
{
InitializeComponent();
}
}
} |
namespace _03.PeriodicTable
{
using System;
using System.Collections.Generic;
using System.Linq;
public class PeriodicTable
{
public static void Main()
{
int lineNumbers = int.Parse(Console.ReadLine());
SortedSet<string> inputStr = new SortedSet<string>();
for (int i = 0; i < lineNumbers; i++)
{
string[] tmpStrings = Console.ReadLine().Split();
foreach (string s in tmpStrings)
{
inputStr.Add(s);
}
}
Console.WriteLine(string.Join(" ",inputStr));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRAPShared;
namespace IRAP.Entity.FVS
{
/// <summary>
/// 制造订单跟踪看板内容
/// </summary>
public class Dashboard_MOTrack
{
/// <summary>
/// 序号
/// </summary>
public int Ordinal { get; set; }
/// <summary>
/// 产品族叶标识
/// </summary>
public int T132LeafID { get; set; }
/// <summary>
/// 背景颜色(#FFFFFF)
/// </summary>
public string BackgroundColor { get; set; }
/// <summary>
/// 分区键
/// </summary>
public long PartitioningKey { get; set; }
/// <summary>
/// 事实编号
/// </summary>
public long FactID { get; set; }
/// <summary>
/// 生产工单号
/// </summary>
public string PWONo { get; set; }
/// <summary>
/// 制造订单号
/// </summary>
public string MONumber { get; set; }
/// <summary>
/// 制造订单行号
/// </summary>
public int MOLineNo { get; set; }
/// <summary>
/// 产品编号
/// </summary>
public string ProductNo { get; set; }
/// <summary>
/// 产品名称
/// </summary>
public string ProductName { get; set; }
/// <summary>
/// 计划开工日期
/// </summary>
public string PlannedStartDate { get; set; }
/// <summary>
/// 计划完工日期
/// </summary>
public string PlannedCloseDate { get; set; }
/// <summary>
/// 排定生产时间
/// </summary>
public string ScheduledStartTime { get; set; }
/// <summary>
/// 实际开工时间
/// </summary>
public string ActualStartTime { get; set; }
/// <summary>
/// 要求完工时间
/// </summary>
public string ScheduledCloseTime { get; set; }
/// <summary>
/// 工单执行进度
/// </summary>
/// <remarks>0=正常 1=偏快 2=过快 3=偏慢 4=过慢</remarks>
public int PWOProgress { get; set; }
/// <summary>
/// 滞在工序名
/// </summary>
public string OperationName { get; set; }
/// <summary>
/// 订单数量
/// </summary>
public long OrderQty { get; set; }
/// <summary>
/// 提料数量
/// </summary>
public long MaterialQty { get; set; }
/// <summary>
/// 正品数量
/// </summary>
public long WIPQty { get; set; }
/// <summary>
/// 废品率(本工序前)
/// </summary>
public decimal ScrapRate { get; set; }
/// <summary>
/// 进度百分比(%)
/// </summary>
public decimal ProgressPercentage { get; set; }
[IRAPORMMap(ORMMap = false)]
public decimal ActualScrapRate
{
get { return ScrapRate / 100; }
}
[IRAPORMMap(ORMMap = false)]
public decimal ActualProgressPercentage
{
get { return ProgressPercentage / 100; }
}
public Dashboard_MOTrack Clone()
{
return this.MemberwiseClone() as Dashboard_MOTrack;
}
}
}
|
using System.Threading;
namespace UIAFramework
{
public static class Mouse
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetCursorPos(int x, int y);
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_WHEEL = 0x800;
private const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
private const int MOUSEEVENTF_RIGHTUP = 0x0010;
public static void MoveTo(int xpos, int ypos)
{
SetCursorPos(xpos, ypos);
}
public static void Click(int xpos, int ypos)
{
SetCursorPos(xpos, ypos);
mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
}
public static void DoubleClick(int xpos, int ypos)
{
SetCursorPos(xpos, ypos);
mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
Thread.Sleep(200);
mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
}
public static void RightClick(int xpos, int ypos)
{
SetCursorPos(xpos, ypos);
mouse_event(MOUSEEVENTF_RIGHTDOWN, xpos, ypos, 0, 0);
mouse_event(MOUSEEVENTF_RIGHTUP, xpos, ypos, 0, 0);
}
}
}
|
/******************************************************************************
* File : pLab_OutOfGeoAreaBoundsUI.cs
* Lisence : BSD 3-Clause License
* Copyright : Lapland University of Applied Sciences
* Authors : Arto Söderström
* BSD 3-Clause License
*
* Copyright (c) 2019, Lapland University of Applied Sciences
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pLab_OutOfGeoAreaBoundsUI : MonoBehaviour
{
#region Variables
[SerializeField]
[Header("Player must be inside this geo area to play")]
private pLab_GeoArea playableGeoArea;
[SerializeField]
private pLab_LocationProvider locationProvider;
[SerializeField]
private GameObject alertIndicatorCanvasObj;
[SerializeField]
private Canvas disableCanvas;
#endregion
#region Inherited Methods
private void Start() {
ToggleAlertIndicatorVisibility(false);
}
private void OnEnable() {
if (locationProvider != null) {
locationProvider.OnLocationUpdated += OnLocationUpdated;
}
}
private void OnDisable() {
if (locationProvider != null) {
locationProvider.OnLocationUpdated -= OnLocationUpdated;
}
}
#endregion
#region Private Methods
/// <summary>
/// Event handler for OnLocationUpdated-event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnLocationUpdated(object sender, pLab_LocationUpdatedEventArgs e)
{
RecheckIfOutOfBounds(e.location);
}
/// <summary>
/// Recheck if new GPS-coordinates are out of bounds
/// </summary>
private void RecheckIfOutOfBounds(pLab_LatLon latLon) {
bool showAlertIndicator = false;
if (playableGeoArea != null) {
showAlertIndicator = !playableGeoArea.IsLocationInsideZone(latLon);
}
ToggleAlertIndicatorVisibility(showAlertIndicator);
}
/// <summary>
/// Toggle alert indicator visibility
/// </summary>
/// <param name="isVisible"></param>
private void ToggleAlertIndicatorVisibility(bool isVisible) {
if (alertIndicatorCanvasObj != null) {
alertIndicatorCanvasObj.SetActive(isVisible);
}
if (disableCanvas != null) {
disableCanvas.enabled = isVisible;
}
}
#endregion
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace _17.Add6H30M
{
class AddMoreTime
{
static void Main()
{
Console.WriteLine("Enter date (date.month.year hour:minute:second):");
string date = Console.ReadLine();
DateTime dt = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);
dt = dt.AddHours(6.5);
Console.WriteLine("{0} {1}", dt.ToString("dddd", new CultureInfo("bg-BG")), dt); //dddd is day of week full name
}
}
}
|
#if (NET20 || NET35 || NETCOREAPP1_0 || NETCOREAPP1_1)
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>Compensates for missing attribute in .NET 2.0</summary>
/// <seealso cref="System.Attribute"/>
public class ExcludeFromCodeCoverageAttribute : Attribute
{
}
}
#endif |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace TitanBlog.Data.Migrations
{
public partial class _005 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "Deleted",
table: "Comment",
type: "timestamp without time zone",
nullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "Moderated",
table: "Comment",
type: "timestamp without time zone",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ModeratedBody",
table: "Comment",
type: "character varying(500)",
maxLength: 500,
nullable: true);
migrationBuilder.AddColumn<int>(
name: "ModerationReason",
table: "Comment",
type: "integer",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<string>(
name: "ModeratorId",
table: "Comment",
type: "text",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Comment_ModeratorId",
table: "Comment",
column: "ModeratorId");
migrationBuilder.AddForeignKey(
name: "FK_Comment_AspNetUsers_ModeratorId",
table: "Comment",
column: "ModeratorId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Comment_AspNetUsers_ModeratorId",
table: "Comment");
migrationBuilder.DropIndex(
name: "IX_Comment_ModeratorId",
table: "Comment");
migrationBuilder.DropColumn(
name: "Deleted",
table: "Comment");
migrationBuilder.DropColumn(
name: "Moderated",
table: "Comment");
migrationBuilder.DropColumn(
name: "ModeratedBody",
table: "Comment");
migrationBuilder.DropColumn(
name: "ModerationReason",
table: "Comment");
migrationBuilder.DropColumn(
name: "ModeratorId",
table: "Comment");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Npgsql;
namespace Lucky13_Milestone2
{
/// <summary>
/// Interaction logic for Checkins.xaml
/// </summary>
public partial class Checkins : Window
{
string busID;
public Checkins(string bisID)
{
InitializeComponent();
busID = bisID;
checkinColChart();
}
private string buildConnectionString()
{
return "Host = localhost; Username = postgres; Database = 415Project; password = 605027";
}
private void checkinColChart()
{
List<KeyValuePair<int, int>> bCheckins = new List<KeyValuePair<int, int>>();
List<KeyValuePair<string, int>> bCheckinsWithMonths = new List<KeyValuePair<string, int>>();
string[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
using (var connection = new NpgsqlConnection(buildConnectionString()))
{
connection.Open();
using (var cmd = new NpgsqlCommand())
{
cmd.Connection = connection;
cmd.CommandText = "SELECT month, count(business_id) FROM checkin WHERE business_id = '" + busID + "' GROUP BY month ORDER BY month; ";
var reader = cmd.ExecuteReader();
try
{
while (reader.Read())
{
bCheckins.Add(new KeyValuePair<int, int>(reader.GetInt32(0), reader.GetInt32(1)));
}
bCheckins.Sort((x, y) => (x.Key.CompareTo(y.Key)));
foreach (KeyValuePair<int, int> temp in bCheckins)
{
string month = months[temp.Key - 1];
bCheckinsWithMonths.Add(new KeyValuePair<string, int>(month, temp.Value));
}
checkinChart.DataContext = bCheckinsWithMonths;
}
catch (NpgsqlException ex)
{
Console.WriteLine(ex.Message.ToString());
MessageBox.Show("SQL Error - " + ex.Message.ToString());
}
finally
{
connection.Close();
}
}
}
}
private void checkInButton_Click(object sender, RoutedEventArgs e)
{
using (var connection = new NpgsqlConnection(buildConnectionString()))
{
connection.Open();
using (var cmd = new NpgsqlCommand())
{
var te = new Review() { bid = busID, year = DateTime.Now.Year, month = DateTime.Now.Month, day = DateTime.Now.Day,
hour = DateTime.Now.Hour, minute = DateTime.Now.Minute, second = DateTime.Now.Second };
cmd.Connection = connection;
cmd.CommandText = "INSERT INTO checkin (business_id, year, month, day, hour, minute, second) VALUES('" +
te.bid + "', " + te.year + ", " + te.month + ", " + te.day + ", " + te.hour + ", " + te.minute + ", " + te.second + " )";
try
{
cmd.ExecuteNonQuery();
checkinColChart();
}
catch (NpgsqlException ex)
{
Console.WriteLine(ex.Message.ToString());
MessageBox.Show("SQL Error - " + ex.Message.ToString());
}
finally
{
connection.Close();
}
}
}
}
}
}
|
namespace IdomOffice.Interface.BackOffice.PriceLists
{
public enum PaymentPlace : int
{
Booking = 1,
Arrival = 2
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Negocio;
using Globales;
using Configuracion;
namespace AerolineaFrba.Abm_Aeronave
{
public partial class frmBajaServicio : Form
{
private Aeronave aero;
public frmBajaServicio(Aeronave a)
{
InitializeComponent();
aero = a;
}
private void btnCancelar_Click(object sender, EventArgs e)
{
Close();
}
private void frmBajaServicio_Load(object sender, EventArgs e)
{
dtpBaja.MinDate = ConfiguracionGlobal.FechaSistema;
dtpReinicio.MinDate = ConfiguracionGlobal.FechaSistema.Date.AddDays(1);
txtMatricula.Text = aero.matriculaAeronave;
}
private void btnAceptar_Click(object sender, EventArgs e)
{
try
{
if (dtpReinicio.Value <= dtpBaja.Value) { throw new Exception("La fecha de reinicio debe ser posterior a la fecha de baja."); }
if (new Viaje().obtenerViajesVendidosDeAeronaveEntreFechas(aero.idAeronave, dtpBaja.Value, dtpReinicio.Value).Rows.Count > 0)
{
frmCancelarOAero fca = new frmCancelarOAero(aero,dtpBaja.Value,dtpReinicio.Value);
fca.ShowDialog();
if (fca.solucionado)
{
aero.bajaPorFueraDeServicio(aero.idAeronave, dtpBaja.Value, dtpReinicio.Value);
MessageBox.Show(string.Format("La aeronave ha sido dada de baja por fuera de servicio. Volverá a estar disponible el {0}", dtpReinicio.Value.ToShortDateString()), "Atención");
Close();
}
}
else
{
aero.bajaPorFueraDeServicio(aero.idAeronave, dtpBaja.Value, dtpReinicio.Value);
MessageBox.Show(string.Format("La aeronave ha sido dada de baja por fuera de servicio. Volverá a estar disponible el {0}",dtpReinicio.Value.ToShortDateString()),"Atención");
Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
}
}
|
using System;
namespace todo_app.Controllers
{
public class MyToDo{
public string ToDo { get; set; }
}
} |
using System.ComponentModel.DataAnnotations.Schema;
namespace GradConnect.Models
{
public class Module
{
public int Id { get; set; }
public string Title { get; set; }
public string Grade { get; set; }
//Navigational props
[InverseProperty("Education")]
public int EducationId { get; set; }
public virtual Education Education { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace WebAppMedOffices.Models
{
[Table("Medicos")]
public class Medico
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Debes introducir un {0}")]
[StringLength(30, ErrorMessage = "El campo {0} puede contener un máximo de {1} y un mínimo de {2} caracteres", MinimumLength = 3)]
[Display(Name = "Nombre")]
public string Nombre { get; set; }
[Required(ErrorMessage = "Debes introducir un {0}")]
[StringLength(30, ErrorMessage = "El campo {0} puede contener un máximo de {1} y un mínimo de {2} caracteres", MinimumLength = 3)]
[Display(Name = "Apellido")]
public string Apellido { get; set; }
[Required(ErrorMessage = "Debes introducir un {0}")]
[StringLength(30, ErrorMessage = "El campo {0} puede contener un máximo de {1} y un mínimo de {2} caracteres", MinimumLength = 3)]
[Index("Medico_UserName_Index", IsUnique = true)]
[DataType(DataType.EmailAddress)]
[Display(Name = "E-mail")]
public string UserName { get; set; }
[Required(ErrorMessage = "Debes introducir un {0}")]
[StringLength(30, ErrorMessage = "El campo {0} debe contener entre {2} y {1} caracteres", MinimumLength = 3)]
[DataType(DataType.PhoneNumber)]
[RegularExpression("^[0-9]*$", ErrorMessage = "No es un número de teléfono válido")]
[Display(Name = "Teléfono")]
public string Telefono { get; set; }
[Required(ErrorMessage = "Debes introducir un {0}")]
[StringLength(30, ErrorMessage = "El campo {0} debe contener entre {2} y {1} caracteres", MinimumLength = 3)]
[DataType(DataType.PhoneNumber)]
[RegularExpression("^[0-9]*$", ErrorMessage = "No es un número de teléfono válido")]
[Display(Name = "Celular")]
public string Celular { get; set; }
[Required(ErrorMessage = "Debes introducir una {0}")]
[MaxLength(50, ErrorMessage = "El campo {0} puede contener un máximo de {1} caracteres")]
[Index("Medico_Matricula_Index", IsUnique = true)]
[Display(Name = "Matrícula")]
public string Matricula { get; set; }
[Display(Name = "Nombre y Apellido")]
public virtual string NombreCompleto
{
get
{
return Nombre + " " + Apellido;
}
}
public virtual ICollection<DuracionTurnoEspecialidad> DuracionTurnoEspecialidades { get; set; }
public virtual ICollection<AtencionHorario> AtencionHorarios { get; set; }
public virtual ICollection<Turno> Turnos { get; set; }
}
} |
namespace SolidWorkshop.LSP.NonComplaint
{
using System;
public class YouTubePlayer
{
public virtual void Play()
{
Console.WriteLine("YouTubePlayer is playing");
}
public virtual void Pause()
{
Console.WriteLine("YouTubePlayer is paused");
}
public virtual void Next()
{
Console.WriteLine("YouTubePlayer plays next track.");
}
public virtual void Previous()
{
Console.WriteLine("YouTubePlayer plays previous track.");
}
public virtual void VolumeUp()
{
Console.WriteLine("YouTubePlayer volume up.");
}
public virtual void VolumeDown()
{
Console.WriteLine("YouTubePlayer volume down.");
}
}
public class YouTubeMobilePlayer : YouTubePlayer
{
public void CastToTv()
{
Console.WriteLine("YouTubeMobilePlayer cast to TV.");
}
public void SetPlaybackSpeed()
{
Console.WriteLine("YouTubeMobilePlayer sets player speed.");
}
public override void VolumeUp()
{
throw new NotSupportedException("Volume up is not supported in mobile player");
}
public override void VolumeDown()
{
throw new NotSupportedException("Volume down is not supported in mobile player");
}
}
} |
using System;
using System.Collections.Generic;
using Grasshopper.Kernel;
using PterodactylEngine;
namespace Pterodactyl
{
public class HorizontalLineGH : GH_Component
{
public HorizontalLineGH()
: base("Horizontal Line", "Horizontal Line",
"Add horizontal line",
"Pterodactyl", "Parts")
{
}
public override bool IsBakeCapable => false;
protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
{
}
protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
{
pManager.AddTextParameter("Report Part", "Report Part", "Created part of the report (Markdown text)", GH_ParamAccess.item);
}
protected override void SolveInstance(IGH_DataAccess DA)
{
string reportPart;
HorizontalLine reportObject = new HorizontalLine();
reportPart = reportObject.Create();
DA.SetData(0, reportPart);
}
protected override System.Drawing.Bitmap Icon
{
get
{
return Properties.Resources.PterodactylHorizontalLine;
}
}
public override Guid ComponentGuid
{
get { return new Guid("db6a6683-e51e-4a89-bb5e-3cdea64bda4e"); }
}
}
} |
// Copyright (C) 2008-2010 Jesse Jones
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using MObjc.Helpers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace MObjc
{
/// <summary>Base class for all Cocoa classes.</summary>
/// <remarks>They don't appear in the documentation but this class exposes all of the
/// standard <a href = "http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html">NSObject</a>
/// methods except that the only perform method exposed is performSelectorOnMainThread:withObject:waitUntilDone:.
/// The rest may be added in the future, but it's much easier to use mcocoa's NSApplication::BeginInvoke
/// method to do this sort of thing.</remarks>
[ThreadModel(ThreadModel.Concurrent)]
public partial class NSObject : IFormattable, IEquatable<NSObject>
{
static NSObject()
{
try
{
Registrar.Init();
ms_class = new Class("NSObject");
}
catch (Exception e)
{
// This is a fatal error and the nunit which ships with mono does a poor
// job printing inner exceptions. So, we'll print the exception ourself
// and shutdown the app.
Console.Error.WriteLine("Registrar.Init raised an exception:");
Console.Error.WriteLine("{0}", e);
Console.Out.Flush();
Console.Error.Flush();
Environment.Exit(13);
}
}
#if DEBUG
/// <summary>Debug method to enable recording stack traces for all NSObjects.</summary>
/// <remarks>ToString("S") will print the traces.</remarks>
public static bool SaveStackTraces {get; set;}
private string[] StackTrace {get; set;}
#endif
/// <summary>Constructs a managed object which is associated with an unmanaged object.</summary>
/// <remarks>In general multiple NSObject instances can be associated with the same unmanaged object.
/// The exception is that only one <see cref = "ExportClassAttribute">ExportClassAttribute</see> object can be associated with an
/// unmanaged object. If an attempt is made to construct two NSObjects pointing to the same
/// exported object an exception will be thrown. (The reason for this is that exported instances may
/// have managed state which should be associated with one and only one unmanaged instance).</remarks>
public NSObject(IntPtr instance)
{
m_instance = instance; // note that it's legal to send messages to nil
m_class = IntPtr.Zero;
if (m_instance != IntPtr.Zero)
{
// It's a little inefficient to always grab this information, but it makes
// dumping objects much easier because we can safely do it even when ref
// counts are zero.
IntPtr exception = IntPtr.Zero;
m_class = DirectCalls.Callp(m_instance, Selector.Class, ref exception);
if (exception != IntPtr.Zero)
CocoaException.Raise(exception);
m_baseClass = DirectCalls.Callp(m_class, Selector.SuperClass, ref exception);
if (exception != IntPtr.Zero)
CocoaException.Raise(exception);
#if DEBUG
if (SaveStackTraces)
{
var stack = new System.Diagnostics.StackTrace(1);
StackTrace = new string[stack.FrameCount];
for (int i = 0; i < stack.FrameCount; ++i) // TODO: provide a MaxStackDepth method?
{
StackFrame frame = stack.GetFrame(i);
if (!string.IsNullOrEmpty(frame.GetFileName()))
StackTrace[i] = string.Format("{0}|{1} {2}:{3}", frame.GetMethod().DeclaringType, frame.GetMethod(), frame.GetFileName(), frame.GetFileLineNumber());
else
StackTrace[i] = string.Format("{0}|{1}", frame.GetMethod().DeclaringType, frame.GetMethod());
}
}
#endif
lock (ms_instancesLock)
{
bool exported;
Type type = GetType();
if (!ms_exports.TryGetValue(type, out exported)) // GetCustomAttribute turns out to be very slow
{
ExportClassAttribute attr = Attribute.GetCustomAttribute(type, typeof(ExportClassAttribute)) as ExportClassAttribute;
exported = attr != null;
ms_exports.Add(type, exported);
}
if (exported)
{
if (ms_instances.ContainsKey(instance))
throw new InvalidOperationException(type + " is being constructed twice with the same id, try using the Lookup method.");
ms_instances.Add(instance, this);
}
}
#if DEBUG
ms_refs.Add(this);
#endif
}
}
/// <summary>Creates a new uninitialized unmanaged object with a reference count of one.</summary>
/// <param name = "name">The class name, e.g. "MyView".</param>
/// <remarks>This is commonly used with exported types which can be created via managed code
/// (as opposed to via Interface Builder).</remarks>
public static IntPtr AllocInstance(string name)
{
Class klass = new Class(name);
IntPtr exception = IntPtr.Zero;
IntPtr instance = DirectCalls.Callp(klass, Selector.Alloc, ref exception);
if (exception != IntPtr.Zero)
CocoaException.Raise(exception);
return instance;
}
/// <summary>Creates a new default initialized unmanaged object with a reference count of one.</summary>
/// <param name = "name">The class name, e.g. "MyView".</param>
/// <remarks>This is commonly used with exported types which can be created via managed code
/// (as opposed to via Interface Builder).</remarks>
public static IntPtr AllocAndInitInstance(string name)
{
Class klass = new Class(name);
IntPtr exception = IntPtr.Zero;
IntPtr instance = DirectCalls.Callp(klass, Selector.Alloc, ref exception);
if (exception != IntPtr.Zero)
CocoaException.Raise(exception);
instance = DirectCalls.Callp(instance, Selector.Init, ref exception);
if (exception != IntPtr.Zero)
CocoaException.Raise(exception);
return instance;
}
/// <summary>Increments the objects instance count.</summary>
/// <remarks>Retain counts work exactly like in native code and both mobjc and mcocoa
/// adhere to the cocoa memory management naming conventions. So, for example, mcocoa's
/// Create methods create auto-released objects with retain counts of one. See Apple's
/// <a href = "http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html">Memory Management Programming Guide</a>
/// for more details.
///
/// <para/>Note that you can also use <c>retain</c> but <c>Retain</c> is often more useful
/// because mcocoa provides <c>Retain</c> methods with better return types (which allows
/// you do do things like <c>NSString m_name = NSString.Create("Fred").Retain();</c>).</remarks>
public NSObject Retain()
{
Unused.Value = retain();
return this;
}
/// <summary>Always returns type NSObject.</summary>
/// <remarks>To get the dynamic type of an instance use the <c>class_</c> method.</remarks>
public static Class Class
{
get {return ms_class;}
}
/// <summary>Returns a new or existing NSObject associated with the unmanaged instance.</summary>
public static NSObject Lookup(IntPtr instance)
{
NSObject managed = null;
lock (ms_instancesLock)
{
if (!ms_instances.TryGetValue(instance, out managed))
{
// Nil is tricky to handle because we want to do things like convert
// id's to NSObject subclasses when marshaling from native to managed
// code. But we can't do this with nil because it has no class info.
// So, rather than returning an NSObject which will break marshaling
// we simply return null.
if (instance == IntPtr.Zero)
return null;
// If we land here then we have a native instance with no associated
// managed instance. This will happen if the native instance isn't
// an exported type, or it is exported and it's calling a managed
// method for the first time.
// First try to create an NSObject derived instance using the types
// which were registered or exported.
Type type = DoGetManagedClass(object_getClass(instance));
if (type != null)
{
Func<IntPtr, NSObject> factory;
if (!ms_factories.TryGetValue(type, out factory)) // Activator.CreateInstance is also a bottleneck
{
ConstructorInfo info = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, ms_factoryArgTypes, null);
if (info == null)
throw new InvalidOperationException("Couldn't find an (IntPtr) ctor for " + type);
factory = i => (NSObject) info.Invoke(new object[]{i});
ms_factories.Add(type, factory);
}
managed = factory(instance);
}
// If we can't create a subclass then just create an NSObject.
else
managed = new NSObject(instance);
}
}
return managed;
}
/// <summary>Returns the unmanaged instance.</summary>
public static implicit operator IntPtr(NSObject value)
{
return value != null ? value.m_instance : IntPtr.Zero;
}
/// <summary>Returns the unmanaged instance.</summary>
/// <remarks>This is needed for languages that don't support operator overloading.</remarks>
public static IntPtr ToIntPtrType(NSObject value)
{
return value != null ? value.m_instance : IntPtr.Zero;
}
[Pure]
public static bool IsNullOrNil(NSObject o)
{
return o == null || o.m_instance == IntPtr.Zero;
}
[Pure]
public bool IsNil()
{
return m_instance == IntPtr.Zero;
}
/// <summary>Returns true if the unmanaged instance has been deleted.</summary>
/// <remarks>This should only be used for debugging and testing.
///
/// <para/>This will be set correctly only if the last release call was from managed
/// code or the type is exported.</remarks>
[Pure]
public bool IsDeallocated()
{
return m_deallocated;
}
/// <summary>Dynamic method call.</summary>
/// <param name = "name">A method name, e.g. "setFrame:display:".</param>
/// <param name = "args">The arguments to pass to the method. If the arity or argument types
/// don't match the unmanaged code an exception will be thrown.</param>
public object Call(string name, params object[] args)
{
Contract.Requires(name != null, "name is null");
Contract.Requires(!m_deallocated, "ref count is zero");
object result;
if (m_instance != IntPtr.Zero)
result = Native.Call(m_instance, name, args);
else
result = new NSObject(IntPtr.Zero);
return result;
}
/// <summary>Dynamic call to an exported type's base class method.</summary>
/// <param name = "baseClass">The class for the type (or a descendent of the type) containing the method you want to call.</param>
/// <param name = "name">A method name, e.g. "setFrame:display:".</param>
/// <param name = "args">The arguments to pass to the method. If the arity or argument types
/// don't match the unmanaged code an exception will be thrown.</param>
public object SuperCall(Class baseClass, string name, params object[] args)
{
Contract.Requires(baseClass != null, "baseClass is null");
Contract.Requires(!string.IsNullOrEmpty(name), "name is null or empty");
Contract.Requires(!m_deallocated, "ref count is zero");
object result = IntPtr.Zero;
if (m_instance != IntPtr.Zero)
{
Native native = new Native(m_instance, new Selector(name), baseClass);
native.SetArgs(args);
result = native.Invoke();
}
return result;
}
/// <summary>Get or set an ivar.</summary>
/// <remarks>Usually these will be Interface Builder outlets.</remarks>
public NSObject this[string ivarName]
{
get
{
Contract.Requires(!string.IsNullOrEmpty(ivarName), "ivarName is null or empty");
Contract.Requires(!m_deallocated, "ref count is zero");
NSObject result;
if (m_instance != IntPtr.Zero)
{
IntPtr value = IntPtr.Zero;
IntPtr ivar = object_getInstanceVariable(m_instance, ivarName, ref value);
if (ivar == IntPtr.Zero)
throw new ArgumentException(ivarName + " isn't a valid instance variable");
result = Lookup(value);
}
else
result = new NSObject(IntPtr.Zero);
return result;
}
set
{
Contract.Requires(!string.IsNullOrEmpty(ivarName), "ivarName is null or empty");
Contract.Requires(!m_deallocated, "ref count is zero");
if (m_instance != IntPtr.Zero)
{
// Retain the new value (if any).
IntPtr exception = IntPtr.Zero, dummy = IntPtr.Zero;
if (!NSObject.IsNullOrNil(value))
{
Unused.Value = DirectCalls.Callp(value, Selector.Retain, ref exception);
if (exception != IntPtr.Zero)
CocoaException.Raise(exception);
}
// Release the old value (if any).
IntPtr oldValue = IntPtr.Zero;
IntPtr ivar = object_getInstanceVariable(m_instance, ivarName, ref oldValue);
if (ivar == IntPtr.Zero)
{
Unused.Value = DirectCalls.Callp(value, Selector.Release, ref dummy);
throw new ArgumentException(ivarName + " isn't a valid instance variable");
}
if (oldValue != IntPtr.Zero)
{
Unused.Value = DirectCalls.Callp(oldValue, Selector.Release, ref exception);
if (exception != IntPtr.Zero)
{
Unused.Value = DirectCalls.Callp(value, Selector.Release, ref dummy);
CocoaException.Raise(exception);
}
}
// Set the value.
ivar = object_setInstanceVariable(m_instance, ivarName, value);
}
}
}
#if DEBUG
/// <summary>Debug method which returns a list of all NSObject instances still in use.</summary>
/// <remarks>Note that the unmanaged instance may have been deleted.</remarks>
public static NSObject[] Snapshot()
{
return ms_refs.Snapshot();
}
#endif
public override bool Equals(object rhsObj)
{
if (rhsObj == null)
return false;
NSObject rhs = rhsObj as NSObject;
return this == rhs;
}
public bool Equals(NSObject rhs)
{
return this == rhs;
}
public static bool operator==(NSObject lhs, NSObject rhs)
{
if (object.ReferenceEquals(lhs, rhs))
return true;
if ((object) lhs == null || (object) rhs == null)
return false;
if (lhs.IsDeallocated() && rhs.IsDeallocated())
return object.ReferenceEquals(lhs, rhs);
else if (lhs.IsDeallocated())
return false;
else if (rhs.IsDeallocated())
return false;
return lhs.isEqual(rhs);
}
public static bool operator!=(NSObject lhs, NSObject rhs)
{
return !(lhs == rhs);
}
public override int GetHashCode()
{
return hash();
}
[ThreadModel(ThreadModel.SingleThread)]
internal static void Register(Type klass, string nativeName)
{
if (!ms_registeredClasses.ContainsKey(nativeName))
ms_registeredClasses.Add(nativeName, klass);
else
throw new InvalidOperationException(nativeName + " has already been registered.");
}
internal IntPtr GetBaseClass()
{
return m_baseClass;
}
internal void Deallocated()
{
if (!m_deallocated)
{
// Allow the managed classes to clean up their state.
OnDealloc();
Contract.Assert(m_deallocated, "base.OnDealloc wasn't called");
// Remove the instance from our list.
lock (ms_instancesLock)
{
bool removed = ms_instances.Remove(m_instance);
Contract.Assert(removed, "dealloc was called but the instance is not in ms_instances");
}
// Allow the unmanaged base class to clean itself up. Note that we have to be
// careful how we do this to avoid falling into infinite loops...
if (m_instance != IntPtr.Zero)
{
IntPtr klass = DoGetNonExportedBaseClass();
Native native = new Native(m_instance, Selector.Dealloc, klass);
Unused.Value = native.Invoke();
}
}
}
#region Protected Methods
/// <summary>Called just before the unmanaged instance of an exported type is deleted.</summary>
/// <remarks>Typically this is where you will release any objects you have retained. Note
/// that the base OnDealloc method must be called (if you don't an <see cref = "ContractException">ContractException</see>
/// will be thrown).</remarks>
protected virtual void OnDealloc()
{
m_deallocated = true;
}
// mono 2.8 no longer calls the static NSObject ctor when a Class ctor is called.
// This screws Class up because it winds up using objc_getClass before we can
// register types. So, we provide this method for Class to call to force the static
// ctor to execute.
protected static void OnForceInit()
{
}
#endregion
#region Private Methods
private IntPtr DoGetNonExportedBaseClass()
{
IntPtr klass = object_getClass(m_instance);
while (klass != IntPtr.Zero)
{
IntPtr ptr = class_getName(klass);
string name = Marshal.PtrToStringAnsi(ptr);
Type type;
if (!Registrar.TryGetType(name, out type))
break;
klass = class_getSuperclass(klass);
}
Contract.Assert(klass != IntPtr.Zero, "couldn't find a non-exported base class"); // should have found NSObject at least
return klass;
}
private static Type DoGetManagedClass(IntPtr klass)
{
while (klass != IntPtr.Zero)
{
IntPtr ptr = class_getName(klass);
string name = Marshal.PtrToStringAnsi(ptr);
Type type;
if (Registrar.TryGetType(name, out type))
return type;
else if (ms_registeredClasses.TryGetValue(name, out type))
return type;
klass = class_getSuperclass(klass);
}
return null;
}
#endregion
#region P/Invokes
[DllImport("/usr/lib/libobjc.dylib")]
private extern static IntPtr object_getClass(IntPtr obj);
[DllImport("/usr/lib/libobjc.dylib")]
private extern static IntPtr class_getName(IntPtr klass);
[DllImport("/usr/lib/libobjc.dylib")]
private extern static IntPtr class_getSuperclass(IntPtr klass);
[DllImport("/usr/lib/libobjc.dylib")]
private extern static IntPtr object_getInstanceVariable(IntPtr obj, string name, ref IntPtr outValue);
[DllImport("/usr/lib/libobjc.dylib")]
private extern static IntPtr object_setInstanceVariable(IntPtr obj, string name, IntPtr value);
#endregion
#region Fields
private readonly IntPtr m_instance;
private readonly IntPtr m_class;
private readonly IntPtr m_baseClass;
private volatile bool m_deallocated;
private static Dictionary<string, Type> ms_registeredClasses = new Dictionary<string, Type>();
private static object ms_instancesLock = new object();
private static Dictionary<IntPtr, NSObject> ms_instances = new Dictionary<IntPtr, NSObject>();
private static Dictionary<Type, bool> ms_exports = new Dictionary<Type, bool>();
private static Dictionary<Type, Func<IntPtr, NSObject>> ms_factories = new Dictionary<Type, Func<IntPtr, NSObject>>();
private static Type[] ms_factoryArgTypes = new Type[]{typeof(IntPtr)};
#if DEBUG
private static WeakList<NSObject> ms_refs = new WeakList<NSObject>(64);
#endif
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FromVideo
{
class Program
{
static void Main(string[] args)
{
Product milk = new Product("Prqsno plqko", "Tranpsort OOD", "Mlqko ot krava", 2.00m);
milk.Quantity = 3;
milk.Weight = 4;
Product cheese = new Product("Bqlo sirene", "Sirene i vino", "Sirene ot shtastlivi jivotni", 15);
cheese.Quantity = 0;
cheese.Weight = 0;
Product yellowCheese = new Product("Kashkaval", "Transport ODD", "Kashkaval.....", 25);
yellowCheese.Quantity = 0;
yellowCheese.Weight = 0;
ProductsContext context = new ProductsContext();
context.Products.Add(milk);
context.Products.Add(cheese);
context.Products.Add(yellowCheese);
context.SaveChanges();
}
}
}
|
using System;
using System.Data.Entity;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using GymWorkout.Data;
using GymWorkout.Entity.Foods;
using WPFCustomMessageBox;
namespace GymWorkout.Views
{
/// <summary>
/// Interaction logic for vwFoodUnits.xaml
/// </summary>
public partial class vwFoodUnits : Window
{
private readonly GymContext _context = new GymContext();
private FoodUnit _foodUnit = new FoodUnit();
public vwFoodUnits()
{
var splashScreen = new SplashScreenWindow();
splashScreen.Show();
InitializeComponent();
BindGrid();
GbAddEdit.DataContext = _foodUnit;
splashScreen.Close();
}
#region Commands
private void DeleteCommandBinding_OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void DeleteCommandBinding_OnExecuted(object sender, ExecutedRoutedEventArgs e)
{
var student = GrdList.SelectedItem as FoodUnit;
if (student != null && CustomMessageBox.ShowYesNo($"جهت حذف رکورد '{student.Title}' اطمینان دارید ؟", "حذف رکورد", "بله", "خیر", MessageBoxImage.Warning)
== MessageBoxResult.Yes)
{
_context.FoodUnits.Attach(student);
_context.Entry(student).State = EntityState.Deleted;
_context.SaveChanges();
Reset();
CustomMessageBox.ShowOK("اطلاعات شما با موفقیت حذف گردید.", "حذف", "بسیار خوب");
}
}
#endregion
#region Events Methods
private void GrdList_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (GrdList.Items.Count > 0)
{
_foodUnit = (FoodUnit)GrdList.SelectedItem;
GbAddEdit.DataContext = _foodUnit;
GbAddEdit.Header = $"ویرایش '{_foodUnit.Title}'";
BtnSave.Content = "ویرایش";
BtnSave.Background = new SolidColorBrush(Color.FromRgb(247, 194, 44));
}
}
private void BtnSave_OnClick(object sender, RoutedEventArgs e)
{
if (CustomMessageBox.ShowYesNo("جهت ثبت اطلاعات اطمینان دارید ؟", "ثبت اطلاعات", "بله", "خیر", MessageBoxImage.Information)
== MessageBoxResult.Yes)
{
if (_foodUnit.Id == 0)
{
_foodUnit.CreateDate = DateTime.Now;
_context.FoodUnits.Add(_foodUnit);
}
else
{
_context.FoodUnits.Attach(_foodUnit);
_context.Entry(_foodUnit).State = EntityState.Modified;
}
_context.SaveChanges();
Reset();
CustomMessageBox.ShowOK("اطلاعات شما با موفقیت ثبت گردید.", "موفقیت آمیز", "بسیار خوب");
}
}
private void BtnCancel_OnClick(object sender, RoutedEventArgs e)
{
Reset();
}
private void BtnClose_OnClick(object sender, RoutedEventArgs e)
{
this.Close();
}
#endregion
#region Methods
private void Reset()
{
_foodUnit = new FoodUnit();
GbAddEdit.DataContext = _foodUnit;
BtnSave.Content = GbAddEdit.Header = "افزودن";
BtnSave.Background = new SolidColorBrush(Color.FromRgb(92, 184, 92));
BindGrid();
}
private void BindGrid()
{
GrdList.ItemsSource = _context.FoodUnits.ToList();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MatrixTavolsag
{
class Program
{
static void Main(string[] args)
{
int N = 9; // int.Parse(Console.ReadLine());
int[,] matrix = new int[N,N];
feltolt(matrix);
kiir(matrix);
Console.WriteLine();
tavolsag(matrix, N);
Console.ReadKey();
}
static void feltolt(int[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i,j] = 0;
}
}
}
static void kiir(int[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i,j] + " ");
}
Console.WriteLine();
}
}
static void tavolsag(int[,] matrix, int N)
{
N--;
int meh = 0;
int meh2 = 0;
for (int i = 1; i < matrix.GetLength(0); i++)
{
for (int j = 1; j < matrix.GetLength(1); j++)
{
int min = N;
if(min > i)
{
min = i;
}
if(min > j)
{
min = j;
}
if (min > N-i)
{
min = N - i;
}
if(min > N-j)
{
min = N - j;
}
matrix[i, j] = min;
}
}
kiir(matrix);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Models.ViewModels
{
public class BookingVm
{
public int BookingId { get; set; }
public string CustomerEmail { get; set; }
public int TimeId { get; set; }
public DateTime Time_Slot { get; set; }
public String BktName { get; set; }
public int BkpId { get; set; }
public string BkpName { get; set; }
public string PackageDescription { get; set; }
public DateTime DateBookingFor { get; set; }
public DateTime? DateBooked { get; set; }
public decimal? Price { get; set; }
public string Status { get; set; }
}
}
|
// Bar POS, class ProductManagmentScreen
// Versiones:
// V0.01 15-May-2018 Moisés: Basic skeleton
// V0.02 16-May-2018 Moisés: Event to close the form
// V0.03 18-May-2018 Moisés: Add method, initialize method, method to move
// forward and backward, delete Product
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace BarPOS
{
public partial class ProductsManagmentScreen : Form
{
private ProductManagementClass ProductManagement;
private SearchScreen searchScreen;
Languajes languaje;
public ProductsManagmentScreen(ProductsList products, Languajes languaje)
{
ProductManagement = new ProductManagementClass(products);
searchScreen = new SearchScreen(languaje);
InitializeComponent();
Draw();
this.languaje = languaje;
drawTexts();
}
private void drawTexts()
{
switch (languaje)
{
case Languajes.Castellano:
btnBackToMainMenu.Text = "Volver al menu";
lblDescription.Text = "Descripción:";
lblPrice.Text = "Precio:";
lblStock.Text = "Stock:";
lblMinimunStock.Text = "Stock mínimo:";
lblCategory.Text = "Categoría:";
lblBuyPrice.Text = "Precio compra:";
lblCode.Text = "Codigo:";
btnBack.Text = "Volver";
btnModify.Text = "Modificar";
btnDelete.Text = "Borrar";
btnAdd.Text = "Añadir";
btnValidate.Text = "Añadir";
btnSearch.Text = "Buscar";
lblProduct.Text = "Producto";
break;
case Languajes.English:
btnBackToMainMenu.Text = "Back to main";
lblDescription.Text = "Description:";
lblPrice.Text = "Price:";
lblStock.Text = "Stock:";
lblMinimunStock.Text = "Minimun Stock:";
lblCategory.Text = "Category:";
lblBuyPrice.Text = "Buy Price:";
lblCode.Text = "Code:";
btnBack.Text = "Back";
btnModify.Text = "Modify";
btnDelete.Text = "Delete";
btnAdd.Text = "Add";
btnValidate.Text = "Add";
btnSearch.Text = "Search";
lblProduct.Text = "Product";
break;
}
}
//Method to draw the actual product
public void Draw()
{
if (ProductManagement.Count < 1)
{
Controls.Clear();
InitializeComponent();
lblIndex.Text = "0/0";
}
else
{
Product actualProduct =
ProductManagement.GetActualProduct();
lblIndex.Text =
ProductManagement.Index + "/" + ProductManagement.Count;
txtCode.Text = actualProduct.Code.ToString("000");
pbImage.ImageLocation = actualProduct.ImagePath;
txtBuyPrice.Text = actualProduct.BuyPrice + "";
txtCategory.Text = actualProduct.Category + "";
txtMinimunStock.Text = actualProduct.MinimunStock + "";
txtName.Text = actualProduct.Description + "";
txtPrice.Text = actualProduct.Price + "";
txtStock.Text = actualProduct.Stock + "";
}
drawTexts();
}
public void Save()
{
string errorCode = ProductManagement.Save();
if (errorCode != "")
{
MessageBox.Show(errorCode);
}
}
//Event to close the window
private void btnClose_Click(object sender, System.EventArgs e)
{
Application.Exit();
}
private void btnAdd_Click(object sender, EventArgs e)
{
this.Controls.Clear();
this.InitializeComponent();
if (ProductManagement.Count == 0)
{
this.txtCode.Text = "001";
}
else
{
this.txtCode.Text = (ProductManagement.Count + 1).
ToString("000");
}
lblIndex.Text =
(ProductManagement.Index + 1) + "/" + ProductManagement.Count;
this.btnForward.Visible = false;
this.btnBackward.Visible = false;
this.btnAdd.Visible = false;
this.btnDelete.Visible = false;
this.btnModify.Visible = false;
this.btnSearch.Visible = false;
this.btnValidate.Visible = true;
}
private void add()
{
try
{
Product newProduct = new Product();
newProduct.ImagePath = pbImage.ImageLocation;
newProduct.BuyPrice = Convert.ToDouble(txtBuyPrice.Text);
newProduct.Category = txtCategory.Text;
newProduct.Code = Convert.ToInt32((
ProductManagement.Count + 1).ToString("000"));
newProduct.Description = txtName.Text;
newProduct.MinimunStock =
Convert.ToInt32(txtMinimunStock.Text);
newProduct.Price = Convert.ToDouble(txtPrice.Text);
newProduct.Stock = Convert.ToInt32(txtStock.Text);
ProductManagement.Add(newProduct);
Save();
}
catch (Exception)
{
MessageBox.Show("Error guardando el producto");
}
this.Controls.Clear();
InitializeComponent();
Draw();
}
private void validate_Click(object sender, EventArgs e)
{
add();
}
private void btnBackward_Click(object sender, EventArgs e)
{
if (ProductManagement.Count > 1 && !ProductManagement.DrawFounds)
{
modify();
}
ProductManagement.MoveBackward();
Draw();
}
private void btnForward_Click(object sender, EventArgs e)
{
if (ProductManagement.Count > 1 && !ProductManagement.DrawFounds)
{
modify();
}
ProductManagement.MoveForward();
Draw();
}
private void btnDelete_Click(object sender, EventArgs e)
{
ProductManagement.Remove();
Save();
Draw();
}
private void pbImage_Click(object sender, EventArgs e)
{
OpenFileDialog getImage = new OpenFileDialog();
getImage.InitialDirectory = Application.StartupPath + @"\imgs\";
getImage.Filter = "Archivos de Imagen (*.jpg)(*.jpeg)(*.png)| " +
"*.jpg;*.jpeg;*.png; | All files(*.*) | *.* ";
if (getImage.ShowDialog() == DialogResult.OK)
{
string fileName = getImage.FileName.Substring(
getImage.FileName.LastIndexOf('\\'));
string sourceFile = getImage.FileName;
string destFile =
Application.StartupPath + @"\imgs\" + fileName;
if (!File.Exists(destFile))
{
File.Copy(sourceFile, destFile, true);
}
this.pbImage.ImageLocation = Application.StartupPath
+ "\\imgs\\" + fileName;
}
else
{
MessageBox.Show("No se selecciono ninguna imagen");
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
searchScreen.StartPosition = FormStartPosition.CenterParent;
searchScreen.ShowDialog();
if (ProductManagement.Search(searchScreen.TextToSearch))
{
Draw();
pnlTopBar.BackColor = Color.Gold;
this.btnBack.Visible = true;
this.btnAdd.Visible = false;
this.btnModify.Visible = false;
}
else
{
MessageBox.Show("No results found");
}
}
private void btnBack_Click(object sender, System.EventArgs e)
{
this.btnBack.Visible = false;
this.btnAdd.Visible = true;
this.btnModify.Visible = true;
ProductManagement.DrawFounds = false;
pnlTopBar.BackColor = Color.Gainsboro;
//restarting the found attribute
for (int i = 1; i <= ProductManagement.Count; i++)
{
ProductManagement.Products.Get(i).Found = false;
}
}
private void btnBackToMainMenu_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnModify_Click(object sender, EventArgs e)
{
modify();
}
private void modify()
{
try
{
Product newProduct = new Product();
newProduct.ImagePath = pbImage.ImageLocation;
newProduct.BuyPrice = Convert.ToDouble(txtBuyPrice.Text);
newProduct.Category = txtCategory.Text;
newProduct.Code = Convert.ToInt32(txtCode.Text);
newProduct.Description = txtName.Text;
newProduct.MinimunStock =
Convert.ToInt32(txtMinimunStock.Text);
newProduct.Price = Convert.ToDouble(txtPrice.Text);
newProduct.Stock = Convert.ToInt32(txtStock.Text);
ProductManagement.Modify(newProduct);
Save();
}
catch (Exception)
{
MessageBox.Show("Error guardando el producto");
}
this.Controls.Clear();
InitializeComponent();
Draw();
}
private void any_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
if (btnModify.Visible)
{
modify();
}
else
{
add();
}
}
}
}
}
|
using System.Data.Entity.ModelConfiguration;
using Properties.Core.Objects;
namespace Properties.Infrastructure.Data.Mapping
{
public class UploadMap : EntityTypeConfiguration<Upload>
{
public UploadMap()
{
Property(u => u.UploadReference)
.HasMaxLength(25);
Property(u => u.Url)
.HasColumnType("nvarchar")
.HasMaxLength(255);
Ignore(p => p.IsDirty);
}
}
}
|
using OrchardCore.ContentManagement;
namespace DFC.ServiceTaxonomy.Title.Models
{
public class UniqueTitlePart : ContentPart
{
public string? Title { get; set; }
}
}
|
using ApiSGCOlimpiada.Models;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSGCOlimpiada.Data.UsuarioDAO
{
public class FuncaoDAO : IFuncaoDAO
{
private readonly string _conn;
public FuncaoDAO(IConfiguration config)
{
_conn = config.GetConnectionString("conn");
}
MySqlConnection conn;
MySqlDataAdapter adapter;
MySqlCommand cmd;
DataTable dt;
public bool Add(Funcao funcao)
{
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Insert into Funcao values(null, '{funcao.funcao}')", conn);
int rows = cmd.ExecuteNonQuery();
if (rows != -1)
{
return true;
}
return false;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
conn.Close();
}
}
public Funcao Find(long id)
{
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Select * from Funcao where id = {id}", conn);
adapter = new MySqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
Funcao funcao = new Funcao();
foreach (DataRow item in dt.Rows)
{
funcao.Id = Convert.ToInt64(item["Id"]);
funcao.funcao = item["funcao"].ToString();
}
return funcao;
}
catch
{
return null;
}
finally
{
conn.Close();
}
}
public IEnumerable<Funcao> GetAll()
{
try
{
List<Funcao> funcaos = new List<Funcao>();
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Select * from Funcao", conn);
adapter = new MySqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow item in dt.Rows)
{
Funcao funcao = new Funcao();
funcao.Id = Convert.ToInt64(item["Id"]);
funcao.funcao = item["funcao"].ToString();
funcaos.Add(funcao);
}
return funcaos;
}
catch
{
return null;
}
finally
{
conn.Close();
}
}
public bool Remove(long id)
{
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Delete from Funcao where id = {id}", conn);
int rows = cmd.ExecuteNonQuery();
if (rows != -1)
{
return true;
}
return false;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
conn.Close();
}
}
public bool Update(Funcao funcao, long id)
{
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Update Funcao set Funcao = {funcao.funcao} where id = {id}", conn);
int rows = cmd.ExecuteNonQuery();
if (rows != -1)
{
return true;
}
return false;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
conn.Close();
}
}
}
}
|
using System.Configuration;
namespace Properties
{
internal sealed class Settings : ApplicationSettingsBase
{
private static Settings defaultInstance = (Settings)Synchronized(new Settings());
public static Settings Default => defaultInstance;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace PayRoll
{
public partial class ApplyLeave : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["euname"] != null && Session["epass"] != null)
{
EmployeeName();
}
else
{
Response.Redirect("Login.aspx");
}
}
}
void EmployeeName()
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select EmpId,Name from Employee", con);
DataSet ds = new DataSet();
da.Fill(ds);
ddlname.DataSource = ds;
ddlname.DataValueField = "EmpId";
ddlname.DataBind();
ddlname.Items.Insert(0, "--Select EmployeeId--");
}
protected void btnupdate_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into ApplyLeave(EmpId,DateOfLeave,LeaveStatus,Reason) values('" + ddlname.SelectedValue + "','" + txtldt.Text + "','" + txtlst.Text + "','" + txtreason.Text + "')", con);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
lblmsg.Text = "Leave Apply Insert Successfully";
}
else
{
lblmsg.Text = "Leave Apply Not Insert";
}
con.Close();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.