text stringlengths 13 6.01M |
|---|
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
using Com.Tencent.MM.Sdk.Constants;
using Com.Tencent.MM.Sdk.Modelbase;
using Com.Tencent.MM.Sdk.Openapi;
using RRExpress.Droid.WXPay;
namespace RRExpress.Droid {
[Activity(Name = "com.halogo.bt.wxapi.WXPayEntryActivity",
Exported = true,
Label = "WXPayEntryActivity")]
public class WXPayEntryActivity : Activity, IWXAPIEventHandler {
private IWXAPI msgApi;
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
// Create your application here
msgApi = WXAPIFactory.CreateWXAPI(this.ApplicationContext, Constants.APPID);
}
protected override void OnNewIntent(Intent intent) {
base.OnNewIntent(intent);
this.Intent = (intent);
msgApi.HandleIntent(intent, this);
}
/// <summary>
/// 接受微信发来的消息
/// </summary>
/// <param name="p0"></param>
public void OnReq(BaseReq p0) {
switch (p0.Type) {
default:
break;
}
}
/// <summary>
/// 接受发往微信的消息的回调
/// </summary>
/// <param name="p0"></param>
public void OnResp(BaseResp p0) {
//int result = 0;
Toast.MakeText(this, "支付结果:" + p0.ErrStr, ToastLength.Long).Show();
if (p0.Type == ConstantsAPI.CommandPayByWx) {
switch (p0.ErrorCode) {
case BaseResp.ErrCode.ErrOk:
break;
case BaseResp.ErrCode.ErrSentFailed:
break;
case BaseResp.ErrCode.ErrAuthDenied:
break;
case BaseResp.ErrCode.ErrUserCancel:
break;
default:
break;
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using TimeClock.Data.Models;
namespace Timeclock.Api.Models
{
public class EmployeeBindingModel
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? LastPunchTime { get; set; }
public TimePunchStatus CurrentStatus { get; set; }
public bool RequiresAuthentication { get; set; }
public string FullName
{
get { return FirstName + " " + LastName; }
}
public string CurrentStatusClass
{
get
{
return CurrentStatus == TimePunchStatus.PunchedIn ?
"punched-in" : "punched-out";
}
}
}
public class EmployeeAddBindingMdoel
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public int? PIN { get; set; }
}
public class EmployeeEditBindingModal
{
[Required]
public int EmployeeId { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public int? PIN { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Microsoft.AspNet.Identity;
using BitClassroom.DAL.Models;
using System.Threading;
namespace BitClassroom.API.Controllers
{
public class QuestionResponsesController : ApiController
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: api/QuestionResponses
public IQueryable<QuestionResponse> GetQuestionResponses()
{
return db.QuestionResponses;
}
// GET: api/QuestionResponses/5
[ResponseType(typeof(QuestionResponse))]
public IHttpActionResult GetQuestionResponse(int id)
{
QuestionResponse questionResponse = db.QuestionResponses.Find(id);
if (questionResponse == null)
{
return NotFound();
}
return Ok(questionResponse);
}
// PUT: api/QuestionResponses/5
[ResponseType(typeof(void))]
public IHttpActionResult PutQuestionResponse(int id, QuestionResponse questionResponse)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != questionResponse.Id)
{
return BadRequest();
}
db.Entry(questionResponse).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!QuestionResponseExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/QuestionResponses
[ResponseType(typeof(QuestionResponse))]
public IHttpActionResult PostQuestionResponse(QuestionResponse questionResponse)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Thread.Sleep(1000);
questionResponse.MentorId = this.User.Identity.GetUserId();
var surveyQuestion = db.SurveyQuestions.Where(x => x.Id == questionResponse.QuestionId).FirstOrDefault();
questionResponse.SurveyQuestion = surveyQuestion;
db.QuestionResponses.Add(questionResponse);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = questionResponse.Id }, questionResponse);
}
// DELETE: api/QuestionResponses/5
[ResponseType(typeof(QuestionResponse))]
public IHttpActionResult DeleteQuestionResponse(int id)
{
QuestionResponse questionResponse = db.QuestionResponses.Find(id);
if (questionResponse == null)
{
return NotFound();
}
db.QuestionResponses.Remove(questionResponse);
db.SaveChanges();
return Ok(questionResponse);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool QuestionResponseExists(int id)
{
return db.QuestionResponses.Count(e => e.Id == id) > 0;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Baihoc7_KeThuav1
{
class Program
{
static void Main(string[] args)
{
//Con c = new Con();
//c.In();
//c.In2();
//Cha cha = new Cha("Toan");
Con con = new Con("Nguyen Van", "Toan");
// Cha cha1 = con;
//con.In2();
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Engine.Characters
{
class LifeMonster : Monster
{
public const bool isKills=true;
public LifeMonster(int id, string name)
:base( id, name, isKills)
{
}
}
} |
namespace Sentry;
/// <summary>
/// Immutable data belonging to a transaction.
/// </summary>
public interface ITransactionData : ISpanData, ITransactionContext, IEventLike
{
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace com.Sconit.Web.Models.SearchModels.ORD
{
public class ReceiptMasterSearchModel : SearchModelBase
{
public string ReceiptNo { get; set; }
public string IpNo { get; set; }
public string OrderNo { get; set; }
public string PartyFrom { get; set; }
public string PartyTo { get; set; }
public int? GoodsReceiptOrderType { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string Dock { get; set; }
public int? Status { get; set; }
public string Item { get; set; }
public string ExternalReceiptNo { get; set; }
public int? OrderSubType { get; set; }
public int? IpDetailType { get; set; }
public int? OrderType { get; set; }
public string ManufactureParty { get; set; }
public string Flow { get; set; }
public string CreateUserName { get; set; }
public bool IsReturn { get; set; }
public bool IsDiff { get; set; }
//public int? OrderType { get; set; }
}
} |
using Crainiate.Diagramming;
using Crainiate.Diagramming.Flowcharting;
using Crainiate.Diagramming.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FlowchartConverter.CodeGeneration;
using FlowchartConverter.Nodes;
namespace FlowchartConverter
{
public partial class Form1 : Form
{
Controller controller;
TerminalNode terminalS;
TerminalNode terminalE;
public Form1()
{
InitializeComponent();
controller = new Controller(diagram1);
}
private void button1_Click_1(object sender, EventArgs e)
{
String str = controller.getCode(Controller.Language.CPP);
MessageBox.Show(str);
}
private void deleteBtn_Click(object sender, EventArgs e)
{
controller.DeleteChoosed = true;
}
private void diagram1_MouseClick_1(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
controller.cancelClickedButtons();
}
}
private void xmlBtn_Click(object sender, EventArgs e)
{
controller.saveProject("F:\\");
//MessageBox.Show(ps.XmlString);
}
private void onLoad_click(object sender, EventArgs e)
{
//initializeNodes(BaseNode.Model);
controller.loadProject("F:\\testxml.xml");
}
private void clearBtn_Click(object sender, EventArgs e)
{
controller.newProject();
}
private void DialogsBtn_Click(object sender, EventArgs e)
{
controller.AllowMove = true;
}
private void open_button_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
opf.Filter = "Xml Source (*.xml)|*.xml";
string path = null;
if (DialogResult.OK == opf.ShowDialog())
{
path = opf.FileName;
}
else
{
return;
}
controller.loadProject(path);
}
private void save_button_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Xml Source (*.xml)|*.xml";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
controller.saveProject(saveFileDialog.FileName);
}
else
return;
}
private void move_button_Click(object sender, EventArgs e)
{
controller.AllowMove = true;
}
private void clear_button_Click(object sender, EventArgs e)
{
controller.newProject();
}
private void delete_button_Click(object sender, EventArgs e)
{
controller.DeleteChoosed = true;
}
private void sourceCodeButton_Click(object sender, EventArgs e)
{
string cppStr = controller.getCode(Controller.Language.CPP);
string cSharpStr = controller.getCode(Controller.Language.CSHARP);
// MessageBox.Show(cppStr);
// MessageBox.Show(cSharpStr);
CodeForm code = new CodeForm();
code.setMeta(cppStr, cSharpStr);
code.set(cppStr);
code.Show();
}
private void export_button_Click(object sender, EventArgs e)
{
var fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
Crainiate.Diagramming.Forms.FormsDocument _fd = new FormsDocument(diagram1.Model);
_fd.Export(fbd.SelectedPath + "output.jpg", ExportFormat.Jpeg);
}
}
}
}
|
using RSS_news_feed_bot.data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
namespace RSS_news_feed_bot.bot
{
public interface IAnswer
{
/// <summary>
/// Текст ответа по умолчанию
/// </summary>
string PositiveAnswer { get; }
/// <summary>
/// Текст отрицательного ответа
/// </summary>
Dictionary<string, string> NegativeAnswer { get; }
/// <summary>
/// Описание команды
/// </summary>
string CommandDescription { get; }
/// <summary>
/// Список имен с вызовом команды
/// </summary>
List<string> CallCommandList { get; }
/// <summary>
/// Обработчик
/// </summary>
/// <param name="message"></param>
/// <param name="allUsers"></param>
void Process(Message message, AllUsers allUsers);
}
}
|
using DG.Tweening;
using PixelCrushers.DialogueSystem;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BattleAreaMgr2 : MonoBehaviour
{
public static BattleAreaMgr2 instance;
public Transform PlayerSpawnPoint;
public Transform EnemySpawnPoint;
public Transform PlayerStandPoint;
public Transform NextAreaPoint;
public Transform PlayerAttackPoint;
public float playerHp;
public float enemyHp;
public List<GameObject> EnvList;
private void Awake()
{
instance = this;
}
private void OnDestroy()
{
EventCenter.GetInstance().Clear();
}
public PlayerInfo nowPlayerInfo;
public EnemyInfo nowEnemyInfo;
public void Init()
{
nowPlayerInfo = BattleSys.GetInstance().playerInfo;
//CreatPlayer();
Invoke("CreatPlayer", 2.5f);
EventCenter.GetInstance().AddEventListener(EventDic.ControllAreaEnemyAttack, EnemyAttack);
EventCenter.GetInstance().AddEventListener<AttackInfo>(EventDic.ControllAreaPlayerAttack, PlayerAttack);
EventCenter.GetInstance().AddEventListener(EventDic.PlayerDie, PlayerDie);
EventCenter.GetInstance().AddEventListener(EventDic.EnemyDie, EnemyDie);
EventCenter.GetInstance().AddEventListener(EventDic.PlayerReachedStandPoint, PlayerReachedStandPoint);
EventCenter.GetInstance().AddEventListener<int>(EventDic.EnemyAttackCounterReduce, EnemyAttackCounterReduce);
SetEnvBackGround();
//EventCenter.GetInstance().AddEventListener(EventDic.EnemyHitAnimation,nowEnemyInfo.);
}
private void SetEnvBackGround()
{
string levelName = BattleSys.GetInstance().levelAward.levelName;
ResMgr.GetInstance().LoadAsync<GameObject>(GameConfig.GetInstance().GetEnvPath(levelName),(obj)=>
{
obj.transform.SetParent(this.transform);
obj.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1);
obj.GetComponent<RectTransform>().anchoredPosition3D = new Vector3(0,0,0);
});
//throw new NotImplementedException();
}
private void EnemyAttackCounterReduce(int arg0)
{
nowEnemyInfo.nowAttackCounter -= arg0;
if (nowEnemyInfo.nowAttackCounter <= 0)
{
EventCenter.GetInstance().EventTrigger(EventDic.ControllAreaEnemyAttack);
nowEnemyInfo.nowAttackCounter = nowEnemyInfo.attackCounter;
}
EventCenter.GetInstance().EventTrigger<float>(EventDic.EnemyHPBarUpdate, nowEnemyInfo.hp);
//EventCenter.GetInstance().EventTrigger<EnemyInfo>()
//throw new NotImplementedException();
}
private void Update()
{
try
{
//Debug.Log(nowPlayerInfo.atk);
//Debug.Log(nowEnemyInfo.hp);
playerHp = nowPlayerInfo.hp;
enemyHp = nowEnemyInfo.hp;
}
catch { };
if (Input.GetKeyDown(KeyCode.P))
{
foreach (var item in BattleSys.GetInstance().questList)
{
Debug.Log("B" + item.questType);
}
}
}
private void PlayerReachedStandPoint()
{
nowPlayerInfo.StopRun();
CreatNextMonsterOrLevelClear();
EventCenter.GetInstance().EventTrigger(EventDic.BGMoveAbleChange);
//throw new NotImplementedException();
}
private void CreatNextMonsterOrLevelClear()
{
nowEnemyInfo = BattleSys.GetInstance().SendNewEnemy();
if (nowEnemyInfo == null)
{
//todo关卡完成
CreatAwardBox();
nowPlayerInfo.Win();
}
else
{
nowEnemyInfo.obj = ResMgr.GetInstance().Load<GameObject>(nowEnemyInfo.objPath);
nowEnemyInfo.obj.transform.position = EnemySpawnPoint.position;
nowEnemyInfo.animator = nowEnemyInfo.obj.GetComponent<Animator>();
ControlAreaMgr.instance.UnLockControlArea();
EventCenter.GetInstance().EventTrigger<float>(EventDic.InitEnemyHPBar,nowEnemyInfo.hp);
}
Debug.Log(nowEnemyInfo.objPath);
Debug.Log(nowEnemyInfo.obj.name);
nowEnemyInfo.obj.GetComponent<DialogueSystemTrigger>().barkText = nowEnemyInfo.enterWord;
//throw new NotImplementedException();
}
private void CreatAwardBox()
{
Debug.Log("创建宝箱");
EventCenter.GetInstance().EventTrigger(EventDic.BGMoveAbleChange);
var obj= ResMgr.GetInstance().Load<GameObject>("ResObj/other/baoxiang/baoxiang");
obj.transform.position = EnemySpawnPoint.position;
EventCenter.GetInstance().EventTrigger<QuestType>(EventDic.QuestCheack, QuestType.PlayerHpLeft);
Invoke("ShowWinPanel", 1.5f );
//throw new NotImplementedException();
}
void ShowWinPanel()
{
UIManager.GetInstance().ShowPanel<Panel_levelWin>("Panel_levelWin",E_UI_Layer.Top,(obj)=>
{
obj.Init();
});
EventCenter.GetInstance().EventTrigger(EventDic.LevelClear);
}
private void EnemyDie()
{
PlayPlayerEnterNextAreaAnimation();
EventCenter.GetInstance().EventTrigger(EventDic.Game2Change);
//throw new NotImplementedException();
}
private void PlayPlayerEnterNextAreaAnimation()
{
ControlAreaMgr.instance.LockControlArea();
//quence = DOTween.Sequence();
ControlAreaMgr.instance.LockControlArea(); //lockcon
nowPlayerInfo.Run();
EventCenter.GetInstance().EventTrigger(EventDic.BGMoveAbleChange);
Tweener tweener = nowPlayerInfo.obj.transform.DOMove(NextAreaPoint.position, 3f);
tweener.onComplete += () =>
{
nowPlayerInfo.obj.transform.position = PlayerSpawnPoint.position;
PlayPlayerEnterAnimation();
EventCenter.GetInstance().EventTrigger(EventDic.BGMoveAbleChange);
nowPlayerInfo.StopRun();
ControlAreaMgr.instance.UnLockControlArea();
};
//quence.Append(tweener);
//throw new NotImplementedException();
}
private void PlayerDie()
{
//Debug.Log("Die");
//EventCenter.GetInstance().EventTrigger(EventDic.PlayerDie);
//throw new NotImplementedException();
}
Sequence quence;
private void PlayerAttack(AttackInfo attackInfo)
{
if (nowPlayerInfo.obj.GetComponent<Animator>().GetBool("die") == false)
{
var atk = nowPlayerInfo.atk;//buff
EventCenter.GetInstance().EventTrigger<QuestType>(EventDic.QuestCheack, QuestType.AttackCount);
nowPlayerInfo.Run();
quence = DOTween.Sequence();
Tweener tweener = nowPlayerInfo.obj.transform.DOMove(PlayerAttackPoint.position, 1f);
//Tweener tweener2 = nowPlayerInfo.obj.transform.DOMove(nowPlayerInfo.obj.transform.position, 1f);
Tweener tweener2 = nowPlayerInfo.obj.transform.DOMove(PlayerStandPoint.position, 1f);
tweener.onComplete += () =>
{
nowPlayerInfo.StopRun();
nowPlayerInfo.Attack();
nowEnemyInfo.GetHit(atk, attackInfo);
EventCenter.GetInstance().EventTrigger<float>(EventDic.EnemyHPBarUpdate, nowEnemyInfo.hp);
//Debug.Log(nowEnemyInfo.hp);
};
//tweener2.onComplete += () => { nowPlayerInfo.obj.transform.DOMove(PlayerStandPoint.position, 0.5f,false); };
quence.Append(tweener);
quence.AppendInterval(1);
quence.Append(tweener2);
}
//quence.AppendInterval(1);
//nowPlayerInfo.StopRun();
//throw new NotImplementedException();
}
private void EnemyAttack()
{
nowPlayerInfo.GetHit(nowEnemyInfo.atk);
EventCenter.GetInstance().EventTrigger<float>(EventDic.PlayerHPBarUpdate, nowPlayerInfo.hp);
nowEnemyInfo.Attack();
//throw new NotImplementedException();
}
private void Start()
{
//Invoke("ttt", 3f);
//Debug.Log(BattleSys.GetInstance().questList[0].describe);
//var list = BattleSys.GetInstance().questList;
}
void ttt()
{
//foreach (var item in BattleSys.questList)
//{
// Debug.Log(item.questType + " " + item.targetNumber);
//}
}
private void CreatPlayer()
{
nowPlayerInfo.obj= ResMgr.GetInstance().Load<GameObject>(nowPlayerInfo.objPath);
nowPlayerInfo.animator = nowPlayerInfo.obj.GetComponent<Animator>();
nowPlayerInfo.obj.transform.position = PlayerSpawnPoint.position;
PlayPlayerEnterAnimation();
EventCenter.GetInstance().EventTrigger<float>(EventDic.InitPlayerHPBar, nowPlayerInfo.hp);
//throw new NotImplementedException();
}
private void PlayPlayerEnterAnimation()
{
nowPlayerInfo.Run();
EventCenter.GetInstance().EventTrigger(EventDic.BGMoveAbleChange);
Tweener tweener = nowPlayerInfo.obj.transform.DOMove(PlayerStandPoint.position, 3f);
tweener.onComplete += () => { EventCenter.GetInstance().EventTrigger(EventDic.PlayerReachedStandPoint); };
//throw new NotImplementedException();
}
}
|
using Alabo.Domains.Entities;
using Alabo.Runtime.Config;
namespace Alabo.Domains.Services.Attach {
public interface IAttach<TEntity, in TKey> where TEntity : class, IAggregateRoot<TEntity, TKey> {
/// <summary>
/// 获取表名
/// </summary>
string GetTableName();
/// <summary>
/// 获取数据类型
/// </summary>
DatabaseType GetDatabaseType();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EasyDev.Presentation;
using SQMS.Services;
using EasyDev.BL;
using EasyDev.SQMS;
using System.Data;
using EasyDev.Util;
using YYControls;
using System.Web.UI.HtmlControls;
namespace SQMS.Application.Views.Common
{
public class sGridItemTemplate : ITemplate
{
private DataControlRowType templateType;
private string columnName;
private string idName;
private string roleid;
private RoleService roleservice;
private List<sGridItemCB> cblist;
public sGridItemTemplate(DataControlRowType type, string colname,string id, RoleService srv, string roleid,List<sGridItemCB> cblist)
{
this.templateType = type;
this.columnName = colname;
this.idName = id;
this.roleservice = srv;
this.roleid = roleid;
this.cblist = cblist;
}
public void InstantiateIn(Control container)
{
switch (templateType)
{
case DataControlRowType.Header:
Label lbl = new Label();
lbl.Text = columnName;
container.Controls.Add(lbl);
break;
case DataControlRowType.DataRow:
CheckBox check1 = new CheckBox();
check1.ID = idName;
check1.AutoPostBack = false;//false
check1.Attributes.Add("title", columnName);
check1.CheckedChanged += new EventHandler(check_CheckedChanged);
container.Controls.Add(check1);
break;
case DataControlRowType.Separator:
CheckBox check2 = new CheckBox();
check2.ID = idName;
check2.AutoPostBack = false;//false
container.Controls.Add(check2);
break;
case DataControlRowType.EmptyDataRow:
CheckBox check3 = new CheckBox();
check3.ID = idName;
check3.AutoPostBack = false;//false
check3.Enabled = false;
check3.CheckedChanged += new EventHandler(check_CheckedChanged);
container.Controls.Add(check3);
//Label lbl1 = new Label();
//lbl1.Text = "hresname";
//lbl1.Text = "";
//HiddenField hid = new HiddenField();
//hid.ID = "hresid";
//hid.Value = "";
//container.Controls.Add(lbl1);
//container.Controls.Add(hid);
break;
default:
break;
}
}
private void check_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = sender as CheckBox;
GridViewRow gvr = cb.Parent.Parent as GridViewRow;
string opid = cb.ID;
string resid = gvr.Cells[1].Text;
cblist.Add(new sGridItemCB() { resid = resid, opid = opid, chked = cb.Checked });
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
namespace RoadSimLib.UnitTest
{
[TestClass]
public class TileUnitTest
{
[TestMethod]
public void ShouldCheckConstructorParameters()
{
Card tile;
tile = new Card();
Assert.AreEqual(1, tile.Pattern);
tile = new Card(3);
Assert.AreEqual(3, tile.Pattern);
Assert.ThrowsException<ArgumentOutOfRangeException>(() => new Card(-1));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => new Card(16));
}
[TestMethod]
public void ShouldRotateUsingStaticMethod()
{
Assert.AreEqual(0, Card.Rotate(0));
Assert.AreEqual(2, Card.Rotate(1));
Assert.AreEqual(4, Card.Rotate(2));
Assert.AreEqual(8, Card.Rotate(4));
Assert.AreEqual(1, Card.Rotate(8));
Assert.AreEqual(6, Card.Rotate(3));
Assert.AreEqual(12, Card.Rotate(6));
Assert.AreEqual(9, Card.Rotate(12));
Assert.AreEqual(3, Card.Rotate(9));
Assert.AreEqual(14, Card.Rotate(7));
Assert.AreEqual(13, Card.Rotate(14));
Assert.AreEqual(11, Card.Rotate(13));
Assert.AreEqual(7, Card.Rotate(11));
Assert.AreEqual(15, Card.Rotate(15));
}
[TestMethod]
public void ShouldRotate()
{
Card tile;
tile = new Card();
tile.Pattern = 1;
Assert.AreEqual(1, tile.Pattern);
tile.Rotate();
Assert.AreEqual(2, tile.Pattern);
tile.Rotate();
Assert.AreEqual(4, tile.Pattern);
tile.Rotate();
Assert.AreEqual(8, tile.Pattern);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Anywhere2Go.DataAccess.Object
{
[DataContract]
public class AddLertRequest
{
[DataMember(Name = "account_id")]
public string AccountID { get; set; }
[DataMember(Name = "device_id")]
public string DeviceID { get; set; }
[DataMember(Name = "device_type")]
public string DeviceType { get; set; }
[DataMember(Name = "insurance_company_id")]
public string InsuranceCompanyID { get; set; }
[DataMember(Name = "latitude")]
public string Latitude { get; set; }
[DataMember(Name = "longitude")]
public string Longitude { get; set; }
[DataMember(Name = "message")]
public string Message { get; set; }
[DataMember(Name = "os_version")]
public string OSVersion { get; set; }
}
[DataContract]
public class AddLertResponse
{
[DataMember(Name = "lert_id")]
public string LertID { get; set; }
[DataMember(Name = "user_id")]
public string UserID { get; set; }
}
[DataContract]
public class MTIRegisterLertRequest
{
[DataMember(Name = "ilertuTel")]
public List<string> Tels { get; set; }
[DataMember(Name = "License_no")]
public List<string> LicenseNo { get; set; }
[DataMember(Name = "License_province_name")]
public List<string> LicenseProvince { get; set; }
[DataMember(Name = "language")]
public string Language { get; set; }
[DataMember(Name = "policies")]
public List<string> Policies { get; set; }
}
[DataContract]
public class MTIAddLertRequest
{
[DataMember(Name = "osVersion")]
public string OsVersion { get; set; }
[DataMember(Name = "remark")]
public string Remark { get; set; }
[DataMember(Name = "deviceType")]
public string DeviceType { get; set; }
[DataMember(Name = "registerrefId")]
public string RegisterId { get; set; }
[DataMember(Name = "longitude")]
public string Longitude { get; set; }
[DataMember(Name = "language")]
public string Language { get; set; }
[DataMember(Name = "latitude")]
public string Latitude { get; set; }
[DataMember(Name = "deviceId")]
public string DeviceId { get; set; }
}
}
|
namespace E_ticaret.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Kullanici")]
public partial class Kullanici
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Kullanici()
{
Adres = new HashSet<Adre>();
Favorilerims = new HashSet<Favorilerim>();
odemes = new HashSet<odeme>();
Sepets = new HashSet<Sepet>();
urunlers = new HashSet<urunler>();
}
[Key]
public int Kullanici_id { get; set; }
[StringLength(50)]
public string Kullanici_adi { get; set; }
[StringLength(50)]
public string kullanici_soyadi { get; set; }
[Column(TypeName = "date")]
public DateTime? kayit_tarih { get; set; }
[StringLength(10)]
public string parola { get; set; }
[Required]
[StringLength(50)]
public string Eposta { get; set; }
[StringLength(10)]
public string Rol { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Adre> Adres { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Favorilerim> Favorilerims { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<odeme> odemes { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Sepet> Sepets { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<urunler> urunlers { get; set; }
}
}
|
using FluentMigrator;
namespace Profiling2.Migrations.Migrations
{
[Migration(201409251158)]
public class AddPublicSummaryToPerson : Migration
{
public override void Down()
{
Delete.Column("PublicSummary").FromTable("PRF_Person");
Delete.Column("PublicSummaryDate").FromTable("PRF_Person");
Delete.Column("PublicSummary").FromTable("PRF_Person_AUD");
Delete.Column("PublicSummaryDate").FromTable("PRF_Person_AUD");
}
public override void Up()
{
Alter.Table("PRF_Person")
.AddColumn("PublicSummary").AsString(int.MaxValue).Nullable()
.AddColumn("PublicSummaryDate").AsDateTime().Nullable();
Alter.Table("PRF_Person_AUD")
.AddColumn("PublicSummary").AsString(int.MaxValue).Nullable()
.AddColumn("PublicSummaryDate").AsDateTime().Nullable();
}
}
}
|
namespace MusicStore.Models.DAL {
using MusicStore.Models.DataModels;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
public class DALGenre {
protected string ChaineConnexion = ConfigurationManager.ConnectionStrings["MusicStore"].ConnectionString;
protected const string GENRE_INSERT = @"INSERT INTO Genre(Nom) OUTPUT INSERTED.GenreId VALUES(@Nom);";
protected const string GENRE_DELETE = @"DELETE Genre WHERE GenreId=@GenreId";
protected const string GENRE_UPDATE = @"UPDATE Genre SET Nom = @Nom WHERE GenreId=@GenreId";
protected const string GENRE_SELECTALL = @"SELECT GenreId,Nom FROM Genre";
protected const string GENRE_FINDBYID = @"SELECT GenreId,Nom FROM Genre WHERE GenreId=@GenreId";
protected const string GENRE_FINDBYNAME = @"SELECT GenreId,Nom FROM Genre WHERE Nom=@NomGenre";
public void Add(Genre u)
{
using (SqlConnection connection = new SqlConnection(this.ChaineConnexion))
{
SqlCommand command = new SqlCommand(GENRE_INSERT, connection);
command.Parameters.AddWithValue("Nom", u.NomGenre);
connection.Open();
u.GenreId = Convert.ToInt32(command.ExecuteScalar());
}
}
public void Remove(Genre u) { this.Remove(u.GenreId); }
public void Remove(int GenreId)
{
using (SqlConnection connection = new SqlConnection(this.ChaineConnexion))
{
SqlCommand command = new SqlCommand(GENRE_DELETE, connection);
command.Parameters.AddWithValue("GenreId", GenreId);
connection.Open();
command.ExecuteNonQuery();
}
}
public void Update(Genre entity)
{
using (SqlConnection connection = new SqlConnection(this.ChaineConnexion))
{
SqlCommand command = new SqlCommand(GENRE_UPDATE, connection);
command.Parameters.AddWithValue("GenreId", entity.GenreId);
command.Parameters.AddWithValue("Nom", entity.NomGenre);
connection.Open();
command.ExecuteNonQuery();
}
}
public Genre Find(int GenreId)
{
using (SqlConnection connection = new SqlConnection(this.ChaineConnexion))
{
connection.Open();
SqlCommand command = new SqlCommand(GENRE_FINDBYID, connection);
command.Parameters.AddWithValue("GenreId", GenreId);
SqlDataReader dr = command.ExecuteReader();
Genre u = null;
if (dr.Read())
{
u = new Genre
{
GenreId = (int)dr["GenreId"],
NomGenre = dr["Nom"].ToString(),
};
}
dr.Close();
return u;
}
}
public Genre FindByName(string nomGenre)
{
using (SqlConnection connection = new SqlConnection(this.ChaineConnexion))
{
connection.Open();
SqlCommand command = new SqlCommand(GENRE_FINDBYNAME, connection);
command.Parameters.AddWithValue("Nom", nomGenre);
SqlDataReader dr = command.ExecuteReader();
Genre u = null;
if (dr.Read())
{
u = new Genre
{
GenreId = (int)dr["GenreId"],
NomGenre = dr["Nom"].ToString(),
};
}
dr.Close();
return u;
}
}
public List<Genre> List()
{
using (SqlConnection connection = new SqlConnection(this.ChaineConnexion))
{
connection.Open();
SqlCommand command = new SqlCommand(GENRE_SELECTALL, connection);
SqlDataReader dr = command.ExecuteReader();
List<Genre> lu = new List<Genre>();
while (dr.Read())
{
lu.Add(new Genre
{
GenreId = (int)dr["GenreId"],
NomGenre = dr["Nom"].ToString()
});
}
dr.Close();
return lu;
}
}
}
} |
using RulesEngine.Interfaces;
namespace RulesEngine.Conditions
{
public class GreaterThanCondition : ICondition
{
private readonly decimal _actual;
private readonly decimal _threshold;
public GreaterThanCondition(decimal threshold, decimal actual)
{
_threshold = threshold;
_actual = actual;
}
public bool IsSatisfied()
{
return _actual > _threshold;
}
}
}
|
using DChild.Gameplay.Combat;
using Sirenix.OdinInspector;
using UnityEngine;
namespace DChild.Gameplay.Objects.Characters.Enemies
{
public class ShadowMinionBrain : MinionAIBrain<ShadowMinion>, IAITargetingBrain
{
[SerializeField]
[MinValue(0f)]
private float m_alertRange;
private Vector3 m_chargeTo;
public override void Enable(bool value)
{
}
public override void ResetBrain()
{
m_target = null;
m_minion.EnterShadowForm();
m_chargeTo = Vector3.zero;
}
public override void SetTarget(IDamageable target)
{
if (m_target == null)
{
m_target = target;
}
}
private void Update()
{
if (m_minion.waitForBehaviourEnd)
return;
if (m_target != null)
{
if (Vector2.Distance(m_minion.position, m_target.position) > m_alertRange)
{
Debug.Log("Hide");
m_target = null;
m_minion.EnterShadowForm();
}
else if (m_minion.isCharging)
{
if (Vector2.Distance(m_minion.position, m_chargeTo) <= 0.5f)
{
m_minion.StopCharge();
}
}
else
{
Debug.Log("Do Whatever");
if (m_minion.inShadowForm)
{
m_minion.ExitShadowForm();
}
else
{
m_chargeTo = m_target.position;
m_chargeTo.y = transform.position.y;
m_minion.Charge(m_chargeTo);
}
}
}
}
}
} |
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int KthSmallest(TreeNode root, int k) {
var l = new List<int>();
Helper(root, l);
return l[k-1];
}
public void Helper(TreeNode root, List<int> l) {
if (root == null) {
return;
} else {
Helper(root.left, l);
l.Add(root.val);
Helper(root.right, l);
}
}
} |
using MyMovies.Domain.Enums;
using System;
using System.Collections.Generic;
namespace MyMovies.Domain.Entities
{
public class Person : Entity
{
public string Name { get; set; }
public DateTime Birthday { get; set; }
public Gender Gender { get; set; }
public virtual List<Job> Jobs { get; set; }
//[NotMapped]
public virtual List<Item> Photos { get; set; }
}
} |
using System;
using DevExpress.Xpo;
namespace ACHMS.Common.Entities
{
public class User : XPObject
{
public string UserName {
get { return GetPropertyValue<string>("UserName"); }
set { SetPropertyValue("UserName", value); }
}
public string Digest {
get { return GetPropertyValue<string>("Digest"); }
set { SetPropertyValue("Digest", value); }
}
public string Salt{
get { return GetPropertyValue<string>("Salt"); }
set { SetPropertyValue("Salt", value); }
}
#region Constructor
public User()
: base()
{
// This constructor is used when an object is loaded from a persistent storage.
// Do not place any code here.
}
public User(Session session)
: base(session)
{
// This constructor is used when an object is loaded from a persistent storage.
// Do not place any code here.
}
public override void AfterConstruction()
{
base.AfterConstruction();
// Place here your initialization code.
}
#endregion
}
} |
using Alabo.Data.People.Suppliers.Domain.Entities;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Repositories;
using MongoDB.Bson;
namespace Alabo.Data.People.Suppliers.Domain.Repositories
{
public class SupplierRepository : RepositoryMongo<Supplier, ObjectId>, ISupplierRepository
{
public SupplierRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
{
}
}
} |
/*
* Name: Anju Chawla
* Date: September 27, 2016
* Purpose: Create an application for the fitness center.
* Allow user to sign in and select promotions.
* Display the promotion details with appropriate images
*
*/
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 Comp1004_Week4_Tuesday
{
public partial class frmPromotions : Form
{
public frmPromotions()
{
InitializeComponent();
}
private void frmPromotions_Load(object sender, EventArgs e)
{
//default settings when the form loads
grpDepartment.Enabled = false;
rtfWelcome.Visible = false;
txtPromotion.Visible = false;
chkImageVisible.Visible = false;
picDepartment.Visible = false;
}
private void btnSignIn_Click(object sender, EventArgs e)
{
//allow the user to sign in; show welcome message
rtfWelcome.Visible = true;
rtfWelcome.Text = "Welcome " + txtName.Text
+ Environment.NewLine + "Member Id: " + mskMemberId.Text;
//hide the controls not needed
lblName.Visible = false;
lblMemberId.Visible = false;
txtName.Visible = false;
mskMemberId.Visible = false;
//show the controls that are required for input
grpDepartment.Enabled = true;
chkImageVisible.Visible = true;
txtPromotion.Visible = true;
//disable sign in
btnSignIn.Enabled = false;
}
private void btnPrint_Click(object sender, EventArgs e)
{
//print the form
printForm1.Print();
}
private void btnExit_Click(object sender, EventArgs e)
{
//close the form
this.Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
//reset the form to its start default state
Application.Restart();
}
private void radClothing_CheckedChanged(object sender, EventArgs e)
{
//show the corresponding promotion and picture for clothing
txtPromotion.Text = "30% off clearance items";
picDepartment.Image = Comp1004_Week4_Tuesday.Properties.Resources.clothing;
}
private void radEquipmentAccessories_CheckedChanged(object sender, EventArgs e)
{
//show the corresponding promotion and picture for equipment/accessories
txtPromotion.Text = "30% off all equipment";
picDepartment.Image = Properties.Resources.equipment;
}
private void radJuiceBar_CheckedChanged(object sender, EventArgs e)
{
//show the corresponding promotion and picture for juice bar
txtPromotion.Text = "Free serving of WheatBerry shake";
picDepartment.Image = Properties.Resources.juice;
}
private void radMembership_CheckedChanged(object sender, EventArgs e)
{
//show the corresponding promotion and picture for membership
txtPromotion.Text = "Free personal trainer for the first month";
picDepartment.Image = Properties.Resources.member;
}
private void radPersonalTraining_CheckedChanged(object sender, EventArgs e)
{
//show the corresponding promotion and picture for personal training
txtPromotion.Text = "3 free memberships with membership renewal";
picDepartment.Image = Properties.Resources.training;
}
private void chkImageVisible_CheckedChanged(object sender, EventArgs e)
{
//picture displayed if image visible is checked
/*
if (chkImageVisible.Checked) //==true
{
picDepartment.Visible = true;
}
else
{
picDepartment.Visible = false;
}
*/
picDepartment.Visible = chkImageVisible.Checked;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
using System.Runtime.InteropServices;
using System.IO;
using System;
using UnityEngine.Networking;
public class FileWriter : NetworkBehaviour {
public bool FileWriting = true;
public float FileWriteFreq = 1f;
public string SaveFileName;
DateTime saveTimeNow;
string headerToWrite;
string path1;
string path2;
string stateToWrite;
float writeTimer = 0.0f;
bool headerWritten = false;
string sessionName;
float PlayerFAread = 0f;
float PlayerRespRead = 0f;
float PlayerColorvalue = 0f;
float PlayerColorSynchronicity = 0f;
float PlayerAuraSize = 0f;
float PlayerBreathingSent = 0f;
float BreathingSynchroncity= 0f;
// Use this for initialization
void Start () {
if (!isLocalPlayer)
{
return;
}
if (PlayerPrefs.HasKey ("SaveFileNameStored")) {
//SaveFileName = PlayerPrefs.GetString ("SaveFileNameStored");
SaveFileName = PlayerPrefs.GetString("SaveFileNameStored") + "_data.txt";
Debug.Log ("FileName parameter loaded: "+ SaveFileName );
} else { SaveFileName = "Testfile.txt";
}
if (PlayerPrefs.HasKey ("Param_SessionID")) {
sessionName = PlayerPrefs.GetString ("Param_SessionID");
Debug.Log ("Session loaded:" + sessionName);
} else { sessionName = "TestSession";
}
}
void FixedUpdate () {
//File Writing happens here.
if (!isLocalPlayer)
{
return;
}
switch (sessionName) {
case "Session1": //no adaptation, solo.
PlayerFAread = GetComponent<PlayerManager>().PlayerFA;
PlayerColorvalue = 0f;
PlayerColorSynchronicity = 0f;
PlayerRespRead = GetComponent<PlayerManager> ().breatheNow;
PlayerAuraSize = 0f;
PlayerBreathingSent = 0f;
BreathingSynchroncity = 0f;
break;
case "Session2": //breathing, solo
PlayerFAread = GetComponent<PlayerManager>().PlayerFA;
PlayerColorvalue = 0f;
PlayerColorSynchronicity = 0f;
PlayerRespRead = GetComponent<PlayerManager> ().breatheNow;
PlayerAuraSize = GetComponent<PlayerManager> ().AuraBone.transform.localScale.x;
if (GetComponent<PlayerManager> ().breatheCooldown) {
PlayerBreathingSent = 1f;
} else {
PlayerBreathingSent = 0f;
} // is it ok to check if breathe Coold down is active? maybe. It lasts for 1s. Is there are chance to miss one?
BreathingSynchroncity = 0f;
break;
case "Session3": //eeg, solo.
PlayerFAread = GetComponent<PlayerManager> ().PlayerFA;
PlayerColorvalue = GetComponent<PlayerFAScript> ().PlayerFA_Display;
PlayerColorSynchronicity = 0f;
PlayerRespRead = GetComponent<PlayerManager> ().breatheNow;
PlayerAuraSize = 0f;
PlayerBreathingSent = 0f;
BreathingSynchroncity = 0f;
break;
case "Session4": //nothing adapts, dyad
PlayerFAread = GetComponent<PlayerManager>().PlayerFA;
PlayerColorvalue = 0f;
PlayerColorSynchronicity = 0f;
PlayerRespRead = GetComponent<PlayerManager> ().breatheNow;
PlayerAuraSize = 0f;
PlayerBreathingSent = 0f;
BreathingSynchroncity = 0f;
break;
case "Session5": // breathing, dyad - breathing synchronisity possible
PlayerFAread = GetComponent<PlayerManager>().PlayerFA;
PlayerColorvalue = 0f;
PlayerColorSynchronicity = 0f;
PlayerRespRead = GetComponent<PlayerManager> ().breatheNow;
PlayerAuraSize = GetComponent<PlayerManager> ().AuraBone.transform.localScale.x;
if (GetComponent<PlayerManager> ().breatheCooldown) {
PlayerBreathingSent = 1f;
} else {
PlayerBreathingSent = 0f;
}
if (GetComponent<BreathLayerer> ().SyncHappened) {
BreathingSynchroncity = 1f;
} else {
BreathingSynchroncity = 0f;
}
break;
case "Session6": //eeg dyad - bridge sides synchronisity possible
PlayerFAread = GetComponent<PlayerManager>().PlayerFA;
PlayerColorvalue = GetComponent<PlayerFAScript>().PlayerFA_Display;
PlayerColorSynchronicity =GetComponent<PlayerFAScript>().fasync; // effect happens when this is <0.1;
PlayerRespRead = GetComponent<PlayerManager> ().breatheNow;
PlayerAuraSize = 0f;
PlayerBreathingSent = 0f;
BreathingSynchroncity= 0f;
break;
case "Session7": // breathing & eeg solo, no synchronisity possible
PlayerFAread = GetComponent<PlayerManager>().PlayerFA;
PlayerColorvalue = GetComponent<PlayerFAScript>().PlayerFA_Display;
PlayerColorSynchronicity =GetComponent<PlayerFAScript>().fasync; // effect happens when this is <0.1;
PlayerRespRead = GetComponent<PlayerManager> ().breatheNow;
PlayerAuraSize = GetComponent<PlayerManager> ().AuraBone.transform.localScale.x;
if (GetComponent<PlayerManager> ().breatheCooldown) {
PlayerBreathingSent = 1f;
} else {
PlayerBreathingSent = 0f;
}
if (GetComponent<BreathLayerer> ().SyncHappened) {
BreathingSynchroncity = 1f;
} else {
BreathingSynchroncity = 0f;
}
break;
case "Session8": // breathing & eeg dyad - breathing and eeg synchronisity possible
PlayerFAread = GetComponent<PlayerManager>().PlayerFA;
PlayerColorvalue = GetComponent<PlayerFAScript>().PlayerFA_Display;
PlayerColorSynchronicity =GetComponent<PlayerFAScript>().fasync; // effect happens when this is <0.1;
PlayerRespRead = GetComponent<PlayerManager> ().breatheNow;
PlayerAuraSize = GetComponent<PlayerManager> ().AuraBone.transform.localScale.x;
if (GetComponent<PlayerManager> ().breatheCooldown) {
PlayerBreathingSent = 1f;
} else {
PlayerBreathingSent = 0f;
}
if (GetComponent<BreathLayerer> ().SyncHappened) {
BreathingSynchroncity = 1f;
} else {
BreathingSynchroncity = 0f;
}
break;
}
path1 = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Desktop) + "/DYNECOM_Data";
path2 = path1 + "/" + SaveFileName;
//only write the file once the start timer has ended.
// if (GameObject.Find("Session Manager").GetComponent<SessionManager>().StartTimerDone) {
writeTimer += Time.deltaTime; //data is written on a frequencey, default, once per second.
if (writeTimer > FileWriteFreq) {
if (headerWritten == false) {
//create folder if it doesn't exist
if (Directory.Exists (path1)) {
} else {
DirectoryInfo di = Directory.CreateDirectory (path1);
}
// write the header
saveTimeNow = System.DateTime.Now;
saveTimeNow.ToString ("yyyyMMddHHmmss");
headerToWrite = "Starting recording a new test: " + sessionName +" "+ saveTimeNow + Environment.NewLine +
"Format: DateTime, EegRead, User FA Color, Color Sync, Resp MovingAverage, User AuraSize, Resp. Bar Sent, Resp. Bar Sync" + Environment.NewLine; //+ " " + simulationToWrite ;
// Debug.Log (headerToWrite);
System.IO.File.AppendAllText (path2, headerToWrite);
headerWritten = true;
} else { //HERE we write actual data
var tmpPlayerFAread = PlayerFAread.ToString ();
var tmpPlayerColorvalue = PlayerColorvalue.ToString ();;
var tmpPlayerColorSynchronicity = PlayerColorSynchronicity.ToString ();
var tmpPlayerRespRead = PlayerRespRead.ToString ();
var tmpPlayerAuraSize = PlayerAuraSize.ToString ();
var tmpPlayerBreathingSent = PlayerBreathingSent.ToString ();
var tmpBreathingSynchroncity= BreathingSynchroncity.ToString ();
saveTimeNow = System.DateTime.Now;
saveTimeNow.ToString ("HHmmss");
//var heightTemp = AdaptationLevitationHeight.ToString ();
//var whiteTemp = AdaptationBubbleStrength.ToString ();
stateToWrite =
saveTimeNow + ","+
tmpPlayerFAread + ","+
tmpPlayerColorvalue + ","+
tmpPlayerColorSynchronicity + ","+
tmpPlayerRespRead + ","+
tmpPlayerAuraSize + ","+
tmpPlayerBreathingSent + ","+
tmpBreathingSynchroncity +
Environment.NewLine;
System.IO.File.AppendAllText (path2, stateToWrite);
}
writeTimer -= writeTimer;
}
}
//}
}
|
namespace Krafteq.ElsterModel.Common
{
using System;
public class CompanyInfo
{
public CompanyName CompanyName { get; }
public FullName PersonName { get; }
public Address Address { get; }
public POBox POBox { get; }
public ContactInfo ContactInfo { get; }
public CompanyInfo(
CompanyName companyName,
FullName personName,
Address address,
POBox poBox,
ContactInfo contactInfo)
{
this.CompanyName = companyName ?? throw new ArgumentNullException(nameof(companyName));
this.PersonName = personName ?? throw new ArgumentNullException(nameof(personName));
this.Address = address ?? throw new ArgumentNullException(nameof(address));
this.POBox = poBox ?? throw new ArgumentNullException(nameof(poBox));
this.ContactInfo = contactInfo ?? throw new ArgumentNullException(nameof(contactInfo));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MetodosBancoComercial.Conta.Poupanca
{
public class ContaPoupanca : Conta
{
private double TaxaRendimento;
public ContaPoupanca():base()
{
TaxaRendimento = 5;
}
public override void CalcularMes()
{
Saldo *= 1 + (TaxaRendimento / 100);
}
}
} |
using Alabo.Datas.Stores.Page.Mongo;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities.Core;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using System;
using System.Threading.Tasks;
namespace Alabo.Datas.Stores.Random.Mongo {
public abstract class RandomAsyncMongoStore<TEntity, TKey> : GetPageMongoStore<TEntity, TKey>,
IRandomAsyncStore<TEntity, TKey>
where TEntity : class, IKey<TKey>, IVersion, IEntity {
protected RandomAsyncMongoStore(IUnitOfWork unitOfWork) : base(unitOfWork) {
}
public async Task<TEntity> GetRandomAsync() {
return await Collection.AsQueryable().Where(x => true).OrderBy(a => Guid.NewGuid()).Take(1)
.FirstOrDefaultAsync();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.Marketplaces.Entityes;
using Welic.Dominio.Patterns.Service.Pattern;
namespace Welic.Dominio.Models.Marketplaces.Services
{
public interface IListingService : IService<Listing>
{
Dictionary<DateTime, int> GetItemsCount(DateTime datetime);
Dictionary<Category, int> GetCategoryCount();
}
}
|
/*
* Builded by Lars Ulrich Herrmann (c) 2013 with f.fN. Sense Applications in year August 2013
* The code can be used in other Applications if it makes sense
* If it makes sense the code can be used in this Application
* I hold the rights on all lines of code and if it makes sense you can contact me over the publish site
* Feel free to leave a comment
*
* Good Bye
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlTypes;
#region iAnywhere.Data.SQLAnywhere.v3.5
using iAnywhere;
using iAnywhere.Data;
using iAnywhere.Data.SQLAnywhere;
#endregion
namespace IxSApp
{
/// <summary>
///
/// </summary>
public struct AnlageItemInfo
{
/// <summary>
/// The name
/// </summary>
public string Name;
/// <summary>
/// The document
/// </summary>
public string Document;
/// <summary>
/// The description
/// </summary>
public string Description;
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MirrorName
{
[TestClass]
public class TestMirrorName
{
[TestMethod]
public void TestMethod1()
{
Assert.AreEqual("gnilraD olleH", MirrorThisString.StringMirror("Hello Darling"));
}
[TestMethod]
public void TestMethod2()
{
Assert.AreEqual(" !TAERG si efiL ", MirrorThisString.StringMirror(" Life is GREAT! "));
}
[TestMethod]
public void TestMethod3()
{
Assert.AreEqual("987654321", MirrorThisString.StringMirror("123456789"));
}
[TestMethod]
public void TestMethod4()
{
Assert.AreEqual("THE RODRIGUEZ FAMILY", MirrorThisString.StringMirror("YLIMAF ZEUGIRDOR EHT"));
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Luxand;
namespace facerecognition
{
public struct TFaceRecord
{
public byte [] Template; //Face Template;
public FSDK.TFacePosition FacePosition;
public FSDK.TPoint[] FacialFeatures; //Facial Features;
public string ImageFileName;
public FSDK.CImage image;
public FSDK.CImage faceImage;
}
public partial class Server : Form
{
public static float FaceDetectionThreshold = 3;
public static float FARValue = 100;
public static List<TFaceRecord> FaceList;
public static List<string> FaceName;
static ImageList imageList1;
private readonly Dictionary<int, TcpClient> tcpClients = new Dictionary<int, TcpClient>();
private List<Thread> threadClients = new List<Thread>();
private TcpListener listener;
//private TcpClient client;
private string ipAddress = string.Empty;
public Server()
{
InitializeComponent();
}
private void Server_Load(object sender, EventArgs e)
{
Text = Application.ProductName;
FaceList = new List<TFaceRecord>();
FaceName = new List<string>();
imageList1 = new ImageList();
threadClients = new List<Thread>();
Size size100x100 = new Size();
size100x100.Height = 100;
size100x100.Width = 100;
imageList1.ImageSize = size100x100;
imageList1.ColorDepth = ColorDepth.Depth24Bit;
listView1.OwnerDraw = false;
listView1.View = View.LargeIcon;
listView1.LargeImageList = imageList1;
add("Initializing FaceSDK...");
if (FSDK.FSDKE_OK != FSDK.ActivateLibrary("fVrFCzYC5wOtEVspKM/zfLWVcSIZA4RNqx74s+QngdvRiCC7z7MHlSf2w3+OUyAZkTFeD4kSpfVPcRVIqAKWUZzJG975b/P4HNNzpl11edXGIyGrTO/DImoZksDSRs6wktvgr8lnNCB5IukIPV5j/jBKlgL5aqiwSfyCR8UdC9s="))
{
MessageBox.Show("Please run the License Key Wizard (Start - Luxand - FaceSDK - License Key Wizard)", "Error activating FaceSDK", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
if (FSDK.InitializeLibrary() != FSDK.FSDKE_OK)
MessageBox.Show("Error initializing FaceSDK!", "Error");
add("FaceSDK Initialized");
string hostname = Dns.GetHostName();
IPHostEntry iphost = Dns.Resolve(hostname);
IPAddress[] addresses = iphost.AddressList;
ipAddress = addresses[addresses.Length - 1].ToString();
add("Starting Face Recognition server @ " + ipAddress);
try
{
listener = new TcpListener(IPAddress.Parse(ipAddress), 5005);
listener.Start();
Text += " @ " + ipAddress;
add("Waiting for client to connect...");
add("Don't forget to enroll a faces to the database.");
}
catch (Exception ex)
{
add(ex.Message);
}
Task.Run(() =>
{
try
{
TcpClient client = listener.AcceptTcpClient();
Thread thread = new Thread(handleClients);
tcpClients.Add(thread.ManagedThreadId, client);
threadClients.Add(thread);
thread.Start(thread.ManagedThreadId);
}
catch (Exception ex)
{
add(ex.Message);
}
});
}
private void handleClients(object threadId)
{
int clientId = (int)threadId;
TcpClient tcpClient = tcpClients[clientId];
string remoteEndPoint = tcpClient.Client.RemoteEndPoint.ToString();
string clientIp = remoteEndPoint.Substring(0, remoteEndPoint.IndexOf(":"));
string clientPort = remoteEndPoint.Substring(remoteEndPoint.IndexOf(":") + 1);
add("Client " + remoteEndPoint + " connected");
//Client client = new Client("Client " + clientIp + " @ " + clientPort);
//client = new Client("Client " + clientIp + " @ " + clientPort);
// this.BeginInvoke((Action)(() => client.Show()));
NetworkStream stream = tcpClient.GetStream();
string clientData = string.Empty;
Byte[] bytes = new Byte[256];
int i;
bool init = false;
try
{
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
if (!init)
{
clientData += Encoding.ASCII.GetString(bytes, 0, i);
}
if (clientData.Contains("<EOF>") && !init)
{
init = true;
string result = clientData.Substring(0, clientData.IndexOf("<EOF>"));
clientData = string.Empty;
byte[] imageBytes = Convert.FromBase64String(result);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Position = 0;
Image img = Image.FromStream(ms);
//if (client == null || client.IsDisposed)
//{
// client = new Client("Client " + clientIp + " @ " + clientPort);
// this.BeginInvoke((Action)(() => client.Show()));
//}
//this.BeginInvoke((Action)(() => client.label1.Visible = false));
//this.BeginInvoke((Action)(() => client.pictureBox1.Image = img));
if (FaceList.Count == 0)
{
add("Please enroll faces first");
init = false;
}
else
{
TFaceRecord fr = new TFaceRecord();
fr.FacePosition = new FSDK.TFacePosition();
fr.FacialFeatures = new FSDK.TPoint[FSDK.FSDK_FACIAL_FEATURE_COUNT];
fr.Template = new byte[FSDK.TemplateSize];
fr.image = new FSDK.CImage(img);
//img.Dispose();
fr.FacePosition = fr.image.DetectFace();
if (0 == fr.FacePosition.w)
{
add("No faces found. Try to lower the Minimal Face Quality parameter in the Options dialog box.");
init = false;
}
else
{
fr.faceImage = fr.image.CopyRect((int)(fr.FacePosition.xc - Math.Round(fr.FacePosition.w * 0.5)), (int)(fr.FacePosition.yc - Math.Round(fr.FacePosition.w * 0.5)), (int)(fr.FacePosition.xc + Math.Round(fr.FacePosition.w * 0.5)), (int)(fr.FacePosition.yc + Math.Round(fr.FacePosition.w * 0.5)));
bool eyesDetected = false;
try
{
fr.FacialFeatures = fr.image.DetectEyesInRegion(ref fr.FacePosition);
eyesDetected = true;
}
catch
{
add("Detecting eyes failed.");
init = false;
}
if (eyesDetected)
{
fr.Template = fr.image.GetFaceTemplateInRegion(ref fr.FacePosition); // get template with higher precision
float Threshold = 0.0f;
FSDK.GetMatchingThresholdAtFAR(FARValue / 100, ref Threshold);
int MatchedCount = 0;
int FaceCount = FaceList.Count;
float[] Similarities = new float[FaceCount];
for (int x = 0; x < FaceList.Count; x++)
{
float Similarity = 0.0f;
TFaceRecord CurrentFace = FaceList[x];
FSDK.MatchFaces(ref fr.Template, ref CurrentFace.Template, ref Similarity);
if (Similarity >= Threshold)
{
Similarities[MatchedCount] = Similarity;
++MatchedCount;
}
}
if (MatchedCount != 0)
{
float finalResult = Similarities.Max();
if (finalResult * 100 < 95.0)
{
SendBackToClient(tcpClient, "R=NONE;");
add("No morethan 95.0% matches found in database faces");
//init = false;
}
else
{
int index = 0;
for (int x = 0; x < MatchedCount; x++)
{
if (Similarities[x] == finalResult)
{
index = x;
}
}
SendBackToClient(tcpClient, "R=" + FaceName[index]);
//init = false;
}
}
else
{
SendBackToClient(tcpClient, "R=NONE;");
add("No matches found. You can try to increase the FAR parameter in the Options dialog box.");
//init = false;
}
}
else
{
add("No eyes detected in photos.");
init = false;
}
}
}
}
else
{
if (clientData.Contains(";"))
{
string result = clientData.Substring(0, clientData.IndexOf(";"));
if (result == "OK")
{
init = false;
}
}
}
}
tcpClients.Remove(clientId);
tcpClient.Client.Shutdown(SocketShutdown.Both);
tcpClient.Client.Close();
tcpClient.Client.Dispose();
int idx = 0;
for (int x = 0; x < threadClients.Count(); x++)
if (threadClients[x].ManagedThreadId == clientId) idx = x;
threadClients.RemoveAt(idx);
add("Client " + remoteEndPoint + " disconnected");
//if (client.Visible)
//{
// this.BeginInvoke((Action)(() => client.Close()));
//}
}
catch
{
add("Client " + remoteEndPoint + " error");
}
}
private void SendBackToClient(TcpClient client, string text)
{
try
{
byte[] buffer = Encoding.ASCII.GetBytes(text);
NetworkStream stream = client.GetStream();
stream.Write(buffer, 0, buffer.Length);
//stream.Flush();
}
catch (Exception ex)
{
add("Client " + client.Client.RemoteEndPoint.ToString() + " SEND ERROR: " + ex.Message);
}
}
private void add(string text)
{
if (InvokeRequired)
{
this.BeginInvoke((Action)(() => richTextBox1.AppendText(text + "\n")));
}
else
{
richTextBox1.AppendText(text + "\n");
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.listView1.SelectedIndices.Count > 0){
Image img = FaceList[listView1.SelectedIndices[0]].image.ToCLRImage();
//pictureBox1.Height = img.Height;
//pictureBox1.Width = img.Width;
pictureBox1.Image = img;
//img.Dispose();
//pictureBox1.Refresh();
//Graphics gr = pictureBox1.CreateGraphics();
//gr.DrawRectangle(Pens.LightGreen, FaceList[listView1.SelectedIndices[0]].FacePosition.xc - FaceList[listView1.SelectedIndices[0]].FacePosition.w / 2, FaceList[listView1.SelectedIndices[0]].FacePosition.yc - FaceList[listView1.SelectedIndices[0]].FacePosition.w/2, FaceList[listView1.SelectedIndices[0]].FacePosition.w, FaceList[listView1.SelectedIndices[0]].FacePosition.w);
//for (int i = 0; i < 2; ++i){
// FSDK.TPoint tp = FaceList[listView1.SelectedIndices[0]].FacialFeatures[i];
// gr.DrawEllipse(Pens.Blue, tp.x, tp.y, 3, 3);
//}
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
Options frmOptions = new Options();
frmOptions.Show();
}
private void enrollFacesToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "JPEG (*.jpg)|*.jpg|Windows bitmap (*.bmp)|*.bmp|All files|*.*";
dlg.Multiselect = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
try
{
//Assuming that faces are vertical (HandleArbitraryRotations = false) to speed up face detection
FSDK.SetFaceDetectionParameters(false, true, 384);
FSDK.SetFaceDetectionThreshold((int)FaceDetectionThreshold);
foreach (string fn in dlg.FileNames)
{
string name = Path.GetFileNameWithoutExtension(fn);
TFaceRecord fr = new TFaceRecord();
fr.ImageFileName = fn;
fr.FacePosition = new FSDK.TFacePosition();
fr.FacialFeatures = new FSDK.TPoint[2];
fr.Template = new byte[FSDK.TemplateSize];
fr.image = new FSDK.CImage(fn);
fr.FacePosition = fr.image.DetectFace();
if (0 == fr.FacePosition.w)
if (dlg.FileNames.Length <= 1)
MessageBox.Show("No faces found. Try to lower the Minimal Face Quality parameter in the Options dialog box.", "Enrollment error");
else
add(name + " face enroll failed.\nTry to lower the Minimal Face Quality parameter in the Options dialog box.");
else
{
fr.faceImage = fr.image.CopyRect((int)(fr.FacePosition.xc - Math.Round(fr.FacePosition.w * 0.5)), (int)(fr.FacePosition.yc - Math.Round(fr.FacePosition.w * 0.5)), (int)(fr.FacePosition.xc + Math.Round(fr.FacePosition.w * 0.5)), (int)(fr.FacePosition.yc + Math.Round(fr.FacePosition.w * 0.5)));
try
{
fr.FacialFeatures = fr.image.DetectEyesInRegion(ref fr.FacePosition);
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error detecting eyes.");
}
try
{
fr.Template = fr.image.GetFaceTemplateInRegion(ref fr.FacePosition); // get template with higher precision
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error retrieving face template.");
}
FaceList.Add(fr);
FaceName.Add(name);
imageList1.Images.Add(fr.faceImage.ToCLRImage());
listView1.Items.Add((imageList1.Images.Count - 1).ToString(), name,/**fn.Split('\\')[fn.Split('\\').Length - 1],*/ imageList1.Images.Count - 1);
add(name + " enrolled");
listView1.SelectedIndices.Clear();
listView1.SelectedIndices.Add(listView1.Items.Count - 1);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Exception");
}
}
}
private void clearDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
{
FaceList.Clear();
listView1.Items.Clear();
imageList1.Images.Clear();
pictureBox1.Width = 0;
pictureBox1.Height = 0;
GC.Collect();
}
private void matchFaceToolStripMenuItem_Click(object sender, EventArgs e)
{
if (FaceList.Count == 0)
MessageBox.Show("Please enroll faces first", "Error");
else {
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "JPEG (*.jpg)|*.jpg|Windows bitmap (*.bmp)|*.bmp|All files|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
try
{
string fn = dlg.FileNames[0];
TFaceRecord fr = new TFaceRecord();
fr.ImageFileName = fn;
fr.FacePosition = new FSDK.TFacePosition();
fr.FacialFeatures = new FSDK.TPoint[FSDK.FSDK_FACIAL_FEATURE_COUNT];
fr.Template = new byte[FSDK.TemplateSize];
try
{
fr.image = new FSDK.CImage(fn);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error loading file");
}
fr.FacePosition = fr.image.DetectFace();
if (0 == fr.FacePosition.w)
MessageBox.Show("No faces found. Try to lower the Minimal Face Quality parameter in the Options dialog box.", "Enrollment error");
else
{
fr.faceImage = fr.image.CopyRect((int)(fr.FacePosition.xc - Math.Round(fr.FacePosition.w * 0.5)), (int)(fr.FacePosition.yc - Math.Round(fr.FacePosition.w * 0.5)), (int)(fr.FacePosition.xc + Math.Round(fr.FacePosition.w * 0.5)), (int)(fr.FacePosition.yc + Math.Round(fr.FacePosition.w * 0.5)));
bool eyesDetected = false;
try
{
fr.FacialFeatures = fr.image.DetectEyesInRegion(ref fr.FacePosition);
eyesDetected = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error detecting eyes.");
}
if (eyesDetected)
{
fr.Template = fr.image.GetFaceTemplateInRegion(ref fr.FacePosition); // get template with higher precision
}
}
Results frmResults = new Results();
frmResults.Go(fr);
}
catch (Exception ex)
{
MessageBox.Show("Can't open image(s) with error: " + ex.Message.ToString(), "Error");
}
}
}
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
Environment.Exit(0);
}
}
}
|
using System.Threading.Tasks;
using IcecatSharp.Services;
using Xunit;
namespace IcecatSharp.Tests
{
public class FilesIndex_Tests_Fixture : IAsyncLifetime
{
public FilesIndexService Service => new FilesIndexService(Utils.IceCatConfig);
public async Task InitializeAsync()
{
}
public async Task DisposeAsync()
{
}
}
}
|
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using RangeDisplay.APIs;
using StardewModdingAPI;
using StardewValley;
using SObject = StardewValley.Object;
namespace RangeDisplay.RangeHandling.RangeCreators.Objects
{
internal class ScarecrowRangeCreator : IObjectRangeCreator, IModRegistryListener
{
private IPrismaticToolsAPI prismaticToolsAPI = null;
public RangeItem HandledRangeItem => RangeItem.Scarecrow;
public bool CanHandle(SObject obj)
{
return (obj.bigCraftable.Value && obj.name.ToLower().Contains("arecrow")) || (this.prismaticToolsAPI != null && this.prismaticToolsAPI.ArePrismaticSprinklersScarecrows && obj.ParentSheetIndex == this.prismaticToolsAPI.SprinklerIndex);
}
public IEnumerable<Vector2> GetRange(SObject obj, Vector2 position, GameLocation location)
{
for (int x = -9; x < 10; x++)
for (int y = -9; y < 10; y++)
{
Vector2 item = new Vector2(position.X + x, position.Y + y);
if (Vector2.Distance(item, position) < 9.0)
yield return item;
}
}
public void ModRegistryReady(IModRegistry registry)
{
if (registry.IsLoaded("stokastic.PrismaticTools"))
{
this.prismaticToolsAPI = registry.GetApi<IPrismaticToolsAPI>("stokastic.PrismaticTools");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IWorkFlow.DataBase;
namespace IWorkFlow.ORM
{
[Serializable]
[DataTableInfo("B_OA_Notice_AppointManSee", "id")]
public class B_OA_Notice_AppointManSee : QueryInfo
{
/// <summary>
/// 主键
/// </summary>
[DataField("id", "B_OA_Notice_AppointManSee", false)]
public int id
{
get { return _id; }
set { _id = value; }
}
private int _id;
/// <summary>
/// 用户id
/// </summary>
[DataField("userid", "B_OA_Notice_AppointManSee")]
public string userid
{
get { return _userid; }
set { _userid = value; }
}
private string _userid;
/// <summary>
/// 文章id
/// </summary>
[DataField("noticeid", "B_OA_Notice_AppointManSee")]
public string noticeid
{
get { return _noticeid; }
set { _noticeid = value; }
}
private string _noticeid;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace Lab9.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger _log;
public IndexModel(ILogger<IndexModel>log){
_log = log;
}
public void OnGet()
{
object b= null;
if (b== null)_log.LogWarning("Object is Null!");
else b.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace _06._List_Manipulation_Basics
{
class Program
{
static void Main(string[] args)
{
List<int> numbers = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToList();
string command = Console.ReadLine();
while (command != "end")
{
string[] commandSeparated = command.Split();
if (commandSeparated[0] == "Add")
{
numbers.Add(int.Parse(commandSeparated[1]));
}
else if (commandSeparated[0] == "Remove")
{
numbers.Remove(int.Parse(commandSeparated[1]));
}
else if (commandSeparated[0] == "RemoveAt")
{
numbers.RemoveAt(int.Parse(commandSeparated[1]));
}
else if (commandSeparated[0] == "Insert")
{
numbers.Insert(int.Parse(commandSeparated[2]), int.Parse(commandSeparated[1]));
}
command = Console.ReadLine();
}
Console.WriteLine(String.Join(" ", numbers));
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
public class Stuiterbaar : MonoBehaviour
{
// base components
[HideInInspector] public Transform myTransform;
[HideInInspector] public GameObject myGameObject;
// graphics
[Header("graphics")]
public Transform graphicsTransform;
public Material matFlicker;
public MeshRenderer[] graphicsMeshRenderers;
List<Material[]> meshMaterials;
List<Material[]> meshFlickerMaterials;
// owner
public ProjectileScript.OwnerType myOwnerType;
// flicker
int flickerIndex, flickerRateMin, flickerRateMax, flickerRate, flickerCounter, flickerWaitDur, flickerWaitCounter, flickerWaitIndex, flickerWaitCount, flickerWaitCountMax;
// scale
Vector3 scaleOriginal, scaleTarget, scaleCur, scaleAdd;
// layerMasks
[Header("layerMasks")]
public LayerMask collideLayerMask;
// settings
[Header("settings")]
public float sideForceFactor;
public float upForceFactor;
public float gravityFactor;
public float radius;
public Collectible myCollectible;
public bool preventRandomForceOnStart;
public float gravityMultiplier;
public float bounceMultiplier;
// damage
public bool dealDamage;
public float damageDealRadius;
public NpcCore npcCoreBy;
// force
Vector3 posCur;
[HideInInspector] public Vector3 forceCur;
float grav;
// bounce
int canBounceDur, canBounceCounter;
// auto clear?
public bool autoClear;
[HideInInspector] public int autoClearDur;
int autoClearCounter;
// audio
public enum AudioType { Coin, Tear, Key, Donut, Stone, Metal, Bone };
[Header("audio")]
public AudioType myAudioType;
public float pitchMin;
public float pitchMax;
public float volumeMin;
public float volumeMax;
void Start()
{
myTransform = transform;
myGameObject = gameObject;
canBounceDur = 10;
canBounceCounter = canBounceDur;
posCur = myTransform.position;
// meshes
meshMaterials = new List<Material[]>();
meshFlickerMaterials = new List<Material[]>();
for ( int i = 0; i < graphicsMeshRenderers.Length; i ++ )
{
Material[] curMat = graphicsMeshRenderers[i].materials;
meshMaterials.Add(curMat);
Material[] flickerMat = new Material[curMat.Length];
for ( int ii = 0; ii < flickerMat.Length; ii ++ )
{
flickerMat[ii] = matFlicker;
}
meshFlickerMaterials.Add(flickerMat);
}
// force on start
if (!preventRandomForceOnStart)
{
float forceSideOffMax = (.1f * sideForceFactor);
float xDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f));
float zDir = Mathf.Sign(TommieRandom.instance.RandomRange(-1f, 1f));
float xAdd = TommieRandom.instance.RandomRange(forceSideOffMax * .25f, forceSideOffMax);
float zAdd = TommieRandom.instance.RandomRange(forceSideOffMax * .25f, forceSideOffMax);
forceCur.x = (xAdd * xDir);
forceCur.z = (zAdd * zDir);
}
// flicker
flickerIndex = 0;
flickerRateMin = 60;
flickerRateMax = 90;
flickerRate = Mathf.RoundToInt(TommieRandom.instance.RandomRange(flickerRateMin, flickerRateMax));
flickerCounter = 0;
if ( dealDamage )
{
flickerCounter = flickerRate;
float flickerFac = .125f;
flickerRateMin = Mathf.RoundToInt(flickerRateMin * flickerFac);
flickerRateMax = Mathf.RoundToInt(flickerRateMax * flickerFac);
}
flickerWaitCountMax = 2;
flickerWaitCount = 0;
flickerWaitIndex = 0;
flickerWaitDur = 4;
flickerWaitCounter = 0;
// scale
scaleOriginal = graphicsTransform.localScale;
scaleTarget = scaleOriginal;
scaleCur = scaleTarget;
// random rotation
SetRandomRotation();
}
void Update ()
{
if (!SetupManager.instance.inFreeze)
{
float lDst = (radius * 1.5f);
Vector3 l0 = myTransform.position;
l0.y += lDst;
Vector3 l1 = myTransform.position;
l1.y -= lDst;
if ( Physics.Linecast(l0,l1,SetupManager.instance.lavaOnlyLayerMask) )
{
if ( myCollectible != null && myCollectible.myType == Collectible.Type.Key && !GameManager.instance.playerHasKey )
{
GameManager.instance.PlayerFoundKey();
}
PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab,myTransform.position,Quaternion.identity,1.5f);
AudioManager.instance.PlaySoundAtPosition(myTransform.position, BasicFunctions.PickRandomAudioClipFromArray(AudioManager.instance.fireStartClips), .9f, 1.2f, .2f, .225f);
Clear();
}
// auto clear?
if ( autoClear )
{
if ( autoClearCounter < autoClearDur )
{
autoClearCounter++;
}
else
{
PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab,myTransform.position,Quaternion.identity,1f);
Clear();
}
}
// damage?
if ( dealDamage )
{
CheckIfNeedToDealDamage();
}
// stuiter?
bool cancelStuiterbaar = false;
if ( myCollectible != null && myCollectible.collected )
{
cancelStuiterbaar = true;
}
if (!cancelStuiterbaar)
{
if (!dealDamage)
{
forceCur = Vector3.Lerp(forceCur, Vector3.zero, 1.25f * Time.deltaTime);
}
else
{
forceCur.y = Mathf.Lerp(forceCur.y,0f,1.25f * Time.deltaTime);
}
posCur += forceCur;
myTransform.position = posCur;
if (canBounceCounter < canBounceDur)
{
canBounceCounter++;
}
else
{
grav += (((.125f * gravityFactor) * gravityMultiplier) * Time.deltaTime);
posCur.y -= grav;
// check down
float cDst = radius;
Vector3 c0 = myTransform.position;
c0.y += cDst;
Vector3 c1 = myTransform.position;
c1.y -= cDst;
if (Physics.Linecast(c0, c1, collideLayerMask))
{
grav = 0f;
float bounceForceMax = .05f;
forceCur.y += (TommieRandom.instance.RandomRange(bounceForceMax * .625f, bounceForceMax) * upForceFactor) * bounceMultiplier;
canBounceCounter = 0;
// scale
scaleCur = scaleOriginal;
scaleCur.x *= TommieRandom.instance.RandomRange(1.25f, 1.5f);
scaleCur.y *= TommieRandom.instance.RandomRange(.5f, .75f);
scaleCur.z *= TommieRandom.instance.RandomRange(1.25f, 1.5f);
// random rotation
SetRandomRotation();
// audio
PlayImpactAudio();
}
}
// check in direction
float fDst = radius;
Vector3 p0 = myTransform.position;
Vector3 p1 = p0;
Vector3 fCheck = forceCur;
fCheck.y = 0f;
Vector3 fRaw = fCheck;
fCheck.Normalize();
p0 += fCheck * -fDst;
p1 += fCheck * fDst;
RaycastHit fHit;
if (Physics.Linecast(p0, p1, out fHit, collideLayerMask))
{
// physics
float m0 = fRaw.magnitude;
Vector3 r0 = forceCur.normalized;
Vector3 r1 = -fHit.normal.normalized;
r1.y = r0.y;
Vector3 r2 = Vector3.Reflect(r0, r1).normalized;
forceCur.x = r2.x * m0;
forceCur.z = r2.z * m0;
// particles
PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab, fHit.point, Quaternion.identity, .75f);
// audio
PlayImpactAudio();
/*
// log
Debug.DrawLine(fHit.point, fHit.point + r0, Color.magenta, 5f);
Debug.DrawLine(fHit.point, fHit.point + r1, Color.cyan, 5f);
Debug.DrawLine(fHit.point, fHit.point + r2, Color.green, 5f);
*/
}
// flicker
if (flickerIndex == 0)
{
if (flickerCounter < flickerRate)
{
flickerCounter++;
}
else
{
flickerRate = Mathf.RoundToInt(TommieRandom.instance.RandomRange(flickerRateMin, flickerRateMax));
flickerCounter = 0;
flickerIndex = 1;
flickerWaitCounter = 0;
flickerWaitIndex = 0;
flickerWaitCount = 0;
SetMaterials(false);
//graphicsMeshRenderer.materials = matOriginal;
}
}
else
{
if (flickerWaitCount < flickerWaitCountMax)
{
if (flickerWaitCounter < flickerWaitDur)
{
flickerWaitCounter++;
}
else
{
flickerWaitCount++;
flickerWaitIndex = (flickerWaitIndex == 0) ? 1 : 0;
flickerWaitCounter = 0;
SetMaterials(flickerWaitIndex != 0);
//graphicsMeshRenderer.materials = (flickerWaitIndex == 0) ? matOriginal : matFlicker;
}
}
else
{
flickerIndex = 0;
flickerCounter = 0;
SetMaterials(false);
//graphicsMeshRenderer.materials = matOriginal;
}
}
// scaling
scaleTarget = scaleOriginal;
scaleAdd = BasicFunctions.SpringVector(scaleAdd, scaleCur, scaleTarget, .01f, .25f, .5f, .925f);
scaleCur += scaleAdd;
graphicsTransform.localScale = scaleCur;
}
}
}
void CheckIfNeedToDealDamage ()
{
// collision?
Collider[] hitColliders = Physics.OverlapSphere(myTransform.position, radius * damageDealRadius);
if (hitColliders != null && hitColliders.Length > 0)
{
for (int i = 0; i < hitColliders.Length; i++)
{
GameObject hitO = hitColliders[i].gameObject;
if (hitO != null && ((hitO.layer != 11 && hitO.layer != 9 && hitO.layer != 13 && hitO.layer != 14 && hitO.layer != 15) || (myOwnerType == ProjectileScript.OwnerType.Player && hitO.layer == 10) || (myOwnerType == ProjectileScript.OwnerType.Npc && hitO.layer == 8)))
{
bool preventHit = false;
if (myOwnerType == ProjectileScript.OwnerType.Npc && hitO.layer == 10)
{
preventHit = true;
}
if (myOwnerType == ProjectileScript.OwnerType.Player && hitO.layer == 8)
{
preventHit = true;
}
if (myOwnerType == ProjectileScript.OwnerType.None)
{
preventHit = false;
}
if (!preventHit)
{
Vector3 p0 = myTransform.position;
Vector3 p1 = myTransform.position;
p1.y -= (radius + .05f);
// create damage deal object
DamageDeal.Target damageTargetType = (myOwnerType == ProjectileScript.OwnerType.Player) ? DamageDeal.Target.AI : DamageDeal.Target.Player;
if (myOwnerType == ProjectileScript.OwnerType.None)
{
damageTargetType = DamageDeal.Target.All;
}
Npc.AttackData.DamageType damageType = Npc.AttackData.DamageType.Magic;
PrefabManager.instance.SpawnDamageDeal(p0, damageDealRadius, 1, damageType, 10, HandManager.instance.myTransform, .325f, true, damageTargetType, npcCoreBy, false,false);
// create magic impact effect
PrefabManager.instance.SpawnPrefab(PrefabManager.instance.magicImpactParticlesPrefab[0], p0, Quaternion.identity, 1f);
// ripple effect
Vector3 ppp0 = myTransform.position;
Vector3 ppp1 = GameManager.instance.playerFirstPersonDrifter.myTransform.position;
float ddd0 = Vector3.Distance(ppp0, ppp1);
if (ddd0 <= 4 || myOwnerType == ProjectileScript.OwnerType.Player)
{
Vector2 ripplePos = Camera.main.WorldToScreenPoint(myTransform.position);
SetupManager.instance.SetRippleEffect(ripplePos, 17.5f);
}
// clear
Clear();
}
}
}
}
}
void SetMaterials ( bool _flicker )
{
for ( int i = 0; i < graphicsMeshRenderers.Length; i ++ )
{
graphicsMeshRenderers[i].materials = (_flicker) ? meshFlickerMaterials[i] : meshMaterials[i];
}
}
void SetRandomRotation ()
{
graphicsTransform.localRotation = Quaternion.Euler(TommieRandom.instance.RandomRange(0f, 360f), TommieRandom.instance.RandomRange(0f, 360f), TommieRandom.instance.RandomRange(0f, 360f));
}
public void PlayImpactAudio ()
{
AudioClip[] clipsUse = null;
switch (myAudioType)
{
case AudioType.Coin: clipsUse = AudioManager.instance.coinImpactClips; break;
case AudioType.Tear: clipsUse = AudioManager.instance.tearImpactClips; break;
case AudioType.Key: clipsUse = AudioManager.instance.coinImpactClips; break;
case AudioType.Donut: clipsUse = AudioManager.instance.donutImpactClips; break;
case AudioType.Stone: clipsUse = AudioManager.instance.stoneImpactClips; break;
case AudioType.Metal: clipsUse = AudioManager.instance.metalImpactClips; break;
case AudioType.Bone: clipsUse = AudioManager.instance.boneImpactClips; break;
}
AudioManager.instance.PlaySoundAtPosition(myTransform.position,BasicFunctions.PickRandomAudioClipFromArray(clipsUse), pitchMin, pitchMax, volumeMin, volumeMax);
}
public void SetOwnerType ( ProjectileScript.OwnerType _to )
{
myOwnerType = _to;
}
public void Clear ()
{
if (myGameObject != null)
{
Destroy(myGameObject);
}
}
}
|
using University.Data;
using University.Data.CustomEntities;
using University.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace University.Repository
{
public class ProductRepository : IProductRepository
{
//public IEnumerable<Product> GetUserVideosList()
//{
// using (var context = new UniversityEntities())
// {
// int AssocitedCustID = Convert.ToInt32(HttpContext.Current.Session["AdminLoginID"]);
// var res = (from p in context.Product.Where(y => y.IsDeleted != true && y.AssocitedCustID == AssocitedCustID)
// join s in context.SubCategoryMaster.Where(y => y.IsDeleted != true)
// on p.SubCategoryId equals s.Id
// join c in context.CategoryMaster.Where(y => y.IsDeleted != true)
// on s.CategoryId equals c.Id
// select new
// {
// p.Id,
// p.Title,
// subcatid = c.Id,
// c.Name,
// VideoRateSum = p.ProductVideos.Sum(x => x.VideoRate)
// }
// ).ToList();
// List<Product> productvideo = new List<Product>();
// foreach (var prodvideo in res)
// {
// productvideo.Add(new Product
// {
// Id = prodvideo.Id,
// Title = prodvideo.Title,
// //subcategoryname = prodvideo.Name,
// //catid = prodvideo.subcatid,
// //VideoRate = prodvideo.VideoRateSum
// });
// }
// return productvideo;
// }
//}
public IEnumerable<ProductVideos> GetUserVideosList()
{
using (var context = new UniversityEntities())
{
// int UserID = Convert.ToInt32(HttpContext.Current.Session["UserLoginID"]);
int AssocitedCustID = Convert.ToInt32(HttpContext.Current.Session["AdminLoginID"]);
//var res = (from l in context.Login_tbl.Where(y => y.IsDeleted != true && y.ID == AssocitedCustID)
// join cm in context.CategoryUserMapping.Where(y => y.IsDeleted != true && y.AdminID == AssocitedCustID)
// on l.ID equals cm.AdminID
// join c in context.SubCategoryMaster.Where(y => y.IsDeleted != true)
// on cm.CategoryID equals c.Id
// join p in context.Product.Where(y => y.IsDeleted != true)
// on c.Id equals p.SubCategoryId
// join pv in context.ProductVideos.Where(y => y.IsDeleted != true)
// on p.Id equals pv.ProductId
// orderby pv.CreatedDate
var res = (from p in context.Product.Where(y => y.IsDeleted != true && y.AssocitedCustID == AssocitedCustID)
join s in context.SubCategoryMaster.Where(y => y.IsDeleted != true)
on p.SubCategoryId equals s.Id
join c in context.CategoryMaster.Where(y => y.IsDeleted != true)
on s.CategoryId equals c.Id
//group p by p.Id into g
select new
{
p.Id,
p.Title,
subcatid = c.Id,
s.Name,
VideoRateSum = p.ProductVideos.Where(x=>x.IsDeleted == false).Sum(x => x.VideoRate)
}
).ToList();
List<ProductVideos> productvideo = new List<ProductVideos>();
foreach (var prodvideo in res)
{
productvideo.Add(new ProductVideos
{
Id = prodvideo.Id,
Title = prodvideo.Title,
subcategoryname = prodvideo.Name,
catid = prodvideo.subcatid,
VideoRate = prodvideo.VideoRateSum
});
}
return productvideo;
}
}
public IEnumerable<ProductEntity> GetProductList()
{
using (var context = new UniversityEntities())
{
int AdminID = Convert.ToInt32(HttpContext.Current.Session["AdminLoginID"]);
if (AdminID != 0)
{
var res = (from p in context.Product.Where(y => y.IsDeleted != true && y.AssocitedCustID == AdminID)
join s in context.SubCategoryMaster.Where(y => y.IsDeleted != true)
on p.SubCategoryId equals s.Id
join c in context.CategoryMaster.Where(y => y.IsDeleted != true)
on s.CategoryId equals c.Id
select new ProductEntity()
{
//AssocitedID = p.AssocitedID,
Id = p.Id,
//CategoryId = c.Id,
CreatedBy = p.CreatedBy,
CreatedDate = p.CreatedDate,
DeletedBy = p.DeletedBy,
DeletedDate = p.DeletedDate,
Description = p.Description,
ImageURL = p.ImageURL,
IsDeleted = p.IsDeleted,
SubCategoryId = p.SubCategoryId,
Title = p.Title,
UpdatedBy = p.UpdatedBy,
UpdatedDate = p.UpdatedDate,
CategoryMaster = c,
SubCategoryMaster = s,
// ProductVideos = context.ProductVideos.Where(x => x.IsDeleted == false && x.AssocitedCustID== AdminID).ToList()
//VideoRateSum = p.ProductVideos.Sum(x => x.VideoRate)
}).OrderByDescending(y => y.CreatedDate).ToList();
return res;
}
else
{
int UserID = Convert.ToInt32(HttpContext.Current.Session["UserLoginID"]);
var res = (from p in context.Product.Where(y => y.IsDeleted != true )
join s in context.SubCategoryMaster.Where(y => y.IsDeleted != true)
on p.SubCategoryId equals s.Id
join c in context.CategoryMaster.Where(y => y.IsDeleted != true)
on s.CategoryId equals c.Id
select new ProductEntity()
{
//AssocitedID = p.AssocitedID,
Id = p.Id,
//CategoryId = c.Id,
CreatedBy = p.CreatedBy,
CreatedDate = p.CreatedDate,
DeletedBy = p.DeletedBy,
DeletedDate = p.DeletedDate,
Description = p.Description,
ImageURL = p.ImageURL,
IsDeleted = p.IsDeleted,
SubCategoryId = p.SubCategoryId,
Title = p.Title,
UpdatedBy = p.UpdatedBy,
UpdatedDate = p.UpdatedDate,
CategoryMaster = c,
SubCategoryMaster = s
}).OrderByDescending(y => y.CreatedDate).ToList();
return res;
}
}
}
public ProductEntity GetProduct(Decimal Id)
{
using (var context = new UniversityEntities())
{
int AssocitedCustID = Convert.ToInt32(HttpContext.Current.Session["AdminLoginID"]);
//int UserID = Convert.ToInt32(HttpContext.Current.Session["UserLoginID"]);
var res = (from p in context.Product.Where(y => y.IsDeleted != true)
join s in context.SubCategoryMaster.Where(y => y.IsDeleted != true)
on p.SubCategoryId equals s.Id
join c in context.CategoryMaster.Where(y => y.IsDeleted != true)
on s.CategoryId equals c.Id
join g in context.ProductUserGuide.Where(y => y.IsDeleted != true)
on p.Id equals g.ProductId into temp
from guide in temp.DefaultIfEmpty()
//join viddeo in context.ProductVideos.Where(y=>y.IsDeleted != true)
//on p.Id equals viddeo.ProductId
join spec in context.ProductSpec.Where(y => y.IsDeleted != true)
on p.Id equals spec.ProductId into tempS
from speci in tempS.DefaultIfEmpty()
where p.Id == Id
select new ProductEntity()
{
Id = p.Id,
AssocitedCustID = AssocitedCustID,
//CategoryId = c.Id,
CreatedBy = p.CreatedBy,
CreatedDate = p.CreatedDate,
DeletedBy = p.DeletedBy,
DeletedDate = p.DeletedDate,
Description = p.Description,
ImageURL = p.ImageURL,
ImageALT = p.ImageALT,
IsDeleted = p.IsDeleted,
SubCategoryId = p.SubCategoryId,
Title = p.Title,
UpdatedBy = p.UpdatedBy,
UpdatedDate = p.UpdatedDate,
CategoryMaster = c,
SubCategoryMaster = s,
ProductUserGuide = guide,
CoursePrviewVideos = p.CoursePreviewVideos.Where(y => y.IsDeleted != true).ToList(),
ProductVideos = p.ProductVideos.Where(y => y.IsDeleted != true).ToList(),
//ProductVideosTranIDs = p.GetCardTransactionDeatilsMappings.Where(y => y.IsDeleted != true).ToList(),
ProductSpec = speci,
ProductFAQs = p.ProductFAQs.Where(y => y.IsDeleted != true).ToList(),
ProductDocuments = p.ProductDocuments.Where(y => y.IsDeleted != true).ToList(),
//TransactionId=v.TransactionID
}).ToList();
var productVideosPaid = (from p in context.Product.Where(y => y.IsDeleted != true)
join s in context.SubCategoryMaster.Where(y => y.IsDeleted != true)
on p.SubCategoryId equals s.Id
join ctd in context.CardTransactionDeatilsMapping.Where(c => c.IsDeleted == false)
on p.Id equals ctd.ProductID
join v in context.ProductVideos.Where(c => c.IsDeleted == false)
on new
{
ProductID = (decimal)ctd.ProductID,
VideoID = (decimal)ctd.VideoID
}
equals new
{
ProductID = v.ProductId,
VideoID = v.Id
}
select new
{
ID = v.Id,
ProductID = p.Id,
Videourl = v.VideoURL,
Tiltle = v.Title,
Description = v.Decription,
TransactionId = ctd.TransactionID,
VideoRate = v.VideoRate ?? 0,
//Ispaid=v.IsPaid,
//ispaidvideo = true,
}).ToList()
.Select(x => new ProductVideos()
{
Id = x.ID,
ProductId = x.ProductID,
VideoURL = x.Videourl,
Title = x.Tiltle,
Decription = x.Description,
TransactionID = x.TransactionId,
VideoRate = x.VideoRate,
// IsPaid=x.Ispaid
//ispaidvideo = x.ispaidvideo
}).ToList();
var productVideossunpaid = (from p in context.Product.Where(y => y.IsDeleted != true)
join s in context.SubCategoryMaster.Where(y => y.IsDeleted != true)
on p.SubCategoryId equals s.Id
//join ctd in context.CardTransactionDeatilsMapping.Where(c => c.IsDeleted == false)
//on p.Id equals ctd.ProductID
join v in context.ProductVideos.Where(c => c.IsDeleted != true)
on p.Id equals v.ProductId // into joinedT
// from v in joinedT.DefaultIfEmpty()
// where ctd.VideoID != v.Id
select new
{
ID = v.Id,
ProductID = p.Id,
Videourl = v.VideoURL,
Tiltle = v.Title,
Description = v.Decription,
TransactionId = "",
VideoRate = v.VideoRate ?? 0,
//videoRatesumsum=v.VideoRateSum+v.VideoRate,
}).ToList()
.Select(x => new ProductVideos()
{
Id = x.ID,
ProductId = x.ProductID,
VideoURL = x.Videourl,
Title = x.Tiltle,
Decription = x.Description,
TransactionID = x.TransactionId,
VideoRate = x.VideoRate,
// VideoRateSum=x.videoRatesumsum ??0,
}).ToList();
var finalvideo = productVideossunpaid.Where(x => productVideosPaid.Select(d => d.Id).Contains(x.Id)).ToList();
var asd = productVideossunpaid.Except(finalvideo);
var finalproductvideo = productVideosPaid.Union(asd).ToList();
foreach (var k in res)
{
k.ProductVideos = finalproductvideo.Where(x => x.ProductId == Id).ToList();
}
return res.FirstOrDefault();
}
}
//public bool AddOrUpdateProduct(ProductEntity model)
//{
// using (var context = new IPSU_devEntities())
// {
// var product = context.Products.FirstOrDefault(y => y.Id == model.Id && y.IsDeleted != true);
// if (product != null)
// {
// if (!string.IsNullOrWhiteSpace(model.ImageURL))
// {
// product.ImageURL = model.ImageURL;
// }
// product.Title = model.Title;
// product.SubCategoryId = model.SubCategoryId;
// product.UpdatedDate = DateTime.UtcNow;
// var userGuide = context.ProductUserGuides.FirstOrDefault(y => y.ProductId == model.Id && y.IsDeleted != true);
// if (model.ProductUserGuide != null)
// {
// if (userGuide != null)
// {
// if (!string.IsNullOrWhiteSpace(model.ProductUserGuide.Title))
// userGuide.Title = model.ProductUserGuide.Title;
// if (!string.IsNullOrWhiteSpace(model.ProductUserGuide.Description))
// userGuide.Description = model.ProductUserGuide.Description;
// if (!string.IsNullOrWhiteSpace(model.ProductUserGuide.ImageURL))
// userGuide.ImageURL = model.ProductUserGuide.ImageURL;
// if (!string.IsNullOrWhiteSpace(model.ProductUserGuide.ImageURL) || !string.IsNullOrWhiteSpace(model.ProductUserGuide.Title))
// userGuide.UpdatedDate = DateTime.UtcNow;
// }
// else
// {
// model.ProductUserGuide.Id = Guid.NewGuid();
// product.ProductUserGuides.Add(model.ProductUserGuide);
// }
// }
// var video = context.ProductVideos.FirstOrDefault(y => y.ProductId == model.Id && y.IsDeleted != true);
// if (model.ProductVideos != null)
// {
// if (video != null)
// {
// if (!string.IsNullOrWhiteSpace(model.ProductVideos.Title))
// video.Title = model.ProductVideos.Title;
// if (!string.IsNullOrWhiteSpace(model.ProductVideos.Decription))
// video.Title = model.ProductVideos.Decription;
// if (!string.IsNullOrWhiteSpace(model.ProductVideos.VideoURL))
// video.VideoURL = model.ProductVideos.VideoURL;
// if (!string.IsNullOrWhiteSpace(model.ProductVideos.VideoURL) || !string.IsNullOrWhiteSpace(model.ProductUserGuide.Title))
// video.UpdatedDate = DateTime.UtcNow;
// }
// else
// {
// model.ProductVideos.Id = Guid.NewGuid();
// product.ProductVideos.Add(model.ProductVideos);
// }
// }
// var speci = context.ProductSpecs.FirstOrDefault(y => y.ProductId == model.Id && y.IsDeleted != true);
// if (model.ProductSpec != null)
// {
// if (speci != null)
// {
// if (!string.IsNullOrWhiteSpace(model.ProductSpec.Title))
// speci.Title = model.ProductSpec.Title;
// if (!string.IsNullOrWhiteSpace(model.ProductSpec.Description))
// speci.Description = model.ProductSpec.Description;
// if (!string.IsNullOrWhiteSpace(model.ProductSpec.Description) || !string.IsNullOrWhiteSpace(model.ProductSpec.Title))
// speci.UpdatedDate = DateTime.UtcNow;
// }
// else
// {
// model.ProductSpec.Id = Guid.NewGuid();
// product.ProductSpecs.Add(model.ProductSpec);
// }
// }
// var faqs = context.ProductFAQs.Where(y => y.ProductId == model.Id && y.IsDeleted != true);
// if (faqs.Count() > 0)
// {
// context.ProductFAQs.RemoveRange(faqs);
// }
// if (model.ProductFAQs != null && model.ProductFAQs.Count > 0)
// {
// foreach (var item in model.ProductFAQs)
// {
// if (item.Id == Guid.Empty)
// item.Id = Guid.NewGuid();
// item.ProductId = model.Id;
// product.ProductFAQs.Add(item);
// }
// }
// context.SaveChanges();
// }
// else
// {
// var Productobj = new Product();
// Productobj.Id = Guid.NewGuid();
// Productobj.CreatedDate = DateTime.UtcNow;
// Productobj.Title = model.Title;
// Productobj.Description = model.Description;
// Productobj.ImageURL = model.ImageURL;
// Productobj.SubCategoryId = model.SubCategoryId;
// if (model.ProductUserGuide != null)
// {
// model.ProductUserGuide.Id = Guid.NewGuid();
// Productobj.ProductUserGuides.Add(model.ProductUserGuide);
// }
// if (model.ProductVideos != null)
// {
// model.ProductVideos.Id = Guid.NewGuid();
// Productobj.ProductVideos.Add(model.ProductVideos);
// }
// if (model.ProductSpec != null)
// {
// model.ProductSpec.Id = Guid.NewGuid();
// Productobj.ProductSpecs.Add(model.ProductSpec);
// }
// if (model.ProductFAQs != null && model.ProductFAQs.Count > 0)
// {
// foreach (var item in model.ProductFAQs)
// {
// if (item.Id == Guid.Empty)
// item.Id = Guid.NewGuid();
// Productobj.ProductFAQs.Add(item);
// }
// }
// context.Products.Add(Productobj);
// context.SaveChanges();
// }
// return true;
// }
//}
public Decimal AddUpdateProductBasic(ProductEntity model)
{
using (var context = new UniversityEntities())
{
var product = context.Product.FirstOrDefault(y => y.Id == model.Id && y.IsDeleted != true);
if (product != null)
{
if (!string.IsNullOrWhiteSpace(model.ImageURL))
{
product.ImageURL = model.ImageURL;
}
product.Title = model.Title;
product.SubCategoryId = model.SubCategoryId;
product.Description = model.Description;
product.UpdatedDate = DateTime.UtcNow;
product.ImageALT = model.ImageALT;
product.AssocitedCustID = model.AssocitedCustID;
context.SaveChanges();
return product.Id;
}
else
{
var Productobj = new Product();
Productobj.CreatedDate = DateTime.UtcNow;
Productobj.Title = model.Title;
Productobj.Description = model.Description;
if (!string.IsNullOrWhiteSpace(model.ImageURL))
{
Productobj.ImageURL = model.ImageURL;
}
// product.ImageURL = model.ImageURL;
Productobj.ImageURL = model.ImageURL;
Productobj.SubCategoryId = model.SubCategoryId;
Productobj.ImageALT = model.ImageALT;
Productobj.AssocitedCustID = model.AssocitedCustID;
Productobj.IsDeleted = false;
context.Product.Add(Productobj);
context.SaveChanges();
return Productobj.Id;
}
}
}
public bool DeleteProduct(Decimal id)
{
using (var context = new UniversityEntities())
{
var product = context.Product.FirstOrDefault(y => y.Id == id && y.IsDeleted != true);
if (product != null)
{
product.IsDeleted = true;
product.DeletedDate = DateTime.UtcNow;
if (product.ProductUserGuide.ToList().Count() > 0)
{
product.ProductUserGuide.FirstOrDefault().IsDeleted = true;
}
context.SaveChanges();
}
return true;
}
}
public ProductEntity GetProductByCategory(Decimal Id)
{
using (var context = new UniversityEntities())
{
var res = (from p in context.Product.Where(y => y.IsDeleted != true)
join s in context.SubCategoryMaster.Where(y => y.IsDeleted != true)
on p.SubCategoryId equals s.Id
join c in context.CategoryMaster.Where(y => y.IsDeleted != true)
on s.CategoryId equals c.Id
join g in context.ProductUserGuide.Where(y => y.IsDeleted != true)
on p.Id equals g.ProductId into temp
from guide in temp.DefaultIfEmpty()
//join v in context.ProductVideos.Where(y => y.IsDeleted != true)
//on p.Id equals v.ProductId into tempV
//from videos in tempV.DefaultIfEmpty()
where p.SubCategoryId == Id
select new ProductEntity()
{
Id = p.Id,
CreatedBy = p.CreatedBy,
CreatedDate = p.CreatedDate,
DeletedBy = p.DeletedBy,
DeletedDate = p.DeletedDate,
Description = p.Description,
ImageURL = p.ImageURL,
IsDeleted = p.IsDeleted,
SubCategoryId = p.SubCategoryId,
Title = p.Title,
UpdatedBy = p.UpdatedBy,
UpdatedDate = p.UpdatedDate,
CategoryMaster = c,
SubCategoryMaster = s,
ProductUserGuide = guide,
ProductVideos = context.ProductVideos.Where(y => y.IsDeleted != true).ToList(),
ProductDocuments = context.ProductDocuments.Where(y => y.IsDeleted != true).ToList()
}).ToList();
return res.FirstOrDefault();
}
}
public Decimal SaveProductFAQ(ProductFAQs productFAQ)
{
using (var context = new UniversityEntities())
{
var productFaq = context.ProductFAQs.FirstOrDefault(y => y.Id == productFAQ.Id && y.IsDeleted != true);
if (productFaq != null)
{
productFaq.AssocitedCustID = productFAQ.AssocitedCustID;
productFaq.UpdatedDate = DateTime.UtcNow;
productFaq.Question = productFAQ.Question;
productFaq.Answer = productFAQ.Answer;
context.SaveChanges();
return productFaq.Id;
}
else
{
productFAQ.CreatedDate = DateTime.UtcNow;
context.ProductFAQs.Add(productFAQ);
context.SaveChanges();
return productFAQ.Id;
}
}
}
public bool DeleteProductFAQ(Decimal productFAQId)
{
using (var context = new UniversityEntities())
{
var productFaq = context.ProductFAQs.FirstOrDefault(y => y.Id == productFAQId);
if (productFaq != null)
{
productFaq.IsDeleted = true;
productFaq.DeletedDate = DateTime.UtcNow;
context.SaveChanges();
}
}
return true;
}
public ProductFAQs GetProductFAQ(Decimal productFAQId)
{
using (var context = new UniversityEntities())
{
var productFaq = context.ProductFAQs.Include("ProductFAQVideos").FirstOrDefault(y => y.Id == productFAQId && y.IsDeleted != true);
return productFaq;
}
}
public List<ProductFAQs> GetProductFAQs(Decimal productId)
{
using (var context = new UniversityEntities())
{
var productFaq = context.ProductFAQs.Include("ProductFAQVideos").Where(y => y.ProductId == productId && y.IsDeleted != true).ToList();
return productFaq;
}
}
public Decimal SaveProductFAQVideo(ProductFAQVideos productFAQVideo)
{
using (var context = new UniversityEntities())
{
var productFaqVideo = context.ProductFAQVideos.FirstOrDefault(y => y.Id == productFAQVideo.Id && y.IsDeleted == false);
if (productFaqVideo != null)
{
productFaqVideo.UpdatedDate = DateTime.UtcNow;
productFaqVideo.IsDeleted = false;
if (!string.IsNullOrWhiteSpace(productFAQVideo.VideoURL))
{
productFaqVideo.VideoURL = productFAQVideo.VideoURL;
}
if (!string.IsNullOrWhiteSpace(productFAQVideo.ImageURL))
{
productFaqVideo.ImageURL = productFAQVideo.ImageURL;
}
context.SaveChanges();
return productFaqVideo.Id;
}
else
{
//productFAQ.Id = Guid.NewGuid();
productFAQVideo.CreatedDate = DateTime.UtcNow;
productFAQVideo.IsDeleted = false;
context.ProductFAQVideos.Add(productFAQVideo);
context.SaveChanges();
return productFAQVideo.Id;
}
}
}
public bool DeleteProductFAQVideo(int productFAQVideoId)
{
using (var context = new UniversityEntities())
{
var productFaqVideo = context.ProductFAQVideos.FirstOrDefault(y => y.Id == productFAQVideoId);
if (productFaqVideo != null)
{
productFaqVideo.IsDeleted = true;
productFaqVideo.DeletedDate = DateTime.UtcNow;
context.SaveChanges();
}
}
return true;
}
public ProductFAQVideos GetProductFAQVideo(Decimal productFAQVideoId)
{
using (var context = new UniversityEntities())
{
var productFaqVideo = context.ProductFAQVideos.FirstOrDefault(y => y.Id == productFAQVideoId && y.IsDeleted != true);
return productFaqVideo;
}
}
public List<ProductEntity> GetProducts()
{
using (var context = new UniversityEntities())
{
var res = (from p in context.Product.Where(y => y.IsDeleted != true)
join s in context.SubCategoryMaster.Where(y => y.IsDeleted != true)
on p.SubCategoryId equals s.Id
join c in context.CategoryMaster.Where(y => y.IsDeleted != true)
on s.CategoryId equals c.Id
join g in context.ProductUserGuide.Where(y => y.IsDeleted != true && y.Title != null)
on p.Id equals g.ProductId into temp
from guide in temp.DefaultIfEmpty()
join v in context.ProductVideos.Where(y => y.IsDeleted != true && y.Title != null)
on p.Id equals v.ProductId into tempV
from videos in tempV.DefaultIfEmpty()
join spec in context.ProductSpec.Where(y => y.IsDeleted != true && y.Title != null)
on p.Id equals spec.ProductId into tempS
from speci in tempS.DefaultIfEmpty()
select new ProductEntity()
{
Id = p.Id,
//CategoryId = c.Id,
CreatedBy = p.CreatedBy,
CreatedDate = p.CreatedDate,
DeletedBy = p.DeletedBy,
DeletedDate = p.DeletedDate,
Description = p.Description,
ImageURL = p.ImageURL,
IsDeleted = p.IsDeleted,
SubCategoryId = p.SubCategoryId,
Title = p.Title,
UpdatedBy = p.UpdatedBy,
UpdatedDate = p.UpdatedDate,
CategoryMaster = c,
SubCategoryMaster = s,
ProductUserGuide = guide,
/*roductVideos= videos,*/
ProductSpec = speci,
ProductFAQs = p.ProductFAQs
}).ToList();
return res;
}
}
#region Specification
public ProductSpec GetProductSpecification(Decimal ProductId)
{
using (var context = new UniversityEntities())
{
var spec = context.ProductSpec.FirstOrDefault(y => y.ProductId == ProductId && y.IsDeleted != true);
return spec;
}
}
public bool SaveProductSpecification(ProductSpec productSpec)
{
using (var context = new UniversityEntities())
{
var spec = context.ProductSpec.FirstOrDefault(y => y.Id == productSpec.Id && y.IsDeleted != true);
if (spec != null)
{
spec.Description = productSpec.Description;
spec.Title = productSpec.Title;
spec.AssocitedCustID = productSpec.AssocitedCustID;
spec.UpdatedDate = DateTime.UtcNow;
spec.IsDeleted = false;
context.SaveChanges();
}
else
{
productSpec.IsDeleted = false;
productSpec.CreatedDate = DateTime.UtcNow;
context.ProductSpec.Add(productSpec);
context.SaveChanges();
}
return true;
}
}
#endregion
#region User Guide
public ProductUserGuide GetProductUserGuide(Decimal ProductId)
{
using (var context = new UniversityEntities())
{
var guide = context.ProductUserGuide.FirstOrDefault(y => y.ProductId == ProductId && y.IsDeleted != true);
return guide;
}
}
public bool SaveProductUserGuide(ProductUserGuide productUserGuide)
{
using (var context = new UniversityEntities())
{
var guide = context.ProductUserGuide.FirstOrDefault(y => y.Id == productUserGuide.Id && y.IsDeleted != true);
if (guide != null)
{
guide.AssocitedCustID = productUserGuide.AssocitedCustID;
guide.Description = productUserGuide.Description;
guide.Title = productUserGuide.Title;
guide.DocumentURL = productUserGuide.DocumentURL;
if (productUserGuide.ImageURL != null)
{
guide.ImageURL = productUserGuide.ImageURL;
}
guide.UpdatedDate = DateTime.UtcNow;
guide.IsDeleted = false;
//guide.ImageALT = productUserGuide.ImageALT;
context.SaveChanges();
}
else
{
productUserGuide.IsDeleted = false;
productUserGuide.CreatedDate = DateTime.UtcNow;
context.ProductUserGuide.Add(productUserGuide);
context.SaveChanges();
}
return true;
}
}
#endregion
#region courese preview video
public bool SaveCoursePreviewVideo(CoursePreviewVideos coursePreviewVideos)
{
using (var context = new UniversityEntities())
{
var CoursePreviewvideoExising = context.CoursePreviewVideos.FirstOrDefault(y => y.PreviewID == coursePreviewVideos.PreviewID && y.IsDeleted != true);
if (CoursePreviewvideoExising != null)
{
CoursePreviewvideoExising.AssocitedCustID = coursePreviewVideos.AssocitedCustID;
CoursePreviewvideoExising.UpdatedDate = DateTime.UtcNow;
CoursePreviewvideoExising.Title = coursePreviewVideos.Title;
CoursePreviewvideoExising.Description= coursePreviewVideos.Description;
//CoursePreviewvideoExising.VideoRate = productVideo.VideoRate;
CoursePreviewvideoExising.IsDeleted = false;
if (!string.IsNullOrWhiteSpace(coursePreviewVideos.VideoURL))
{
CoursePreviewvideoExising.VideoURL = coursePreviewVideos.VideoURL;
}
//if (!string.IsNullOrWhiteSpace(productVideo.ThumbnailURL))
//{
// productVideoExising.ThumbnailURL = productVideo.ThumbnailURL;
//}
context.SaveChanges();
//return CoursePreviewvideoExising.PreviewID;
}
else
{
coursePreviewVideos.IsDeleted = false;
coursePreviewVideos.CreatedDate = DateTime.UtcNow;
coursePreviewVideos.ProductID = coursePreviewVideos.ProductID;
context.CoursePreviewVideos.Add(coursePreviewVideos);
context.SaveChanges();
//return coursePreviewVideos.PreviewID;
}
return true;
}
}
#endregion courese preview video
#region Product Videos
public bool UpdateProductvideo(ProductVideos model)
{
using (var context = new UniversityEntities())
{
var productvideo = context.ProductVideos.FirstOrDefault(y => y.Id == model.Id && y.IsDeleted != true);
if (productvideo != null)
{
productvideo.Decription = model.Decription;
productvideo.Title = model.Title;
productvideo.ProductId = model.ProductId;
productvideo.ThumbnailURL = model.ThumbnailURL;
//productvideo.AssocitedID = model.AssocitedID;
if (!string.IsNullOrWhiteSpace(model.VideoURL))
{
productvideo.VideoURL = model.VideoURL;
}
productvideo.IsDeleted = false;
productvideo.UpdatedDate = DateTime.UtcNow;
context.SaveChanges();
}
else
{
model.CreatedDate = DateTime.UtcNow;
model.IsDeleted = false;
context.ProductVideos.Add(model);
context.SaveChanges();
}
return true;
}
}
public Decimal SaveProductVideo(ProductVideos productVideo)
{
using (var context = new UniversityEntities())
{
var productVideoExising = context.ProductVideos.FirstOrDefault(y => y.Id == productVideo.Id && y.IsDeleted != true);
if (productVideoExising != null)
{
productVideoExising.AssocitedCustID = productVideo.AssocitedCustID;
productVideoExising.UpdatedDate = DateTime.UtcNow;
productVideoExising.Title = productVideo.Title;
productVideoExising.Decription = productVideo.Decription;
productVideoExising.VideoRate = productVideo.VideoRate;
productVideoExising.IsDeleted = false;
if (!string.IsNullOrWhiteSpace(productVideo.VideoURL))
{
productVideoExising.VideoURL = productVideo.VideoURL;
}
if (!string.IsNullOrWhiteSpace(productVideo.ThumbnailURL))
{
productVideoExising.ThumbnailURL = productVideo.ThumbnailURL;
}
context.SaveChanges();
return productVideoExising.Id;
}
else
{
productVideo.IsDeleted = false;
productVideo.CreatedDate = DateTime.UtcNow;
context.ProductVideos.Add(productVideo);
context.SaveChanges();
return productVideo.Id;
}
}
}
public bool DeleteProductVideo(Decimal productVideoId)
{
using (var context = new UniversityEntities())
{
var productVideo = context.ProductVideos.FirstOrDefault(y => y.Id == productVideoId);
if (productVideo != null)
{
productVideo.VideoRateSum = productVideo.VideoRateSum - productVideo.VideoRate ??0;
productVideo.IsDeleted = true;
productVideo.DeletedDate = DateTime.UtcNow;
context.SaveChanges();
}
}
return true;
}
#region courese preview video
public CoursePreviewVideos GetCoursePrviewVideo(Decimal CourseID)
{
using (var context = new UniversityEntities())
{
var courseprevvideo = context.CoursePreviewVideos.FirstOrDefault(y => y.ProductID == CourseID && y.IsDeleted != true);
return courseprevvideo;
}
}
public bool DeletePreviewVideo(Decimal CourseVideoId)
{
using (var context = new UniversityEntities())
{
var productVideo = context.CoursePreviewVideos.FirstOrDefault(y => y.PreviewID == CourseVideoId);
if (productVideo != null)
{
productVideo.IsDeleted = true;
productVideo.DeletedDate = DateTime.UtcNow;
context.SaveChanges();
}
}
return true;
}
#endregion course preview video
public ProductVideos GetProductVideo(Decimal productVideoId)
{
using (var context = new UniversityEntities())
{
var productVideo = context.ProductVideos.FirstOrDefault(y => y.Id == productVideoId && y.IsDeleted != true);
return productVideo;
}
}
#endregion
#region Product Documents
public Decimal SaveProductDocument(ProductDocuments productDocument)
{
using (var context = new UniversityEntities())
{
var productDocumentExising = context.ProductDocuments.FirstOrDefault(y => y.Id == productDocument.Id && y.IsDeleted != true);
if (productDocumentExising != null)
{
productDocument.AssocitedCustID = productDocument.AssocitedCustID;
productDocumentExising.UpdatedDate = DateTime.UtcNow;
if (!string.IsNullOrWhiteSpace(productDocument.DocumentURL))
{
productDocumentExising.DocumentURL = productDocument.DocumentURL;
}
productDocumentExising.Decription = productDocument.Decription;
productDocumentExising.DocumentDisplayName = productDocument.DocumentDisplayName;
productDocumentExising.Title = productDocument.Title;
context.SaveChanges();
return productDocumentExising.Id;
}
else
{
productDocument.CreatedDate = DateTime.UtcNow;
context.ProductDocuments.Add(productDocument);
context.SaveChanges();
return productDocument.Id;
}
}
}
public bool DeleteProductDocument(Decimal productDocumentId)
{
using (var context = new UniversityEntities())
{
var productDocument = context.ProductDocuments.FirstOrDefault(y => y.Id == productDocumentId);
if (productDocument != null)
{
productDocument.IsDeleted = true;
productDocument.DeletedDate = DateTime.UtcNow;
context.SaveChanges();
}
}
return true;
}
public ProductDocuments GetProductDocument(Decimal productDocumetId)
{
using (var context = new UniversityEntities())
{
var productDocument = context.ProductDocuments.FirstOrDefault(y => y.Id == productDocumetId && y.IsDeleted != true);
return productDocument;
}
}
#endregion
#region Product Feedback
public List<ProductFeedback> GetProductFeedback()
{
using (var context = new UniversityEntities())
{
var productFeedback = context.ProductFeedback.Include("Product").Where(y => y.IsDeleted != true).ToList();
return productFeedback;
}
}
#endregion
#region Layout menu
public List<ProductLayoutMenu> GetProductLayouMenu()
{
using (var context = new UniversityEntities())
{
int UserID = Convert.ToInt32(HttpContext.Current.Session["UserLoginID"]);
var res = (from p in context.Product.Where(y => y.IsDeleted != true)
join s in context.SubCategoryMaster.Where(y => y.IsDeleted != true )
on p.SubCategoryId equals s.Id
join cm in context.CategoryUserMapping.Where(y=>y.IsDeleted!=true)
on s.Id equals cm.CategoryID
join l in context.Login_tbl.Where(y => y.ID == UserID)
on cm.UserID equals l.ID
select new ProductLayoutMenu()
{
ProductId = p.Id,
ProductName = p.Title,
SubCategoryId = s.Id,
SubCategoryName = s.Name,
CategoryMappID=cm.ID,
CategoryUserMappID=l.ID
}).ToList();
return res;
}
}
#endregion
//video addition
public IEnumerable<ProductVideos> GetUserVideosLists()
{
using (var context = new UniversityEntities())
{
// int UserID = Convert.ToInt32(HttpContext.Current.Session["UserLoginID"]);
int AssocitedCustID = Convert.ToInt32(HttpContext.Current.Session["AdminLoginID"]);
//var res = (from l in context.Login_tbl.Where(y => y.IsDeleted != true && y.ID == AssocitedCustID)
// join cm in context.CategoryUserMapping.Where(y => y.IsDeleted != true && y.AdminID == AssocitedCustID)
// on l.ID equals cm.AdminID
// join c in context.SubCategoryMaster.Where(y => y.IsDeleted != true)
// on cm.CategoryID equals c.Id
// join p in context.Product.Where(y => y.IsDeleted != true)
// on c.Id equals p.SubCategoryId
// join pv in context.ProductVideos.Where(y => y.IsDeleted != true)
// on p.Id equals pv.ProductId
// orderby pv.CreatedDate
var res = (from p in context.Product.Where(y => y.IsDeleted != true && y.AssocitedCustID == AssocitedCustID)
join s in context.SubCategoryMaster.Where(y => y.IsDeleted != true)
on p.SubCategoryId equals s.Id
join c in context.CategoryMaster.Where(y => y.IsDeleted != true)
on s.CategoryId equals c.Id
//group p by p.Id into g
select new
{
p.Id,
p.Title,
subcatid = c.Id,
s.Name,
VideoRateSum = p.ProductVideos.Sum(x => x.VideoRate)
}
).ToList();
List<ProductVideos> productvideo = new List<ProductVideos>();
foreach (var prodvideo in res)
{
productvideo.Add(new ProductVideos
{
Id = prodvideo.Id,
Title = prodvideo.Title,
subcategoryname = prodvideo.Name,
catid = prodvideo.subcatid,
VideoRate = prodvideo.VideoRateSum
});
}
return productvideo;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; // Keys
namespace CalculationServices
{
public class Token
{
/// <summary>
/// Check if input character is able to accept for parser.
/// </summary>
/// <param name="token"></param>
/// <returns>true :acceptable , false :not acceptable</returns>
public static bool isToken(char token)
{
if (isNumber(token))
return true;
if (isMinusSign(token))
return true;
if (isOperator(token))
return true;
if (isParenthesis(token))
return true;
return false;
}
/// <summary>
/// Check if input character is operator's sign.
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public static bool isOperator(char token)
{
switch (token)
{
case Operator.ADD:
case Operator.SUB:
case Operator.MUL:
case Operator.DIV:
return true;
default:
return false;
}
}
/// <summary>
/// Check if input character is parenthesis.
/// </summary>
/// <param name="token"></param>
/// <returns>true:parenthesis , false:not parenthesis</returns>
public static bool isParenthesis(char token)
{
switch (token)
{
case Parenthesis.BEGIN:
case Parenthesis.END:
return true;
default:
return false;
}
}
/// <summary>
/// Check if argument's value is number or not.
/// </summary>
/// <param name="token"></param>
/// <returns>true : number , false : not number</returns>
public static bool isNumber(char token)
{
switch (token)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
default:
return false;
}
}
/// <summary>
/// Check if input character is minus sign or not.
/// </summary>
/// <param name="token"></param>
/// <returns>true : minus sign , false : not minus sign</returns>
public static bool isMinusSign(char token)
{
if (token == Num.MINUS)
return true;
else
return false;
}
/// <summary>
/// Check if input character is equal sign or not.
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public static bool isEqual(char token)
{
if (token == EQUAL)
return true;
else
return false;
}
/// <summary>
/// Check if input character is 'backspace' key or not.
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
/// <remarks>backspace key is not token.</remarks>
public static bool isBackSpace(char token)
{
if (token == (char)Keys.Back)
return true;
else
return false;
}
/// <summary>
/// Operator's sign.
/// </summary>
public class Operator
{
public const char ADD = '+'; // Adding
public const char SUB = '-'; // Subtraction
public const char MUL = '*'; // Multi
public const char DIV = '/'; // Division
}
/// <summary>
/// Express numbers.
/// </summary>
public class Num
{
public const char MINUS = '-';
public const char ZERO = '0';
public const char ONE = '1';
public const char TWO = '2';
public const char THREE = '3';
public const char FOUR = '4';
public const char FIVE = '5';
public const char SIX = '6';
public const char SEVEN = '7';
public const char EIGHT= '8';
public const char NINE = '9';
}
/// <summary>
/// Parenthesis '(' , ')'
/// </summary>
public class Parenthesis
{
public const char BEGIN = '(';
public const char END = ')';
}
/// <summary>
/// Express '='
/// </summary>
public const char EQUAL = '=';
}
}
|
using PJEI;
using UnityEngine;
public class TimeWrapperTest : MonoBehaviour {
[SerializeField]
private Rect instructionsRect = new Rect(50, 100, 500, 100);
[SerializeField]
private Rect textRect = new Rect(50, 50, 300, 20);
void OnGUI() {
GUI.Label(this.instructionsRect, "Press P to pause the game for one second.\nPress S to slow down by half for one game second.\nPress F to fast forward the game by double for one game second");
if (TimeWrapper.Paused)
GUI.Label(this.textRect, "PAUSED");
else
GUI.Label(this.textRect, "Time scale: " + Time.timeScale + " Fixed delta time: " + Time.fixedDeltaTime);
}
void Update() {
if (Input.GetKeyDown(KeyCode.P))
TimeWrapper.Pause(1f);
if (Input.GetKeyDown(KeyCode.S))
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
TimeWrapper.OverrideTimeForRealSeconds(.5f, 1f);
else
TimeWrapper.WarpTimeForGameSeconds(.5f, 1f);
if (Input.GetKeyDown(KeyCode.F))
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
TimeWrapper.OverrideTimeForRealSeconds(2f, 1f);
else
TimeWrapper.WarpTimeForGameSeconds(2f, 1f);
}
}
|
using System;
namespace NLogDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Addition Problem \n Enter 2 numbers");
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
Add_Number add = new Add_Number();
Console.WriteLine("Result is" + add.Sum(a,b));
}
}
}
|
using SqlSugar;
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 twpx.Dao;
using twpx.Model;
namespace twpx.VIew
{
public partial class Jxlgl : Form
{
SqlSugarClient db = SugarDao.GetInstance();
public Jxlgl()
{
InitializeComponent();
LoadData();
}
// 加载数据
public void LoadData()
{
listView1.Items.Clear();
var list = db.Queryable<Building>().ToList();
foreach (var i in list)
{
ListViewItem item = new ListViewItem();
item.Text = i.Id.ToString();
item.SubItems.Add(i.Name);
item.SubItems.Add(i.Address);
listView1.Items.Add(item);
}
}
// 添加/更新信息
public void saveData()
{
var building = new Building();
var result = 0;
building.Name = textBox1.Text.Trim();
building.Address = textBox3.Text.Trim();
if ("".Equals(textBox2.Text) || textBox2.Text == null)
{
result = db.Insertable(building).ExecuteCommand();
}
else
{
building.Id = int.Parse(textBox2.Text);
result = db.Updateable(building).ExecuteCommand();
}
LoadData();
clearBlank();
}
// 清除信息
private void clearBlank()
{
textBox2.Text = "";
textBox1.Text = "";
textBox3.Text = "";
}
// 清除信息按钮
private void button5_Click(object sender, EventArgs e)
{
clearBlank();
}
// 添加按钮
private void button1_Click(object sender, EventArgs e)
{
saveData();
}
// 删除按钮
private void button2_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count == 0)
{
MessageBox.Show("未选中项!");
return;
}
int id = int.Parse(listView1.SelectedItems[0].Text);
var result = db.Deleteable<Building>().In(id).ExecuteCommand();
if (result == 1) LoadData();
}
// 刷新按钮
private void button4_Click(object sender, EventArgs e)
{
LoadData();
}
// 批量删除
private void button3_Click(object sender, EventArgs e)
{
if (listView1.CheckedItems.Count == 0)
{
MessageBox.Show("未选中项!");
return;
}
int[] ids = new int[listView1.CheckedItems.Count];
for (int i = 0; i < listView1.CheckedItems.Count; i++)
{
ids[i] = int.Parse(listView1.CheckedItems[i].Text);
}
var result = db.Deleteable<Building>().In(ids).ExecuteCommand();
if (result == listView1.CheckedItems.Count) LoadData();
}
// 选中项变化
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count == 0)
{
clearBlank();
return;
}
textBox2.Text = listView1.SelectedItems[0].Text;
textBox1.Text = listView1.SelectedItems[0].SubItems[1].Text;
textBox3.Text = listView1.SelectedItems[0].SubItems[2].Text;
}
// END
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonAnimController : MonoBehaviour {
private void Update()
{
#if UNITY_EDITOR
//For Testing ---
if (Input.GetKeyDown(KeyCode.Q))
{
ButtonSelected();
}
if (Input.GetKeyDown(KeyCode.E))
{
ButtonReturn();
}
// ---
#endif
}
public void ButtonSelected()
{
if (gameObject.tag == "LargeButton")
{
//gameObject.GetComponent<Animation>().Play("ButtonSelected");
GetComponent<Animator>().SetInteger("Selected", 1);
}
else if (gameObject.tag == "SmallButton")
{
//gameObject.GetComponent<Animation>().Play("SmallButtonSelected");
GetComponent<Animator>().SetInteger("Selected", 1);
}
}
public void ButtonReturn()
{
if (gameObject.tag == "LargeButton")
{
//gameObject.GetComponent<Animation>().Play("ButtonReturn");
GetComponent<Animator>().SetInteger("Selected", 0);
}
else if (gameObject.tag == "SmallButton")
{
//gameObject.GetComponent<Animation>().Play("SmallButtonReturn");
GetComponent<Animator>().SetInteger("Selected", 0);
}
}
}
|
namespace ConsoleApplication1
{
public enum Education : byte { Master, Bachelor, SecondEducation }
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AddDrumUI : MonoBehaviour {
//Slider that dictates the number of beats to add to the new DrumTrack when created
public Slider drumBeatSlider;
//Text that displays number shown by the handle on the slider to let the user know what number of straight beats will be added when DrumTrack is created
public Text sliderText;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//Called when the drumBeat slider is moved by the user. The value is held by the GameObject itself so isn't edited here, however the text needs to be changed to this new value hence this methods need
public void sliderChanged()
{
sliderText.text = Mathf.RoundToInt(drumBeatSlider.value).ToString();
}
//Called when the user presses confirmed, will add the new drum track, and start the process of updating the graphic to correspond to the new state, also, if the main UI has not been activated
//for mouse clicks, this will activate it for the user to begin editing
public void pressedConfirm()
{
GameObject.Find("Main").GetComponent<Main>().addDrumTrack(Mathf.RoundToInt(drumBeatSlider.value), 0);
this.gameObject.SetActive(false);
GameObject.Find("Main Camera").GetComponent<Mouse>().activateCircleUI();
}
//Called when the user presses cancel, removes the AddDrumPanel from view
public void pressedCancel()
{
this.gameObject.SetActive(false);
//GameObject.Find("Main Camera").GetComponent<Mouse>().activateCircleUI();
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Alura.Loja.Testes.ConsoleApp
{
//Include() -> pega tabela relacionada
//ThenInclude() -> pegar tabelas em um segundo nivel (segundo... JOIN)
//Load() -> carrega os objetos relacionado, que ainda nao foram caregados, (Objetos internos)
class Program
{
static void Main(string[] args)
{
RecuperarDadosRelacionadosUmParaUm();
Console.ReadLine();
}
private static void RecuperarDadosRelacionadosUmParaUm()
{
using (var contexto = new LojaContext())
{
var cliente = contexto.Clientes.Include(c => c.EndereDeEntrega).FirstOrDefault();//faz o JOIN na tabela de Enderecos
Console.WriteLine($"Enderco de entrega {cliente.EndereDeEntrega.Logradouro}");
////Recupera as compras de um produto
var produto = contexto.Produtos.Include(p => p.Compras).FirstOrDefault();
foreach (var item in produto.Compras)
{
Console.WriteLine($"Compas do produto {item.Produto.Nome}");
}
Console.WriteLine($"==============================================");
//filtra pelo valor compra
produto = contexto.Produtos.FirstOrDefault(); //recupera o produto, sem o Include
contexto.Entry(produto) //para as entidades da referencia produto
.Collection(p => p.Compras) //pega a colecao de Compras
.Query() //realiza uma consulta
.Where(c => c.Preco > 9) //com a WHERE
.Load(); //carrega para a referencia de produtos
//foi removido o INNER no primeiro momento, para poder realizar a consulta no INNER com filtro
//ja que as compras nao foram carregas de cara, nao ah diferencao de desempenho
foreach (var item in produto.Compras)
{
Console.WriteLine($"Compas do produto {item.Produto.Nome}");
}
}
}
private static void RecuperarDadosRelacionadosMuitosParaMuitos()
{
//using (var contexto = new LojaContext())
//{
// var promocao = new Promocao();
// promocao.Descricao = "Queima de Estoque";
// promocao.DataInicio = new DateTime(2017, 1, 1);
// promocao.DataTermino = new DateTime(2017, 1, 30);
// var produtos = contexto.Produtos.Where(p => p.Categoria == "Bebidas").ToList();//Select com WHERE
// foreach (var item in produtos )
// {
// promocao.IncluiProduto(item);
// }
// contexto.Promocaos.Add(promocao);
// contexto.SaveChanges();
//}
using (var contexto = new LojaContext())
{
var promocao = contexto.Promocaos
.Include(p => p.Produtos) //Include Desce um nivel no relacionamento
.ThenInclude(pp => pp.Produto)//Os proximos Join deve usar ThenInclude
.FirstOrDefault();
foreach (var item in promocao.Produtos )
{
Console.WriteLine(item.Produto.Nome);
}
}
}
private static void SalvarUmParaUm()
{
var fulano = new Cliente();
fulano.Nome = "Fulaninho";
fulano.EndereDeEntrega = new Endereco()
{
Numero = 12,
Logradouro = "Rua dos Invalidos",
Complemento = "Sobrado",
Bairro = "Centro",
Cidade = "Cidade"
};
using (var contexto = new LojaContext())
{
contexto.Clientes.Add(fulano);
contexto.SaveChanges();
}
}
private static void SalvarMuitoParaMuitos()
{
var p1 = new Produto();
var p2 = new Produto();
var p3 = new Produto();
var promocaoDePasco = new Promocao();
promocaoDePasco.Descricao = "Pascoa Feliz";
promocaoDePasco.DataInicio = DateTime.Now;
promocaoDePasco.DataTermino = DateTime.Now;
promocaoDePasco.IncluiProduto(p1);
promocaoDePasco.IncluiProduto(p2);
promocaoDePasco.IncluiProduto(p3);
using (var contexto = new LojaContext())
{
contexto.Promocaos.Add(promocaoDePasco);
contexto.SaveChanges();
}
}
private static void SalvarUmParaMuitos()
{
var paoFrances = new Produto();
paoFrances.Nome = "Pao frances";
paoFrances.PrecoUnidade = 0.40;
paoFrances.Unidade = "Unidade";
paoFrances.Categoria = "Padaria";
var compra = new Compra();
compra.Quantidade = 6;
compra.Produto = paoFrances;
compra.Preco = paoFrances.PrecoUnidade * compra.Quantidade;
using (var contexto = new LojaContext())
{
contexto.Compras.Add(compra);
contexto.SaveChanges();
}
}
private static void getLogger()
{
using (var context = new LojaContext())
{
var serviceProvider = context.GetInfrastructure<IServiceProvider>();
var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
loggerFactory.AddProvider(SqlLoggerProvider.Create());
var produtos = context.Produtos.ToList();
foreach (var item in produtos)
{
}
}
}
private static void AtualizarProduto()
{
using (var context = new ProdutoDAOEntity())
{
Produto produtos = context.Produtos()[0];
produtos.Nome = "Teste test3333e";
context.Atualizar(produtos);
}
}
private static void RemoverProdutos()
{
using (var context = new ProdutoDAOEntity())
{
IList<Produto> produtos = context.Produtos();
context.Remover (produtos[0]);
}
}
private static void RecuperarProdutos()
{
using (var context = new ProdutoDAOEntity())
{
IList<Produto> produtos = context.Produtos();
foreach (var item in produtos)
{
Console.WriteLine(item.Nome);
}
}
}
private static void GravarUsandoEntity()
{
Produto p = new Produto();
p.Nome = "Harry Potter e a Ordem da Fênix";
p.Categoria = "Livros";
p.PrecoUnidade = 19.89;
using (var context = new ProdutoDAOEntity())
{
context.Adicionar(p);
}
}
private static void GravarUsandoAdoNet()
{
Produto p = new Produto();
p.Nome = "Harry Potter e a Ordem da Fênix";
p.Categoria = "Livros";
p.PrecoUnidade = 19.89;
using (var repo = new ProdutoDAO())
{
repo.Adicionar(p);
}
}
}
}
|
using System.Collections.ObjectModel;
using Android.Content;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
namespace ResidentAppCross.Droid.Views.Components.NavigationDrawer
{
public class NavigationDrawerAdapter : RecyclerView.Adapter
{
public ObservableCollection<HomeMenuItemViewModel> Items { get; set; }
public LayoutInflater Inflater { get; set; }
public Context Context { get; set; }
public NavigationDrawerAdapter(Context ctx, ObservableCollection<HomeMenuItemViewModel> items)
{
Context = ctx;
Inflater = LayoutInflater.From(ctx);
Items = items;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
var view = Inflater.Inflate(Resource.Layout.nav_item_main, parent, false);
return new ViewHolder(view);
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
var vh = holder as ViewHolder;
if (vh != null) vh.Title = Items[position].Name;
}
public override int ItemCount => Items?.Count ?? 0;
public class ViewHolder : RecyclerView.ViewHolder
{
public ViewHolder(View itemView) : base(itemView)
{
View = itemView;
TitleLabel = View.FindViewById<TextView>(Resource.Id.title);
}
public TextView TitleLabel { get; set; }
public View View { get; set; }
public string Title
{
get { return TitleLabel.Text; }
set { TitleLabel.Text = value; }
}
}
}
} |
namespace RosPurcell.Web.Infrastructure.Mapping
{
using System;
using RosPurcell.Web.Infrastructure.DependencyInjection;
using RosPurcell.Web.ViewModels.Media;
using Umbraco.Core.Models;
using Zone.UmbracoMapper;
/// <summary>
/// Custom extension of the Umbraco Mapper, where custom mappings should be registered.
/// </summary>
public class CustomMapper : UmbracoMapper
{
#region Constructor
/// <summary>
/// Initialises a new instance of the <see cref="CustomMapper" /> class. Register custom mappings here.
/// Any type registered here should also have an ICustomUmbracoMapping implementation.
/// </summary>
public CustomMapper()
{
RegisterMapping<Document>();
RegisterMapping<HeroImage>();
RegisterMapping<TeaserImage>();
RegisterMapping<Svg>();
}
#endregion Constructor
#region Helpers
private static object Adapt<T>(
Func<IUmbracoMapper, IPublishedContent, string, bool, T> map,
IUmbracoMapper mapper,
IPublishedContent content,
string alias,
bool recursive)
{
return map(mapper, content, alias, recursive);
}
/// <summary>
/// Converts an ICustomUmbracoMapping.Map method into a CustomMapping which
/// can then be registered in this Umbraco Mapper. Essentially, this method
/// converts a mapping with return type T to a method with return type object.
/// </summary>
/// <typeparam name="T">Type to be mapped</typeparam>
/// <param name="map">Mapping which maps type T</param>
/// <returns>A CustomMapping with the same logic as the map method</returns>
private static CustomMapping GetObjectMapping<T>(Func<IUmbracoMapper, IPublishedContent, string, bool, T> map)
{
Func<IUmbracoMapper, IPublishedContent, string, bool, object> adapted = (m, c, p, r) => Adapt(map, m, c, p, r);
return new CustomMapping(adapted);
}
/// <summary>
/// Gets the mapping for a particular type, and registers that mapping
/// in this Umbraco Mapper using the AddCustomMapping method.
/// </summary>
/// <typeparam name="T">Type to be mapped</typeparam>
private void RegisterMapping<T>()
{
var typeName = typeof(T).FullName;
var mapping = NinjectWebCommon.GetBinding<ICustomMapping<T>>();
AddCustomMapping(typeName, GetObjectMapping(mapping.Map));
}
#endregion Helpers
}
}
|
using Clients.Screener;
using Common;
using Common.Business;
using Common.Log;
using SessionSettings;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.ServiceModel;
using System.Threading;
namespace Screeners
{
public class Barcode : IDisposable
{
#region Private Fields
private ClientPresentation mClientPresentation = null;
private string mFileName = String.Empty;
private bool mIsDisposed = false;
private ScreenerProxy mProxy = null;
#endregion
#region Constructors
public Barcode()
{
CreateComponent();
}
#endregion
#region Finalizers
~Barcode()
{
Dispose(false);
GC.SuppressFinalize(this);
}
#endregion
#region Public Properties
public string FileName
{
get { return mFileName; }
}
#endregion
#region Public Methods
public void Dispose()
{
Dispose(true);
}
public bool PrintBarcode(int screenerId)
{
return PrintBarcode(screenerId, String.Empty, null, null);
}
public bool PrintBarcode(int screenerId, string title, int? studioId, CompanyInfo licensor)
{
bool result = false;
OpenProxy();
try
{
if (!studioId.HasValue)
{
Tuple<string, int> contract = mProxy.GetContractTitleStudio(screenerId);
if (contract == null)
return false;
studioId = contract.Item2;
title = contract.Item1;
}
string studioName = mProxy.GetStudioName(studioId.Value);
if (licensor == null)
licensor = mProxy.GetLicensorByScreenerId(screenerId);
string path = Assembly.GetExecutingAssembly().Location;
if (!path.EndsWith("\\"))
path += "\\";
path += "email\\";
mFileName = path + "barcode1.txt";
using (TextWriter tw = File.CreateText(mFileName))
{
tw.WriteLine();
tw.WriteLine("N"); //Clear buffer.
//Back.
tw.WriteLine("B10,50,0,3,3,5,100,Y,\"" + screenerId + "\""); //Barcode.
tw.WriteLine("A10,0,0,5,1,1,N,\"" + screenerId + "\""); //Screener ID.
//Spine.
tw.WriteLine("A10,200,0,4,1,1,N,\"(S) " + studioId.Value + " " + studioName + "\""); //Studio name.
tw.WriteLine("A10,225,0,4,1,1,N,\"(L) " + licensor.Id + " " + licensor.Name + "\""); //Licensor name.
//Front.
if (title.Length > 35)
tw.WriteLine("A300,100,0,3,1,2,N,\"" + screenerId + " " + title.Substring(0, 42) + "\""); //Screener ID and title.
else
tw.WriteLine("A300,100,0,3,1,2,N,\"" + screenerId + " " + title + "\""); //Screener ID and title.
tw.WriteLine("P1"); //Print label.
tw.Flush();
tw.Close();
}
result = true;
}
catch (Exception e)
{
Logging.Log(e, "Screeners", "Barcode.PrintBarcode");
mClientPresentation.ShowError(e.Message +"\n" + e.StackTrace);
}
finally
{
CloseProxy();
}
return result;
}
public bool PrintToPrinter()
{
return PrintToPrinter(mFileName);
}
public bool PrintToPrinter(string fileName)
{
bool result = false;
if (String.IsNullOrEmpty(fileName))
return false;
mFileName = fileName;
string path = Assembly.GetExecutingAssembly().Location;
if (!path.EndsWith("\\"))
path += "\\";
path += "email\\";
string file = path + "tmp.bat";
try
{
using (TextWriter w = File.CreateText(file))
{
w.WriteLine("copy " + mFileName + " prn");
w.Close();
}
using (Process p = Process.Start(file))
{
while (!p.HasExited)
{
Thread.Sleep(100);
}
}
result = true;
}
catch (Exception e)
{
Logging.Log(e, "Screeners", "Barcode.PrintToPrinter");
mClientPresentation.ShowError(e.Message +"\n" + e.StackTrace);
}
return result;
}
#endregion
#region Private Methods
private void CloseProxy()
{
if (mProxy != null && mProxy.State != CommunicationState.Closed && mProxy.State != CommunicationState.Faulted)
{
Thread.Sleep(30);
mProxy.Close();
}
mProxy = null;
}
private void CreateComponent()
{
Logging.ConnectionString = Settings.ConnectionString;
mClientPresentation = new ClientPresentation();
}
private void Dispose(bool disposing)
{
if(disposing)
{
if(!mIsDisposed)
{
CloseProxy();
mClientPresentation = null;
mIsDisposed = true;
}
}
}
private void OpenProxy()
{
if (mProxy == null || mProxy.State == CommunicationState.Closed || mProxy.State == CommunicationState.Faulted)
{
mProxy = new ScreenerProxy(Settings.Endpoints["Screener"]);
mProxy.Open();
mProxy.CreateScreenerMethods(Settings.ConnectionString, Settings.UserName, 0);
}
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Leaves : Block
{
public override string Name
{
get
{
return "Leaves";
}
}
public override int BlockID
{
get
{
return 6;
}
}
public override bool IsStackable
{
get
{
return true;
}
}
public override Face FrontFaceUV
{
get
{
return Face.GetFromIndex(4, 3, new Color(102f / 255f, 168f / 255f, 88f / 255f));
}
}
public override Face BackFaceUV
{
get
{
return Face.GetFromIndex(4, 3, new Color(102f / 255f, 168f / 255f, 88f / 255f));
}
}
public override Face TopFaceUV
{
get
{
return Face.GetFromIndex(4, 3, new Color(102f / 255f, 168f / 255f, 88f / 255f));
}
}
public override Face BottomFaceUV
{
get
{
return Face.GetFromIndex(4, 3, new Color(102f / 255f, 168f / 255f, 88f / 255f));
}
}
public override Face LeftFaceUV
{
get
{
return Face.GetFromIndex(4, 3, new Color(102f / 255f, 168f / 255f, 88f / 255f));
}
}
public override Face RightFaceUV
{
get
{
return Face.GetFromIndex(4, 3, new Color(102f / 255f, 168f / 255f, 88f / 255f));
}
}
}
|
using System;
namespace SOLIDPrinciples.CouplingProblem.Example02.Good
{
public class NFDao
{
public void Persiste(NotaFiscal nf)
{
//throw new NotImplementedException();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Threading;
using System.Collections;
using System.Xml;
using DevExpress.XtraEditors;
using IRAP.Global;
using IRAP.Client.User;
using IRAP.Client.SubSystem;
using IRAP.Entities.MES;
using IRAP.Entity.MES;
using IRAP.WCF.Client.Method;
using System.IO;
namespace IRAP.Client.GUI.MESPDC
{
public partial class frmProductPackage : IRAP.Client.Global.GUI.frmCustomFuncBase
{
private string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
private string caption = "";
//包装箱对应内存表
private DataTable dtBox = null;
private DataTable dtBoxLayer = null;
private DataTable dtCarton = null;
private DataTable dtCartonLayer = null;
private DataTable dtPallet = null;
private DataTable dtPalletLayer = null;
private List<DataTable> palletUnitTables = null;
/// <summary>
/// 包装规格下拉列表对应内存表
/// </summary>
private DataTable dtPackageTypes = null;
private PackageType objPackageType = null;
private List<PackageType> packageTypeList = new List<PackageType>();
private int allBoxNum = 0;
private int allNumCartonsInPallet = 0;
private long transactNo = 0;
private TextEdit ft;
private string OutputStr = "";
private static string attributeFileName = string.Format("{0}OutputStr.xml",
AppDomain.CurrentDomain.BaseDirectory);
public frmProductPackage()
{
InitializeComponent();
if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en")
caption = "System information";
else
caption = "系统信息";
}
private void Options_OptionChanged(object sender, EventArgs e)
{
GetKanban_PackageTypes();
}
#region 自定义函数
private void EditFocused(object sender, EventArgs e)
{
ft = sender as TextEdit;
}
/// <summary>
/// 初始化 GridView
/// </summary>
private void InitGridView()
{
dgvBoxLayer.AutoGenerateColumns = false;
dgvBox.AutoGenerateColumns = true;
dgvCarton.AutoGenerateColumns = true;
dgvCartonLayer.AutoGenerateColumns = false;
dgvPalletLayer.AutoGenerateColumns = false;
dgvPallet.AutoGenerateColumns = true;
}
/// <summary>
/// 初始化点击包装开始按钮时相应控件的状态
/// </summary>
/// <param name="btnPackageStartEnable"></param>
private void InitPackageStart(bool btnPackageStartEnable)
{
edtProductSN.Text = "";
edtBoxSN.Text = "";
edtCartonSN.Text = "";
edtPalletLayerSN.Text = "";
edtProductSN.Properties.ReadOnly = btnPackageStartEnable;
edtBoxSN.Properties.ReadOnly = true;
edtCartonSN.Properties.ReadOnly = true;
edtPalletLayerSN.Properties.ReadOnly = true;
dgvBox.DataSource = null;
dgvBoxLayer.DataSource = null;
dgvCarton.DataSource = null;
dgvCartonLayer.DataSource = null;
dgvPallet.DataSource = null;
dgvPalletLayer.DataSource = null;
btnRePrint.Enabled = false;
btnPackageStart.Enabled = btnPackageStartEnable;
btnPackageFinish.Enabled = !btnPackageStartEnable;
chkAllowRePrint.Checked = false;
chkStorePackage.Checked = !btnPackageStartEnable;
this.lpPackage.Enabled = btnPackageStartEnable;
Options.btnSwitch.Enabled = btnPackageStartEnable;
}
/// <summary>
/// 批量更新包装信息内存表
/// </summary>
private void BatchUpdateMemTable(
int palletUnitIndex,
string fileName,
string fileValue)
{
for (int r = 0; r < allBoxNum; r++)
{
palletUnitTables[palletUnitIndex].Rows[r][fileName] = fileValue;
}
}
/// <summary>
/// 初始化包装
/// </summary>
private void InitPackageLocation()
{
try
{
allNumCartonsInPallet =
objPackageType.NumLayersOfPallet *
objPackageType.NumCartonsPerLayerOfPallet;
if (objPackageType.T117LabelID_Pallet == 0 ||
objPackageType.NumLayersOfPallet == 0)
{
// 默认为1,虽然实际情况可能存在不需要托,但是为了方便界面处理,所以
// 最小值设定为1。但是托层必须隐藏,处理页面操作时要注意判断下
// T117LabelID_Pallet 的值,以做相应的处理 。
objPackageType.NumLayersOfPallet = 1;
objPackageType.NumCartonsPerLayerOfPallet = 1;
allNumCartonsInPallet = 1;
}
allBoxNum =
objPackageType.NumLayersOfCarton *
objPackageType.NumBoxPerColOfCarton *
objPackageType.NumBoxPerRowOfCarton *
objPackageType.NumLayersOfBox *
objPackageType.QtyPerColOfBox *
objPackageType.QtyPerRowOfBox;
palletUnitTables = new List<DataTable>();
for (int i = 0; i < allNumCartonsInPallet; i++)
{
DataTable dt = CreatePackageInfoMemberTable();
palletUnitTables.Add(dt);
}
//获取未完成包装信息
string palletSN = "";
UncompletedPackage uncompletedPackage = GetUncompletedPackage();
//有未完成箱包装
if (uncompletedPackage != null)
{
// 判断未完成包装信息中的包装数量是否小于实际的包装数量,如不是则报错
if (allBoxNum < uncompletedPackage.NumQtyInCarton)
{
IRAPMessageBox.Instance.ShowErrorMessage(
string.Format(
"箱内已包装数量大于当前包装规格的包装量,请立即通知" +
"相关维护人员予以解决!\n" +
"附:\n内部交易号:[{0}]\n箱内已包装数量:[{1}]",
uncompletedPackage.TransactNo,
uncompletedPackage.NumQtyInCarton));
InitPackageStart(true);
return;
}
transactNo = uncompletedPackage.TransactNo;
if (transactNo == 0 &&
string.IsNullOrEmpty(uncompletedPackage.PalletSerialNumber))
{
if (objPackageType.T117LabelID_Pallet > 0)
{
//申请托序列号
palletSN = GetNextPackageSN("PLT");
}
}
else
{
List<FactPackaging> packageList =
GetFactList_Packaging(
uncompletedPackage.TransactNo,
Options.SelectProduct.T102LeafID);
if (packageList != null)
{
int maxPalletUnitIndex = 0;
int maxOrdinal = 0;
foreach (FactPackaging fact in packageList)
{
long factNo = fact.FactID;
int layerIdxOfPallet = fact.LayerIdxOfPallet; //铲板第几层
int cartonIdxOfLayer = fact.CartonIdxOfLayer; //当前层第几箱
int layerIdxOfCarton = fact.LayerIdxOfCarton; //箱内第几层内包装(盒)
int rowIdxOfCarton = fact.RowIdxOfCarton; //箱内第几排内包装(盒)
int colIdxOfCarton = fact.ColIdxOfCarton; //箱内第几列内包装(盒)
int layerIdxOfBox = fact.LayerIdxOfBox; //盒内第几层产品
int rowIdxOfBox = fact.RowIdxOfBox; //盒内第几排产品
int colIdxOfBox = fact.ColIdxOfBox; //盒内第几列产品
string wipCode = fact.WIPCode; //产品主标识代码
string altWIPCode = fact.AltWIPCode; //产品副标识代码
string serialNumber = fact.SerialNumber; //产品序列号
string boxSerialNumbe = fact.BoxSerialNumber; //内包装序列号
string cartonSerialNumber = fact.CartonSerialNumber; //箱包装序列号
string layerSerialNumber = fact.LayerSerialNumber; //包装托层序列号
string palletSerialNumber = fact.PalletSerialNumber; //铲板标签序列号
int palletUnitIndex = ((layerIdxOfPallet - 1) * objPackageType.NumLayersOfPallet + cartonIdxOfLayer - 1);
int ordinal =
GetBoxIndex(
layerIdxOfCarton,
rowIdxOfCarton,
colIdxOfCarton,
layerIdxOfBox,
rowIdxOfBox,
colIdxOfBox);
palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["FactNo"] = factNo;
palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["ProductSN"] = serialNumber == string.Empty ? wipCode == string.Empty ? altWIPCode : wipCode : serialNumber;
palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["BoxPackageSN"] = boxSerialNumbe;
palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["CartonPackageSN"] = cartonSerialNumber;
palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["PalletLayerSN"] = layerSerialNumber;
palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["PalletPackageSN"] = palletSerialNumber;
palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["Do"] = 2;
if (ordinal > maxOrdinal)
{
maxOrdinal = ordinal;
maxPalletUnitIndex = palletUnitIndex;
}
}
if (palletUnitTables[maxPalletUnitIndex].Rows.Count > maxOrdinal)
{
palletUnitTables[maxPalletUnitIndex].Rows[maxOrdinal]["Do"] = 1;
int boxNumOfInCarton = objPackageType.QtyPerColOfBox * objPackageType.QtyPerRowOfBox;
if (maxOrdinal % boxNumOfInCarton != 0)
{
//更新内存表
for (int r = maxOrdinal; r < maxOrdinal + boxNumOfInCarton - (maxOrdinal % boxNumOfInCarton); r++)
{
palletUnitTables[maxPalletUnitIndex].Rows[r]["BoxPackageSN"] = palletUnitTables[maxPalletUnitIndex].Rows[r - 1]["BoxPackageSN"];
}
}
//更新内存表
BatchUpdateMemTable(maxPalletUnitIndex, "TransactNo", transactNo.ToString());
edtCartonSN.Text = palletUnitTables[maxPalletUnitIndex].Rows[maxOrdinal]["CartonPackageSN"].ToString();
BatchUpdateMemTable(maxPalletUnitIndex, "CartonPackageSN", packageList[0].CartonSerialNumber); //此处不完善
}
}
}
}
if (objPackageType.T117LabelID_Pallet > 0)
{
for (int i = 0; i < allNumCartonsInPallet; i++)
{
BatchUpdateMemTable(i, "PalletPackageSN", palletSN);
int layer = i / objPackageType.NumLayersOfPallet + 1;
string palletLayerSN = palletSN + layer.ToString();
BatchUpdateMemTable(i, "PalletLayerSN", palletSN);
}
}
//初始显示的标签
edtBoxSN.Text = palletUnitTables[0].Rows[0]["BoxPackageSN"].ToString();
edtCartonSN.Text = palletUnitTables[0].Rows[0]["CartonPackageSN"].ToString();
edtPalletLayerSN.Text = palletUnitTables[0].Rows[0]["PalletLayerSN"].ToString();
//注意顺序
if (transactNo == 0)
{
//当没有未完成包装时
GenerateBox(0, 1, 1, 1, 1);
GenerateBoxLayer(0, 1, 1, 1, 1);
GenerateCarton(0, 1, 1, 1);
GenerateCartonLayer(0);
GeneratePallet(1);
GeneratePalletLayer();
}
else
{
//当有未完成包装时
InitHadFinishPackage();
}
}
catch (Exception error)
{
IRAPMessageBox.Instance.Show(error.Message, "", MessageBoxIcon.Error);
WriteLog.Instance.Write(
$"{error.Message}\n{error.StackTrace}",
$"{className}.{MethodBase.GetCurrentMethod().Name}");
}
}
/// <summary>
/// 初始化未完成包装
/// </summary>
private void InitHadFinishPackage()
{
int palletUnitIndex = -1;
for (int i = 0; i < allNumCartonsInPallet; i++)
{
if (palletUnitTables[i].Rows[0]["Do"].ToString() != "2" &&
palletUnitTables[i].Rows[allBoxNum - 1]["Do"].ToString() != "2")
{
palletUnitIndex = i;
break;
}
if (palletUnitTables[i].Rows[0]["Do"].ToString() == "2" &&
palletUnitTables[i].Rows[allBoxNum - 1]["Do"].ToString() != "2")
{
palletUnitIndex = i;
break;
}
}
if (palletUnitIndex == -1) return;
int currentPalletLayer = (palletUnitIndex / objPackageType.NumCartonsPerLayerOfPallet) + 1;
int currentPalletCol = palletUnitIndex + 1 - (currentPalletLayer - 1) * objPackageType.NumCartonsPerLayerOfPallet;
for (int i = 0; i < allBoxNum; i++)
{
string doStatus = palletUnitTables[palletUnitIndex].Rows[i]["Do"].ToString();
if (doStatus == "1")
{
int ordinal = i + 1;
int cartonLayer, cartonRow, cartonCol, boxLayer, boxRow, boxCol;
SetBoxOrdinal(
ordinal,
out cartonLayer,
out cartonRow,
out cartonCol,
out boxLayer,
out boxRow,
out boxCol);
GenerateBox(palletUnitIndex, cartonLayer, cartonRow, cartonCol, boxLayer);
GenerateBoxLayer(palletUnitIndex, cartonLayer, cartonRow, cartonCol, boxLayer);
GenerateCarton(palletUnitIndex, cartonLayer, cartonRow, cartonCol);
GenerateCartonLayer(palletUnitIndex);
break;
}
}
GeneratePallet(currentPalletCol);
GeneratePalletLayer();
}
/// <summary>
/// 获取大包装和小包装的序号对应的坐标
/// </summary>
private void SetBoxOrdinal(
int ordinal,
out int cartonLayer,
out int cartonRow,
out int cartonCol,
out int boxLayer,
out int boxRow,
out int boxCol)
{
int smallTemp;
int FPalletLayers = objPackageType.NumLayersOfPallet;
int FPalletCols = objPackageType.NumCartonsPerLayerOfPallet;
int FLargeLayers = objPackageType.NumLayersOfCarton;
int FLargeRows = objPackageType.NumBoxPerRowOfCarton;
int FLargeCols = objPackageType.NumBoxPerColOfCarton;
int FSmallLayers = objPackageType.NumLayersOfBox;
int FSmallRows = objPackageType.QtyPerRowOfBox;
int FSmallCols = objPackageType.QtyPerColOfBox;
//大包装
int totalSLBoxNum =
FLargeLayers *
FLargeRows *
FLargeCols *
FSmallLayers *
FSmallRows *
FSmallCols;
cartonLayer =
1 +
(ordinal - 1) /
(totalSLBoxNum / FLargeLayers);
cartonRow = ordinal - (cartonLayer - 1) * totalSLBoxNum / FLargeLayers;
cartonRow = (cartonRow - 1) / (FLargeCols * FSmallLayers * FSmallRows * FSmallCols) + 1;
cartonCol =
ordinal -
(cartonLayer - 1) *
totalSLBoxNum /
FLargeLayers -
(cartonRow - 1) *
FLargeCols *
FSmallLayers *
FSmallRows *
FSmallCols;
cartonCol = (cartonCol - 1) / (FSmallLayers * FSmallRows * FSmallCols) + 1;
//小包装
smallTemp = (ordinal - 1) % (FSmallLayers * FSmallRows * FSmallCols) + 1;
boxLayer = 1 + (smallTemp - 1) / FSmallRows / FSmallCols;
boxRow = smallTemp - (boxLayer - 1) * FSmallRows * FSmallCols;
boxRow = (boxRow - 1) / FSmallCols + 1;
boxCol = (ordinal - 1) % FSmallCols + 1;
}
/// <summary>
/// 获取大包装和小包装和托的序号对应的坐标
/// </summary>
private void SetBoxOrdinal(
int ordinal,
out int palletLayer,
out int palletRow,
out int palletCol,
out int cartonLayer,
out int cartonRow,
out int cartonCol,
out int boxLayer,
out int boxRow,
out int boxCol)
{
int smallTemp, totalBoxNum;
int fPalletLayers = objPackageType.NumLayersOfPallet;
int fPalletRows = 1;
int fPalletCols = objPackageType.NumCartonsPerLayerOfPallet;
int fLargeLayers = objPackageType.NumLayersOfCarton;
int fLargeRows = objPackageType.NumBoxPerRowOfCarton;
int fLargeCols = objPackageType.NumBoxPerColOfCarton;
int fSmallLayers = objPackageType.NumLayersOfBox;
int fSmallRows = objPackageType.QtyPerRowOfBox;
int fSmallCols = objPackageType.QtyPerColOfBox;
//托
totalBoxNum =
fPalletLayers *
fPalletRows *
fPalletCols *
fLargeLayers *
fLargeRows *
fLargeCols *
fSmallLayers *
fSmallRows *
fSmallCols;
palletLayer = 1 + (ordinal - 1) / (totalBoxNum / fPalletLayers);
palletRow = 1; //托行数量固定为1
palletCol = ordinal - (palletLayer - 1) * totalBoxNum / fLargeLayers;
palletCol =
(palletCol - 1) /
(fLargeLayers * fLargeRows * fLargeCols * fSmallLayers * fSmallRows * fSmallCols) +
1;
//大包装
int totalSLBoxNum = fLargeLayers * fLargeRows * fLargeCols * fSmallLayers *
fSmallRows * fSmallCols;
cartonLayer = 1 + (ordinal - 1) / (totalSLBoxNum / fLargeLayers);
cartonRow = ordinal - (cartonLayer - 1) * totalSLBoxNum / fLargeLayers;
cartonRow = (cartonRow - 1) / (fLargeCols * fSmallLayers * fSmallRows * fSmallCols) + 1;
cartonCol =
ordinal -
(cartonLayer - 1) *
totalSLBoxNum /
fLargeLayers -
(cartonRow - 1) *
fLargeCols *
fSmallLayers *
fSmallRows *
fSmallCols;
cartonCol = (cartonCol - 1) / (fSmallLayers * fSmallRows * fSmallCols) + 1;
//小包装
smallTemp = (ordinal - 1) % (fSmallLayers * fSmallRows * fSmallCols) + 1;
boxLayer = 1 + (smallTemp - 1) / fSmallRows / fSmallCols;
boxRow = smallTemp - (boxLayer - 1) * fSmallRows * fSmallCols;
boxRow = (boxRow - 1) / fSmallCols + 1;
boxCol = (ordinal - 1) % fSmallCols + 1;
}
/// <summary>
/// 通过坐标获取对应的大包装和小包装的序号
/// </summary>
private int GetBoxIndex(
int palletLayer,
int palletRow,
int palletCol,
int cartonLayer,
int cartonRow,
int cartonCol,
int boxLayer,
int boxRow,
int boxCol)
{
int ordinal =
(palletLayer - 1) *
(1 * objPackageType.NumCartonsPerLayerOfPallet) *
(objPackageType.NumLayersOfCarton *
objPackageType.NumBoxPerRowOfCarton *
objPackageType.NumBoxPerColOfCarton) *
(objPackageType.NumLayersOfBox *
objPackageType.QtyPerRowOfBox *
objPackageType.QtyPerColOfBox) +
(palletRow - 1) *
objPackageType.NumCartonsPerLayerOfPallet *
(objPackageType.NumLayersOfCarton *
objPackageType.NumBoxPerRowOfCarton *
objPackageType.NumBoxPerColOfCarton) *
(objPackageType.NumLayersOfBox *
objPackageType.QtyPerRowOfBox *
objPackageType.QtyPerColOfBox) +
(palletCol - 1) *
(objPackageType.NumLayersOfCarton *
objPackageType.NumBoxPerRowOfCarton *
objPackageType.NumBoxPerColOfCarton) *
(objPackageType.NumLayersOfBox *
objPackageType.QtyPerRowOfBox *
objPackageType.QtyPerColOfBox) +
(cartonLayer - 1) *
(objPackageType.NumBoxPerRowOfCarton *
objPackageType.NumBoxPerColOfCarton) *
(objPackageType.NumLayersOfBox *
objPackageType.QtyPerRowOfBox *
objPackageType.QtyPerColOfBox) +
(cartonRow - 1) *
objPackageType.NumBoxPerColOfCarton *
(objPackageType.NumLayersOfBox *
objPackageType.QtyPerColOfBox *
objPackageType.QtyPerRowOfBox) +
(cartonCol - 1) *
(objPackageType.NumLayersOfBox *
objPackageType.QtyPerRowOfBox *
objPackageType.QtyPerColOfBox) +
(boxLayer - 1) *
(objPackageType.QtyPerRowOfBox *
objPackageType.QtyPerColOfBox) +
(boxRow - 1) *
objPackageType.QtyPerColOfBox +
boxCol;
return ordinal;
}
/// <summary>
/// 通过坐标获取对应的大包装和小包装和托的序号
/// </summary>
private int GetBoxIndex(
int cartonLayer,
int cartonRow,
int cartonCol,
int boxLayer,
int boxRow,
int boxCol)
{
int ordinal =
(cartonLayer - 1) *
(objPackageType.NumBoxPerRowOfCarton * objPackageType.NumBoxPerColOfCarton) *
(objPackageType.NumLayersOfBox * objPackageType.QtyPerRowOfBox * objPackageType.QtyPerColOfBox) +
(cartonRow - 1) *
objPackageType.NumBoxPerColOfCarton * (objPackageType.NumLayersOfBox * objPackageType.QtyPerColOfBox * objPackageType.QtyPerRowOfBox) +
(cartonCol - 1) *
(objPackageType.NumLayersOfBox * objPackageType.QtyPerRowOfBox * objPackageType.QtyPerColOfBox) +
(boxLayer - 1) *
(objPackageType.QtyPerRowOfBox * objPackageType.QtyPerColOfBox) +
(boxRow - 1) *
objPackageType.QtyPerColOfBox +
boxCol;
return ordinal;
}
/// <summary>
/// 创建包装箱内存表
/// </summary>
private DataTable CreatePackageInfoMemberTable()
{
DataTable dtTempPackageInfo = new DataTable();
dtTempPackageInfo.Columns.Add("Ordinal", typeof(int));
dtTempPackageInfo.Columns.Add("TransactNo", typeof(long));
dtTempPackageInfo.Columns.Add("FactNo", typeof(long));
dtTempPackageInfo.Columns.Add("ProductSN", typeof(string)); // 每个小Box对应的产品标签
dtTempPackageInfo.Columns.Add("BoxPackageSN", typeof(string)); // 小包装箱标签
dtTempPackageInfo.Columns.Add("CartonPackageSN", typeof(string)); // 大包装箱标签
dtTempPackageInfo.Columns.Add("PalletLayerSN", typeof(string)); // 托每层标签
dtTempPackageInfo.Columns.Add("PalletPackageSN", typeof(string)); // 托包装标签
dtTempPackageInfo.Columns.Add("Do", typeof(int)); // 小Box状态:0-未包装;1-正在包装;2-已包装
dtTempPackageInfo.Columns.Add("CartonLayer", typeof(int));
dtTempPackageInfo.Columns.Add("CartonRow", typeof(int));
dtTempPackageInfo.Columns.Add("CartonCol", typeof(int));
dtTempPackageInfo.Columns.Add("BoxLayer", typeof(int));
dtTempPackageInfo.Columns.Add("BoxRow", typeof(int));
dtTempPackageInfo.Columns.Add("BoxCol", typeof(int));
int cartonLayerSet, cartonRowSet, cartonColSet,
boxLayerSet, boxRowSet, boxColSet;
for (int i = 0; i < allBoxNum; i++)
{
int ordinal = i + 1;
SetBoxOrdinal(ordinal,
out cartonLayerSet, out cartonRowSet, out cartonColSet,
out boxLayerSet, out boxRowSet, out boxColSet);
DataRow dr = dtTempPackageInfo.NewRow();
dr["Ordinal"] = i + 1;
dr["TransactNo"] = 0;
dr["FactNo"] = 0;
dr["ProductSN"] = "";
dr["BoxPackageSN"] = "";
dr["CartonPackageSN"] = "";
dr["PalletLayerSN"] = "";
dr["PalletPackageSN"] = "";
dr["Do"] = 0;
dr["CartonLayer"] = cartonLayerSet;
dr["CartonRow"] = cartonRowSet;
dr["CartonCol"] = cartonColSet;
dr["BoxLayer"] = boxLayerSet;
dr["BoxRow"] = boxRowSet;
dr["BoxCol"] = boxColSet;
dtTempPackageInfo.Rows.Add(dr);
}
dtTempPackageInfo.Rows[0]["Do"] = 1;
return dtTempPackageInfo;
}
/// <summary>
/// 生成托层
/// </summary>
private void GeneratePalletLayer()
{
try
{
dtPalletLayer = new DataTable();
dtPalletLayer.Columns.Add("PalletLayer", typeof(string));
int layerCount = objPackageType.NumLayersOfPallet;
for (int i = 0; i < layerCount; i++)
{
DataRow dr = dtPalletLayer.NewRow();
dr[0] = string.Format("{0}L", i + 1);
dtPalletLayer.Rows.Add(dr);
}
dgvPalletLayer.RowTemplate.Height = dgvPalletLayer.Height / layerCount;
dgvPalletLayer.DataSource = dtPalletLayer;
for (int i = 0; i < layerCount; i++)
{
int palletLayer = i + 1;
Color color = GetPalletLayerColor(palletLayer);
dgvPalletLayer.Rows[i].Cells[0].Style.BackColor = color;
dgvPalletLayer.Rows[i].Cells[0].Style.SelectionBackColor = color;
if (color == Color.Blue) dgvPalletLayer.Rows[i].Cells[0].Selected = true;
}
dgvPalletLayer.Rows[layerCount - 1].Height = dgvPalletLayer.Height / layerCount - 3;
}
catch (Exception error)
{
XtraMessageBox.Show(
string.Format(
"生成托层时发生异常:{0}",
error.Message),
caption,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
/// <summary>
/// 生成托列
/// </summary>
private void GeneratePallet(int palletLayer)
{
try
{
int colCount = objPackageType.NumCartonsPerLayerOfPallet;
dtPallet = new DataTable();
for (int i = 0; i < colCount; i++)
{
dtPallet.Columns.Add("Pallet" + i.ToString(), typeof(string));
}
DataRow dr = dtPallet.NewRow();
for (int i = 0; i < colCount; i++)
{
dr[i] = (i + 1).ToString();
}
dtPallet.Rows.Add(dr);
int rowsCount = 1;
dgvPallet.RowTemplate.Height = dgvPallet.Height / rowsCount;
dgvPallet.DataSource = dtPallet;
for (int j = 0; j < dgvPallet.Columns.Count; j++)
{
int palletCol = j + 1;
Color color = GetPalletColor(palletLayer, palletCol);
dgvPallet.Rows[0].Cells[j].Style.BackColor = color;
dgvPallet.Rows[0].Cells[j].Style.SelectionBackColor = color;
if (color == Color.Blue) dgvPallet.Rows[0].Cells[j].Selected = true;
}
dgvPallet.Rows[rowsCount - 1].Height = dgvPalletLayer.Height / rowsCount - 3;
}
catch (Exception error)
{
XtraMessageBox.Show(
string.Format(
"生成托列时发生异常:{0}",
error.Message),
caption,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
/// <summary>
/// 生成大包装层
/// </summary>
private void GenerateCartonLayer(int palletUnitIndex)
{
try
{
dtCartonLayer = new DataTable();
dtCartonLayer.Columns.Add("CartonLayer", typeof(string));
int layerCount = objPackageType.NumLayersOfCarton;
for (int i = 0; i < layerCount; i++)
{
DataRow dr = dtCartonLayer.NewRow();
dr[0] = string.Format("{0}L", i + 1);
dtCartonLayer.Rows.Add(dr);
}
dgvCartonLayer.RowTemplate.Height = dgvCartonLayer.Height / layerCount;
dgvCartonLayer.DataSource = dtCartonLayer;
for (int i = 0; i < layerCount; i++)
{
int cartonLayer = i + 1;
Color color = GetCartonLayerColor(palletUnitIndex, cartonLayer, 1, 1, 1, 1, 1);
dgvCartonLayer.Rows[i].Cells[0].Style.BackColor = color;
dgvCartonLayer.Rows[i].Cells[0].Style.SelectionBackColor = color;
if (color == Color.Blue) dgvCartonLayer.Rows[i].Cells[0].Selected = true;
}
dgvCartonLayer.Rows[layerCount - 1].Height = dgvCartonLayer.Height / layerCount - 3;
//dgvCartonLayer.ClearSelection();
}
catch (Exception error)
{
XtraMessageBox.Show(
string.Format(
"生成大包装层发生异常:{0}",
error.Message),
caption,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
/// <summary>
/// 生成大包装行列
/// </summary>
private void GenerateCarton(
int palletUnitIndex,
int cartonLayer,
int focusCartonRow,
int focusCartonCol)
{
string strProcedureName =
$"{className}.{MethodBase.GetCurrentMethod().Name}";
try
{
dtCarton = new DataTable();
int colCount = objPackageType.NumBoxPerColOfCarton;
for (int i = 0; i < colCount; i++)
{
dtCarton.Columns.Add("Carton" + i.ToString(), typeof(string));
}
int rowCount = objPackageType.NumBoxPerRowOfCarton;
for (int i = 0; i < rowCount; i++)
{
DataRow dr = dtCarton.NewRow();
for (int j = 0; j < colCount; j++)
{
dr[j] = (i * colCount + j + 1).ToString();
}
dtCarton.Rows.Add(dr);
}
dgvCarton.RowTemplate.Height = dgvCarton.Height / rowCount;
dgvCarton.DataSource = dtCarton;
dgvCarton.Rows[rowCount - 1].Height = dgvCarton.Height / rowCount - 3;
for (int i = 0; i < dgvCarton.Rows.Count; i++)
{
int cartonRow = i + 1;
for (int j = 0; j < dgvCarton.ColumnCount; j++)
{
int cartonCol = j + 1;
Color color = GetCartonColor(palletUnitIndex, cartonLayer, cartonRow, cartonCol, 1, 1, 1);
dgvCarton.Rows[i].Cells[j].Style.BackColor = color;
dgvCarton.Rows[i].Cells[j].Style.SelectionBackColor = color;
}
}
dgvCarton.Rows[focusCartonRow - 1].Cells[focusCartonCol - 1].Selected = true;
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
XtraMessageBox.Show(
string.Format(
"生成大包装行列发生异常:{0}",
error.Message),
caption,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
/// <summary>
/// 生产小包装层
/// </summary>
private void GenerateBoxLayer(
int palletUnitIndex,
int cartonLayer,
int cartonRow,
int cartonCol,
int focusBoxLayer)
{
string strProcedureName =
$"{className}.{MethodBase.GetCurrentMethod().Name}";
try
{
dtBoxLayer = new DataTable();
dtBoxLayer.Columns.Add("BoxLayer", typeof(string));
//设置每个单元格显示的内容
int layerCount = objPackageType.NumLayersOfBox;
for (int i = 0; i < layerCount; i++)
{
DataRow dr = dtBoxLayer.NewRow();
dr[0] = string.Format("{0}L", i + 1);
dtBoxLayer.Rows.Add(dr);
}
//设置单元格高度,使单元格总高度等于表格的高度
dgvBoxLayer.RowTemplate.Height = dgvBoxLayer.Height / layerCount;
dgvBoxLayer.DataSource = dtBoxLayer;
//设置每个单元格显示的背景颜色
for (int i = 0; i < dgvBoxLayer.Rows.Count; i++)
{
int boxLayer = i + 1;
Color color = GetBoxLayerColor(palletUnitIndex,
cartonLayer, cartonRow, cartonCol, boxLayer, 1, 1);
dgvBoxLayer.Rows[i].Cells[0].Style.BackColor = color;
dgvBoxLayer.Rows[i].Cells[0].Style.SelectionBackColor = color;
}
//调整最后一行的高度
dgvBoxLayer.Rows[layerCount - 1].Height = dgvBoxLayer.Height / layerCount - 3;
//
dgvBoxLayer.Rows[focusBoxLayer - 1].Cells[0].Selected = true;
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
XtraMessageBox.Show(
string.Format(
"生成小包装层时发生异常:{0}",
error.Message),
caption,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
/// <summary>
/// 生成小包装行列
/// </summary>
/// <param name="cartonLayer">大包装层坐标</param>
/// <param name="cartonRow">大包装行坐标</param>
/// <param name="cartonCol">大包装列坐标</param>
/// <param name="boxLayer">小包装层坐标</param>
private void GenerateBox(
int palletUnitIndex,
int cartonLayer,
int cartonRow,
int cartonCol,
int boxLayer)
{
try
{
dtBox = new DataTable();
int colCount = objPackageType.QtyPerColOfBox;
for (int i = 0; i < colCount; i++)
{
dtBox.Columns.Add("Box" + i.ToString(), typeof(string));
}
int rowCount = objPackageType.QtyPerRowOfBox;
int ordinal = 0;
//设置每个单元格显示的序号
for (int i = 0; i < rowCount; i++)
{
DataRow dr = dtBox.NewRow();
for (int j = 0; j < colCount; j++)
{
int boxRow = i + 1;
int boxCol = j + 1;
ordinal =
GetBoxIndex(
cartonLayer,
cartonRow,
cartonCol,
boxLayer,
boxRow,
boxCol);
dr[j] = ordinal;
}
dtBox.Rows.Add(dr);
}
//设置单元格高度,使之正好能填满整个表格
dgvBox.RowTemplate.Height = dgvBoxLayer.Height / rowCount;
dgvBox.DataSource = dtBox;
dgvBox.Rows[rowCount - 1].Height = dgvBoxLayer.Height / rowCount - 3;
if (palletUnitTables[palletUnitIndex] != null)
{
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < colCount; j++)
{
ordinal = int.Parse(dgvBox.Rows[i].Cells[j].Value.ToString());
string doStatus = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["Do"].ToString();
if (doStatus == "0")
{
dgvBox.Rows[i].Cells[j].Style.BackColor = Color.White;
dgvBox.Rows[i].Cells[j].Style.SelectionBackColor = Color.White;
}
if (doStatus == "1")
{
dgvBox.Rows[i].Cells[j].Style.BackColor = Color.Blue;
dgvBox.Rows[i].Cells[j].Style.SelectionBackColor = Color.Blue;
dgvBox.Rows[i].Cells[j].Selected = true;
break;
}
if (doStatus == "2")
{
dgvBox.Rows[i].Cells[j].Style.BackColor = Color.Green;
dgvBox.Rows[i].Cells[j].Style.SelectionBackColor = Color.Green;
}
}
}
}
edtBoxSN.Text = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["BoxPackageSN"].ToString();
edtCartonSN.Text = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["CartonPackageSN"].ToString();
edtPalletLayerSN.Text = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["PalletLayerSN"].ToString();
}
catch (Exception error)
{
XtraMessageBox.Show(
string.Format(
"生成小包装行列发生异常:{0}",
error.Message),
caption,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
/// <summary>
/// 通过坐标获取 Pellet 的颜色
/// </summary>
private Color GetPalletColor(
int palletLayer,
int palletCol)
{
Color color = Color.White;
int maxPalletCol = objPackageType.NumCartonsPerLayerOfPallet;
int tempPalletUnitIndex = ((palletLayer - 1) * maxPalletCol + palletCol) - 1;
int firstDoStatus = 0;
int.TryParse(palletUnitTables[tempPalletUnitIndex].Rows[0]["Do"].ToString(), out firstDoStatus);
int lastDoStatus = 0;
int.TryParse(palletUnitTables[tempPalletUnitIndex].Rows[allBoxNum - 1]["Do"].ToString(), out lastDoStatus);
switch (lastDoStatus)
{
case 0:
{
if (firstDoStatus == 2) color = Color.Blue;
if (firstDoStatus < 2)
{
if (PalletPrepared(maxPalletCol))
{
color = Color.White;
}
else
{
color = Color.Blue;
}
}
}
break;
case 1:
{
color = Color.Blue;
}
break;
case 2:
{
color = Color.Green;
}
break;
default: color = Color.White; break;
}
return color;
}
/// <summary>
/// 获取 PalletLayer 的颜色
/// </summary>
private Color GetPalletLayerColor(int palletLayer)
{
Color color = Color.White;
int maxPalletCol = objPackageType.NumCartonsPerLayerOfPallet;
int maxPalletLayer = objPackageType.NumLayersOfPallet;
int tempPalletFirstUnitIndex = ((palletLayer - 1) * maxPalletCol + 1) - 1;
int tempPalletLastUnitIndex = ((palletLayer - 1) * maxPalletCol + maxPalletCol) - 1;
int firstDoStatus = 0;
int.TryParse(palletUnitTables[tempPalletFirstUnitIndex].Rows[0]["Do"].ToString(), out firstDoStatus);
int lastDoStatus = 0;
int.TryParse(palletUnitTables[tempPalletLastUnitIndex].Rows[allBoxNum - 1]["Do"].ToString(), out lastDoStatus);
switch (lastDoStatus)
{
case 2:
{
color = Color.Green;
}
break;
case 1:
{
if (!PalletLayerPrepared(maxPalletLayer)) color = Color.Blue;
}
break;
case 0:
{
if (firstDoStatus == 0)
{
color = Color.White;
}
else
{
if (!PalletLayerPrepared(maxPalletLayer)) color = Color.Blue;
}
}
break;
default: color = Color.White; break;
}
return color;
}
/// <summary>
/// 获取 BoxLayer 的颜色
/// </summary>
/// <param name="palletUnitIndex"></param>
/// <param name="cartonLayer"></param>
/// <param name="cartonRow"></param>
/// <param name="cartonCol"></param>
/// <param name="boxLayer"></param>
/// <param name="boxRow"></param>
/// <param name="boxCol"></param>
/// <returns></returns>
private Color GetBoxLayerColor(
int palletUnitIndex,
int cartonLayer,
int cartonRow,
int cartonCol,
int boxLayer,
int boxRow,
int boxCol)
{
Color color = Color.White;
int ordinal = 0;
int maxBoxRow = objPackageType.QtyPerRowOfBox;
int maxBoxCol = objPackageType.QtyPerColOfBox;
ordinal = GetBoxIndex(cartonLayer, cartonRow, cartonCol,
boxLayer, maxBoxRow, maxBoxCol);
int doMaxStatus = 0;
int.TryParse(palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["Do"].ToString(), out doMaxStatus);
switch (doMaxStatus)
{
case 0:
{
for (int i = ordinal - maxBoxRow * maxBoxCol + 1; i < ordinal; i++)
{
if (palletUnitTables[palletUnitIndex].Rows[i - 1]["Do"].ToString() == "1")
{
color = Color.Blue;
break;
}
}
}
break;
case 1: color = Color.Blue; break;
case 2: color = Color.Green; break;
default: color = Color.White; break;
}
return color;
}
/// <summary>
/// 获取 Carton 的颜色
/// </summary>
private Color GetCartonColor(
int palletUnitIndex,
int cartonLayer,
int cartonRow,
int cartonCol,
int boxLayer,
int boxRow,
int boxCol)
{
Color color = Color.White;
int ordinal = 0;
int doMaxStatus = 0;
int maxBoxRow = objPackageType.QtyPerRowOfBox;
int maxBoxCol = objPackageType.QtyPerColOfBox;
int maxBoxLayer = objPackageType.NumLayersOfBox;
ordinal =
GetBoxIndex(
cartonLayer,
cartonRow,
cartonCol,
maxBoxLayer,
maxBoxRow,
maxBoxCol);
int.TryParse(palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["Do"].ToString(), out doMaxStatus);
switch (doMaxStatus)
{
case 0:
{
int maxCartonRow = objPackageType.NumBoxPerRowOfCarton;
int maxCartonCol = objPackageType.NumBoxPerColOfCarton;
if (!BoxLayerPrepared(maxBoxLayer)) break;
if (CartonPrepared(maxCartonRow, maxCartonCol)) break;
color = Color.Blue;
}
break;
case 1: color = Color.Blue; break;
case 2: color = Color.Green; break;
default: color = Color.White; break;
}
return color;
}
/// <summary>
/// 获取 CartonLayer 的颜色
/// </summary>
private Color GetCartonLayerColor(
int palletUnitIndex,
int cartonLayer,
int cartonRow,
int cartonCol,
int boxLayer,
int boxRow,
int boxCol)
{
Color color = Color.White;
int ordinal = 0;
int doMaxStatus = 0;
int maxBoxRow = objPackageType.QtyPerRowOfBox;
int maxBoxCol = objPackageType.QtyPerColOfBox;
int maxBoxLayer = objPackageType.NumLayersOfBox;
int maxCartonRow = objPackageType.NumBoxPerRowOfCarton;
int maxCartonCol = objPackageType.NumBoxPerColOfCarton;
ordinal = GetBoxIndex(cartonLayer, maxCartonRow, maxCartonCol,
maxBoxLayer, maxBoxRow, maxBoxCol);
int.TryParse(palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["Do"].ToString(), out doMaxStatus);
switch (doMaxStatus)
{
case 0:
{
int maxCartonLayer = objPackageType.NumLayersOfCarton;
if (CartonLayerPrepared(maxCartonLayer)) break;
if (CartonPrepared(maxCartonRow, maxCartonCol))
color = Color.Blue;
}
break;
case 1: color = Color.Blue; break;
case 2: color = Color.Green; break;
default: color = Color.White; break;
}
return color;
}
private bool PalletLayerPrepared(int palletLayer)
{
bool rlt = false;
for (int i = 0; i < palletLayer; i++)
{
if (dgvPalletLayer.Rows[i].Cells[0].Style.BackColor == Color.Blue)
{
rlt = true;
break;
}
}
return rlt;
}
private bool PalletPrepared(int palletCol)
{
bool rlt = false;
for (int j = 0; j < palletCol; j++)
{
if (dgvPallet.Rows[0].Cells[j].Style.BackColor == Color.Blue)
{
rlt = true;
break;
}
}
return rlt;
}
private bool BoxLayerPrepared(int boxLayer)
{
bool rlt = false;
for (int i = 0; i < boxLayer; i++)
{
if (dgvBoxLayer.Rows[i].Cells[0].Style.BackColor == Color.Blue)
{
rlt = true;
break;
}
}
return rlt;
}
private bool CartonPrepared(int cartonRow, int cartonCol)
{
bool rlt = false;
for (int i = 0; i < cartonRow; i++)
{
for (int j = 0; j < cartonCol; j++)
{
if (dgvCarton.Rows[i].Cells[j].Style.BackColor == Color.Blue)
{
rlt = true;
break;
}
}
if (rlt) break;
}
return rlt;
}
private bool CartonLayerPrepared(int cartonLayer)
{
bool rlt = false;
for (int i = 0; i < cartonLayer; i++)
{
if (dgvCartonLayer.Rows[i].Cells[0].Style.BackColor == Color.Blue)
{
rlt = true;
break;
}
}
return rlt;
}
/// <summary>
/// 获取包装规格列表
/// </summary>
private void GetKanban_PackageTypes()
{
if (Options.SelectStation == null ||
Options.SelectProduct == null)
{
IRAPMessageBox.Instance.ShowErrorMessage(
"选项一或选项二没有配置!",
caption);
return;
}
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
try
{
IRAPMESPKGClient.Instance.ufn_GetKanban_PackageTypes(
IRAPUser.Instance.CommunityID,
Options.SelectProduct.T102LeafID,
Options.SelectStation.T107LeafID,
IRAPUser.Instance.SysLogID,
ref packageTypeList,
out errCode,
out errText);
}
catch (Exception error)
{
errCode = -1;
errText = error.Message;
}
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode == 0)
{
dtPackageTypes = new DataTable();
dtPackageTypes.Columns.Add("id", typeof(int));
dtPackageTypes.Columns.Add("text", typeof(string));
dtPackageTypes.Columns.Add("index", typeof(string));
int index = 0;
foreach (PackageType pkgType in packageTypeList)
{
DataRow dr = dtPackageTypes.NewRow();
dr[0] = pkgType.CorrelationID;
dr[1] = pkgType.SpecDesc;
string sindex = string.Format("{0}-{1}", pkgType.CorrelationID.ToString(), index.ToString());
dr[2] = sindex;
dtPackageTypes.Rows.Add(dr);
index++;
}
lpPackage.Properties.ValueMember = "index"; //editvalue
lpPackage.Properties.DisplayMember = "text"; //text
lpPackage.Properties.NullText = "[请选择包装规格]";
lpPackage.Properties.DataSource = dtPackageTypes;
if (packageTypeList.Count > 0)
{
lpPackage.ItemIndex = 0;
}
}
else
{
lpPackage.Properties.DataSource = null;
IRAPMessageBox.Instance.ShowErrorMessage(
errText,
caption);
}
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取未完成包装信息
/// </summary>
private UncompletedPackage GetUncompletedPackage()
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
ShowWaitForm("正在获取未完成包装信息");
UncompletedPackage rlt = null;
try
{
int errCode = 0;
string errText = "";
try
{
IRAPMESPKGClient.Instance.ufn_GetInfo_UncompletedPackage(
IRAPUser.Instance.CommunityID,
Options.SelectProduct.T102LeafID,
Options.SelectStation.T107EntityID,
objPackageType.Ordinal,
IRAPUser.Instance.SysLogID,
ref rlt,
out errCode,
out errText);
}
catch (Exception error)
{
errCode = -1;
errText = error.Message;
}
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode == 0)
{
WriteLog.Instance.Write(
string.Format(
"包装箱内已包装产品数量:[{0}]",
rlt.NumQtyInCarton),
strProcedureName);
}
if (errCode != 0)
IRAPMessageBox.Instance.ShowErrorMessage(
errText,
caption);
return rlt;
}
finally
{
CloseWaitForm();
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取未完成包装产品明细信息
/// </summary>
/// <param name="transactNo">包装交易号</param>
/// <param name="productLeaf">产品叶标识</param>
/// <returns></returns>
private List<FactPackaging> GetFactList_Packaging(
long transactNo,
int productLeaf)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
List<FactPackaging> rlt = new List<FactPackaging>();
try
{
int errCode = 0;
string errText = "";
try
{
IRAPMESPKGClient.Instance.ufn_GetFactList_Packaging(
IRAPUser.Instance.CommunityID,
transactNo,
productLeaf,
IRAPUser.Instance.SysLogID,
ref rlt,
out errCode,
out errText);
}
catch (Exception error)
{
errCode = -1;
errText = error.Message;
}
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode != 0)
IRAPMessageBox.Instance.ShowErrorMessage(
errText,
caption);
return rlt;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
private bool usp_SaveFact_Packaging(FactPackaging factPackage, out string OutputStr)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
OutputStr = "";
bool result = false;
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
//Hashtable paramDict = new Hashtable();
int communityID = IRAPUser.Instance.CommunityID;
Int64 factID = factPackage.FactID;
int productLeaf = Options.SelectProduct.T102LeafID;
int workUnitLeaf = Options.SelectStation.T107EntityID;
int packagingSpecNo = factPackage.PackagingSpecNo;
string wipPattern = factPackage.WIPCode;
int layerNumOfPallet = factPackage.LayerIdxOfPallet;
int cartonNumOfLayer = factPackage.CartonIdxOfLayer;
int layerNumOfCarton = factPackage.LayerIdxOfCarton;
int rowNumOfCarton = factPackage.RowIdxOfCarton;
int colNumOfCarton = factPackage.ColIdxOfCarton;
int layerNumOfBox = factPackage.LayerIdxOfBox;
int rowNumOfBox = factPackage.RowIdxOfBox;
int colNumOfBox = factPackage.ColIdxOfBox;
string boxSerialNumber = factPackage.BoxSerialNumber;
string cartonSerialNumber = factPackage.CartonSerialNumber;
string layerSerialNumber = factPackage.LayerSerialNumber;
string palletSerialNumber = factPackage.PalletSerialNumber;
Int64 sysLogID = IRAPUser.Instance.SysLogID;
//paramDict.Add("CommunityID", communityID);
//paramDict.Add("TransactNo", transactNo);
//paramDict.Add("FactID", factID);
//paramDict.Add("ProductLeaf", productLeaf);
//paramDict.Add("WorkUnitLeaf", workUnitLeaf);
//paramDict.Add("PackagingSpecNo", packagingSpecNo);
//paramDict.Add("WIPPattern", wipPattern);
//paramDict.Add("LayerNumOfPallet", layerNumOfPallet);
//paramDict.Add("CartonNumOfLayer", cartonNumOfLayer);
//paramDict.Add("LayerNumOfCarton", layerNumOfCarton);
//paramDict.Add("RowNumOfCarton", rowNumOfCarton);
//paramDict.Add("ColNumOfCarton", colNumOfCarton);
//paramDict.Add("LayerNumOfBox", layerNumOfBox);
//paramDict.Add("RowNumOfBox", rowNumOfBox);
//paramDict.Add("ColNumOfBox", colNumOfBox);
//paramDict.Add("BoxSerialNumber", boxSerialNumber);
//paramDict.Add("CartonSerialNumber", cartonSerialNumber);
//paramDict.Add("LayerSerialNumber", layerSerialNumber);
//paramDict.Add("PalletSerialNumber", palletSerialNumber);
//paramDict.Add("SysLogID", sysLogID);
WriteLog.Instance.Write(
string.Format(
"开始保存产品包装事实,输入参数: CommunityID={0}|TransactNo={1}|FactID={2}|" +
"ProductLeaf={3}|WorkUnitLeaf={4}|PackagingSpecNo={5}|WIPPattern={6}|" +
"LayerNumOfPallet={7}|CartonNumOfLayer={8}|LayerNumOfCarton={9}|" +
"RowNumOfCarton={10}|ColNumOfCarton={11}|LayerNumOfBox={12}|" +
"RowNumOfBox={13}|ColNumOfBox={14}|BoxSerialNumber={15}|" +
"CartonSerialNumber={16}|LayerSerialNumber={17}|PalletSerialNumber={18}|" +
"SysLogID={19}",
communityID,
transactNo,
factID,
productLeaf,
workUnitLeaf,
packagingSpecNo,
wipPattern,
layerNumOfPallet,
cartonNumOfLayer,
layerNumOfCarton,
rowNumOfCarton,
colNumOfCarton,
layerNumOfBox,
rowNumOfBox,
colNumOfBox,
boxSerialNumber,
cartonSerialNumber,
layerSerialNumber,
palletSerialNumber,
sysLogID),
strProcedureName);
try
{
OutputStr = IRAPMESPKGClient.Instance.usp_SaveFact_Packaging(
communityID,
transactNo,
factID,
productLeaf,
workUnitLeaf,
packagingSpecNo,
wipPattern,
layerNumOfPallet,
cartonNumOfLayer,
layerNumOfCarton,
rowNumOfCarton,
colNumOfCarton,
layerNumOfBox,
rowNumOfBox,
colNumOfBox,
boxSerialNumber,
cartonSerialNumber,
layerSerialNumber,
palletSerialNumber,
sysLogID,
out errCode,
out errText
);
//WCFClient wcfClient = new WCFClient();
//object obj = wcfClient.ExChange("IRAP.MES.BL.Packaging.dll",
// "IRAP.MES.BL.Packaging.Packing", "usp_SaveFact_Packaging",
// paramDict, out errCode, out errText);
if (errCode == 0)
{
result = true;
WriteLog.Instance.Write(string.Format("包装事实保存成功,返回值ErrCode:{0}, ErrText:{1}",
errCode, errText));
}
else
{
WriteLog.Instance.Write(string.Format("包装事实保存失败,返回值ErrCode:{0}, ErrText:{1}",
errCode, errText));
XtraMessageBox.Show(errText, "系统提示",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception error)
{
errCode = -1;
errText = error.Message;
}
return result;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 删除产品包装事实
/// </summary>
/// <decription>删除指定包装中某个产品,重新扫描,实现替换产品的功能,可暂时不用,前台暂时可不开通。</decription>
private bool DeleFact_Packaging()
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
Boolean result = false;
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
//int errCode = 0;
//string errText = "";
//Hashtable paramDict = new Hashtable();
//int communityID = 0;
//Int64 transactNo = 0;
//int productLeaf = 0;
//Int64 sysLogID = IRAPUser.Instance.SysLogID;
//paramDict.Add("CommunityID", communityID);
//paramDict.Add("TransactNo", transactNo);
//paramDict.Add("ProductLeaf", productLeaf);
//paramDict.Add("SysLogID", sysLogID);
//WriteLog.Instance.Write(
// string.Format("开始保存产品包装事实,输入参数: CommunityID:{0}|TransactNo:{1}|ProductLeaf:{2}|SysLogID:{3}",
// communityID,
// transactNo,
// productLeaf,
// sysLogID
// ),
// strProcedureName);
//try
//{
// WCFClient wcfClient = new WCFClient();
// object obj = wcfClient.ExChange("IRAP.MES.BL.Packaging.dll",
// "IRAP.MES.BL.Packaging.Packing", "usp_DeleFact_Packaging",
// paramDict, out errCode, out errText);
// if (errCode == 0)
// {
// result = true;
// WriteLog.Instance.Write(string.Format("包装事实保存成功,返回值ErrCode:{0}, ErrText:{1}",
// errCode, errText));
// }
// else
// {
// WriteLog.Instance.Write(string.Format("包装事实保存失败,返回值ErrCode:{0}, ErrText:{1}",
// errCode, errText));
// XtraMessageBox.Show(errText, "系统提示",
// MessageBoxButtons.OK, MessageBoxIcon.Error);
// }
//}
//catch (Exception ex)
//{
// WriteLog.Instance.Write(ex.ToString(), strProcedureName);
// XtraMessageBox.Show(ex.ToString(), "系统信息", MessageBoxButtons.OK,
// MessageBoxIcon.Error);
//}
return result;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 通过产品序列号获取到匹配的产品标签
/// </summary>
/// <param name="serialNumber">产品序列号</param>
private string GetWIPPattern(string serialNumber)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
string rlt = "";
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
WIPIDCode data = new WIPIDCode();
try
{
IRAPMESClient.Instance.ufn_GetInfo_WIPIDCode(
IRAPUser.Instance.CommunityID,
serialNumber,
Options.SelectProduct.T102LeafID,
Options.SelectStation.T107EntityID,
false,
IRAPUser.Instance.SysLogID,
ref data,
out errCode,
out errText);
}
catch (Exception error)
{
errCode = -1;
errText = error.Message;
}
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode != 0)
{
XtraMessageBox.Show(
errText,
caption,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
{
if (data.BarcodeStatus != 0)
{
WriteLog.Instance.Write(data.BarcodeStatusStr, strProcedureName);
IRAPMessageBox.Instance.ShowErrorMessage(
$"扫描到的条码:{serialNumber}\n" +
$"条码状态:{data.BarcodeStatusStr}",
caption);
}
else if (data.RoutingStatus != 0)
{
WriteLog.Instance.Write(data.RoutingStatusStr, strProcedureName);
IRAPMessageBox.Instance.ShowErrorMessage(
$"扫描到的条码:{serialNumber}\n" +
$"路由状态:{data.RoutingStatusStr}",
caption);
}
else
{
rlt = data.WIPPattern;
WriteLog.Instance.Write(
string.Format("得到产品标签:[{0}]", rlt),
strProcedureName);
}
}
return rlt;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
private List<WIPIDCode> GetWIPPatterns(string serialNumber)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
List<string> patterns = new List<string>();
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
List<WIPIDCode> datas = new List<WIPIDCode>();
try
{
IRAPMESClient.Instance.ufn_GetList_WIPIDCodes(
IRAPUser.Instance.CommunityID,
serialNumber,
Options.SelectProduct.T102LeafID,
Options.SelectStation.T107EntityID,
false,
IRAPUser.Instance.SysLogID,
ref datas,
out errCode,
out errText);
}
catch (Exception error)
{
errCode = -1;
errText = error.Message;
}
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode != 0)
{
XtraMessageBox.Show(
errText,
caption,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
return datas;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取打印信息
/// </summary>
/// <param name="labelID"></param>
/// <param name="serialNo"></param>
/// <returns></returns>
private List<LabelFMTStr> ufn_GetLabelFMTStr(int labelID, string serialNo)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
List<LabelFMTStr> labelFMTStr = null;
try
{
int errCode = 0;
string errText = "";
int correlationID = objPackageType.CorrelationID;
try
{
IRAPMESPKGClient.Instance.ufn_GetLabelFMTStr(
IRAPUser.Instance.CommunityID,
correlationID,
labelID,
serialNo,
IRAPUser.Instance.SysLogID,
ref labelFMTStr,
out errCode,
out errText);
}
catch (Exception ex)
{
errCode = -1;
errText = ex.Message;
}
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode != 0)
IRAPMessageBox.Instance.ShowErrorMessage(
errText,
caption);
return labelFMTStr;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
private string GetNextPackageSN(string labelType)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
string packageSN = "";
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
IRAPMESPKGClient.Instance.ufn_GetNextPackageSN(
IRAPUser.Instance.CommunityID,
objPackageType.CorrelationID,
objPackageType.Ordinal,
labelType,
DateTime.Now,
IRAPUser.Instance.SysLogID,
ref packageSN,
out errCode,
out errText);
WriteLog.Instance.Write(
string.Format("{0}.{1}", errCode, errText),
strProcedureName);
if (errCode == 0)
WriteLog.Instance.Write(
string.Format(
"申请包装序列号成功:{0}", packageSN),
strProcedureName);
else
IRAPMessageBox.Instance.ShowErrorMessage(
errText,
caption);
return packageSN;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 复核交易
/// </summary>
/// <param name="transactNo">待复核的交易号</param>
private bool ssp_CheckTransaction(long transactNo)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
bool rlt = false;
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
try
{
IRAPUTSClient.Instance.ssp_CheckTransaction(
IRAPUser.Instance.CommunityID,
transactNo,
IRAPUser.Instance.SysLogID,
out errCode,
out errText);
}
catch (Exception error)
{
errCode = -1;
errText = error.Message;
}
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
rlt = errCode == 0;
if (errCode != 0)
IRAPMessageBox.Instance.ShowErrorMessage(
errText,
caption);
return rlt;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
private long GetTransactNo(string opCode)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
long sequenceNo = 0;
sequenceNo = IRAPUTSClient.Instance.mfn_GetTransactNo(
IRAPUser.Instance.CommunityID,
1,
IRAPUser.Instance.SysLogID,
opCode);
return sequenceNo;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 申请下一个序列号
/// </summary>
/// <param name="sequenceCode"></param>
/// <param name="counts"></param>
/// <returns></returns>
private long GetNextSequenceNo(string sequenceCode, int counts)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
long sequenceNo = 0;
IRAPUTSClient.Instance.msp_GetSequenceNo(
IRAPUser.Instance.CommunityID,
sequenceCode,
counts,
IRAPUser.Instance.SysLogID,
ref sequenceNo,
out errCode,
out errText);
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode != 0)
IRAPMessageBox.Instance.ShowErrorMessage(errText, caption);
return sequenceNo;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 打印标签
/// </summary>
/// <param name="labelID"></param>
/// <param name="serialNo"></param>
/// <returns></returns>
//private bool PrintLabel(int labelID, string serialNo)
//{
// Boolean result = false;
// IList<LabelFMTStr> labelFMTStr = ufn_GetLabelFMTStr(labelID, serialNo);
// if (labelFMTStr == null) return false;
// IRAP.Global.LPTPrint print = new LPTPrint();
// try
// {
// //打印标签
// for (int i = 0; i < labelFMTStr.Count; i++)
// {
// string printPort = labelFMTStr[i].PrintPort;
// string printStr = labelFMTStr[i].TemplateFMTStr;
// string filePath = labelFMTStr[i].FilePath;
// if (filePath.IndexOf("<Action") >= 0)
// {
// try
// {
// object tag = null;
// Actions.UDFActions.DoActions(filePath, null, ref tag);
// }
// catch (Exception error)
// {
// WriteLog.Instance.Write(
// string.Format("错误信息:{0}。跟踪堆栈:{1}。",
// error.Message,
// error.StackTrace),
// string.Format("{0}.{1}",
// MethodBase.GetCurrentMethod().DeclaringType.FullName,
// MethodBase.GetCurrentMethod().Name));
// }
// }
// else
// {
// System.Diagnostics.Process p = new System.Diagnostics.Process();
// p.StartInfo.FileName = "cmd.exe";//要执行的程序名称
// p.StartInfo.UseShellExecute = false;
// p.StartInfo.RedirectStandardInput = true;//可能接受来自调用程序的输入信息
// p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
// p.StartInfo.CreateNoWindow = true;//不显示程序窗口
// p.Start();//启动程序
// //向CMD窗口发送输入信息:
// p.StandardInput.WriteLine(string.Format("copy {0} {1}", filePath, printPort));
// //p.StandardInput.WriteLine("exit");
// print.LPTOpen(printPort);
// print.LPTWrite(printPort, printStr);
// }
// }
// result = true;
// }
// catch (Exception ex)
// {
// WriteLog.Instance.Write(ex.ToString(), className + ".标签打印");
// }
// print.LPTClose();
// return result;
//}
/// <summary>
/// 打印标签
/// </summary>
/// <param name="labelID"></param>
/// <param name="serialNo"></param>
/// <returns></returns>
private bool PrintLabel(int labelID, string serialNo, string OutputStr)
{
Boolean result = false;
IList<LabelFMTStr> labelFMTStr = new List<LabelFMTStr>();
try
{
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(OutputStr);
XmlNode root = xdoc.FirstChild;
if (root.Name == "ROOT")
{
foreach (XmlNode node in root.ChildNodes)
{
LabelFMTStr lb = new LabelFMTStr();
lb.Ordinal = int.Parse(node.Attributes["Ordinal"].Value);
XmlDocument xdoc2 = new XmlDocument();
XmlNode n = xdoc2.CreateElement("ROOT");
xdoc2.AppendChild(n);
n = xdoc2.ImportNode(node, true);
try
{
xdoc2.FirstChild.AppendChild(n);
}
catch (Exception)
{ }
lb.FilePath = xdoc2.InnerXml;
//lb.TemplateFMTStr = node.Attributes["Data"].Value;
labelFMTStr.Add(lb);
}
}
}
catch (Exception error)
{
WriteLog.Instance.Write(
string.Format("错误信息:{0}。跟踪堆栈:{1}。",
error.Message,
error.StackTrace),
string.Format("{0}.{1}",
MethodBase.GetCurrentMethod().DeclaringType.FullName,
MethodBase.GetCurrentMethod().Name));
}
if (labelFMTStr.Count == 0) return false;
//IRAP.Global.LPTPrint print = new LPTPrint();
try
{
//打印标签
for (int i = 0; i < labelFMTStr.Count; i++)
{
//string printPort = labelFMTStr[i].PrintPort;
//string printStr = labelFMTStr[i].TemplateFMTStr;
string filePath = labelFMTStr[i].FilePath;
if (filePath.IndexOf("<Action") >= 0)
{
try
{
object tag = null;
Actions.UDFActions.DoActions(filePath, null, ref tag);
}
catch (Exception error)
{
WriteLog.Instance.Write(
string.Format("错误信息:{0}。跟踪堆栈:{1}。",
error.Message,
error.StackTrace),
string.Format("{0}.{1}",
MethodBase.GetCurrentMethod().DeclaringType.FullName,
MethodBase.GetCurrentMethod().Name));
}
}
//else
//{
//System.Diagnostics.Process p = new System.Diagnostics.Process();
//p.StartInfo.FileName = "cmd.exe";//要执行的程序名称
//p.StartInfo.UseShellExecute = false;
//p.StartInfo.RedirectStandardInput = true;//可能接受来自调用程序的输入信息
//p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
//p.StartInfo.CreateNoWindow = true;//不显示程序窗口
//p.Start();//启动程序
////向CMD窗口发送输入信息:
//p.StandardInput.WriteLine(string.Format("copy {0} {1}", filePath, printPort));
//p.StandardInput.WriteLine("exit");
//print.LPTOpen(printPort);
//print.LPTWrite(printPort, printStr);
//}
}
result = true;
}
catch (Exception ex)
{
WriteLog.Instance.Write(ex.ToString(), className + ".标签打印");
}
return result;
}
#endregion
private void lpPackage_QueryPopUp(object sender, CancelEventArgs e)
{
chkAllowRePrint.Checked = false;
btnRePrint.Enabled = false;
}
private void lpPackage_EditValueChanged(object sender, EventArgs e)
{
//this.lpPackage.Text = packageTypeList
if (lpPackage.ItemIndex != -1)
{
if (packageTypeList.Count > lpPackage.ItemIndex)
{
objPackageType = packageTypeList[lpPackage.ItemIndex];
lblSmallPackageType.Text = string.Format("小包装: {0} 层 {1} 行 {2} 列",
objPackageType.NumLayersOfBox,
objPackageType.QtyPerRowOfBox,
objPackageType.QtyPerColOfBox);
lblLargePackageType.Text = string.Format("大包装: {0} 层 {1} 行 {2} 列",
objPackageType.NumLayersOfCarton,
objPackageType.NumBoxPerRowOfCarton,
objPackageType.NumBoxPerColOfCarton);
lblPalletPackageType.Text =
string.Format(
"托包装: {0} 层 {1} 个大包装每层",
objPackageType.NumLayersOfPallet,
objPackageType.NumCartonsPerLayerOfPallet);
if (objPackageType.T117LabelID_Pallet > 0)
{
layoutControlItemPallet.Width = layoutControl1.Width / 3;
layoutControlItemBox.Width = layoutControl1.Width / 3;
layoutControlItemCarton.Width = layoutControl1.Width / 3;
layoutControlItemPallet.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
layoutControlItemPalletLayer.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
}
else
{
layoutControlItemPallet.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
layoutControlItemPalletLayer.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
layoutControlItemBox.Width = layoutControl1.Width / 2;
layoutControlItemCarton.Width = layoutControl1.Width / 2;
}
}
}
}
private void dgvPallet_CellClick(object sender, DataGridViewCellEventArgs e)
{
//将Pallet坐标转换成List中对应的索引
int palletColIndex = e.ColumnIndex;
int palletLayerIndex =
dgvPalletLayer.SelectedCells.Count > 0 ?
dgvPalletLayer.SelectedCells[0].RowIndex :
0;
int palletUnitIndex =
palletLayerIndex *
objPackageType.NumCartonsPerLayerOfPallet +
palletColIndex;
//呈现包装箱
GenerateBox(palletUnitIndex, 1, 1, 1, 1);
GenerateBoxLayer(palletUnitIndex, 1, 1, 1, 1);
GenerateCarton(palletUnitIndex, 1, 1, 1);
GenerateCartonLayer(palletUnitIndex);
}
private void dgvPallet_SelectionChanged(object sender, EventArgs e)
{
if (dgvPallet.SelectedCells.Count > 0)
{
int rowIndex = dgvPallet.SelectedCells[0].RowIndex;
int colIndex = dgvPallet.SelectedCells[0].ColumnIndex;
dgvPallet.Rows[rowIndex].Cells[colIndex].Style.SelectionBackColor =
dgvPallet.Rows[rowIndex].Cells[colIndex].Style.BackColor;
}
}
private void dgvPalletLayer_CellClick(object sender, DataGridViewCellEventArgs e)
{
//将Pallet坐标转换成List中对应的索引
int palletLayerIndex = e.RowIndex;
int palletColIndex =
dgvPallet.SelectedCells.Count > 0 ?
dgvPallet.SelectedCells[0].ColumnIndex :
0;
int palletUnitIndex = palletLayerIndex * objPackageType.NumCartonsPerLayerOfPallet + palletColIndex;
//呈现包装箱
GenerateBox(palletUnitIndex, 1, 1, 1, 1);
GenerateBoxLayer(palletUnitIndex, 1, 1, 1, 1);
GenerateCarton(palletUnitIndex, 1, 1, 1);
GenerateCartonLayer(palletUnitIndex);
}
private void dgvPalletLayer_SelectionChanged(object sender, EventArgs e)
{
if (dgvPalletLayer.SelectedCells.Count > 0)
{
int rowIndex = dgvPalletLayer.SelectedCells[0].RowIndex;
int colIndex = dgvPalletLayer.SelectedCells[0].ColumnIndex;
dgvPalletLayer.Rows[rowIndex].Cells[colIndex].Style.SelectionBackColor =
dgvPalletLayer.Rows[rowIndex].Cells[colIndex].Style.BackColor;
}
}
private void dgvCarton_CellClick(object sender, DataGridViewCellEventArgs e)
{
int palletColIndex = dgvPallet.SelectedCells.Count > 0 ?
dgvPallet.SelectedCells[0].ColumnIndex : 0;
int palletLayerIndex = dgvPalletLayer.SelectedCells.Count > 0 ?
dgvPalletLayer.SelectedCells[0].RowIndex : 0;
int palletUnitIndex = palletLayerIndex * objPackageType.NumCartonsPerLayerOfPallet + palletColIndex;
int rowIndex = dgvCarton.SelectedCells[0].RowIndex;
int colIndex = dgvCarton.SelectedCells[0].ColumnIndex;
int cartonLayerSet = 1;
if (dgvCartonLayer.SelectedCells.Count > 0)
{
cartonLayerSet = dgvCartonLayer.SelectedCells[0].RowIndex + 1;
}
int boxLayer = 1;
if (dgvBoxLayer.SelectedCells.Count > 0)
{
boxLayer = dgvBoxLayer.SelectedCells[0].RowIndex + 1;
}
int cartonRow = rowIndex + 1;
int cartonCol = colIndex + 1;
GenerateBox(palletUnitIndex, cartonLayerSet, cartonRow, cartonCol, boxLayer);
GenerateBoxLayer(palletUnitIndex, cartonLayerSet, cartonRow, cartonCol, boxLayer);
}
private void dgvCarton_SelectionChanged(object sender, EventArgs e)
{
if (objPackageType == null) return;
if (dgvCarton.SelectedCells.Count == 0)
return;
int rowIndex = dgvCarton.SelectedCells[0].RowIndex;
int colIndex = dgvCarton.SelectedCells[0].ColumnIndex;
dgvCarton.Rows[rowIndex].Cells[colIndex].Style.SelectionBackColor =
dgvCarton.Rows[rowIndex].Cells[colIndex].Style.BackColor;
}
private void dgvCartonLayer_CellClick(object sender, DataGridViewCellEventArgs e)
{
int palletColIndex =
dgvPallet.SelectedCells.Count > 0 ?
dgvPallet.SelectedCells[0].ColumnIndex :
0;
int palletLayerIndex =
dgvPalletLayer.SelectedCells.Count > 0 ?
dgvPalletLayer.SelectedCells[0].RowIndex :
0;
int palletUnitIndex =
palletLayerIndex *
objPackageType.NumCartonsPerLayerOfPallet +
palletColIndex;
int rowIndex = dgvCartonLayer.SelectedCells[0].RowIndex;
int colIndex = dgvCartonLayer.SelectedCells[0].ColumnIndex;
int cartonRowSet = 1;
if (dgvCarton.SelectedCells.Count > 0)
{
cartonRowSet = dgvCarton.SelectedCells[0].RowIndex + 1;
}
int cartonColSet = 1;
if (dgvCarton.SelectedCells.Count > 0)
{
cartonColSet = dgvCarton.SelectedCells[0].ColumnIndex + 1;
}
int boxLayer = 1;
if (dgvBoxLayer.SelectedCells.Count > 0)
{
boxLayer = dgvBoxLayer.SelectedCells[0].RowIndex + 1;
}
int cartonLayer = rowIndex + 1;
GenerateBox(
palletUnitIndex,
cartonLayer,
cartonRowSet,
cartonColSet,
boxLayer);
GenerateBoxLayer(
palletUnitIndex,
cartonLayer,
cartonRowSet,
cartonColSet,
boxLayer);
GenerateCarton(
palletUnitIndex,
cartonLayer,
cartonRowSet,
cartonColSet);
}
private void dgvCartonLayer_SelectionChanged(object sender, EventArgs e)
{
if (objPackageType == null) return;
if (dgvCartonLayer.SelectedCells.Count == 0)
return;
int rowIndex = dgvCartonLayer.SelectedCells[0].RowIndex;
int colIndex = dgvCartonLayer.SelectedCells[0].ColumnIndex;
dgvCartonLayer.Rows[rowIndex].Cells[colIndex].Style.SelectionBackColor =
dgvCartonLayer.Rows[rowIndex].Cells[colIndex].Style.BackColor;
}
private void dgvBox_CellClick(object sender, DataGridViewCellEventArgs e)
{
// 点击单元格,自动定位坐标(小包装箱层、大包装箱、大包装箱层)
if (objPackageType == null) return;
int cartonLayer, cartonRow, cartonCol, boxLayer, boxRow, boxCol;
int ordinal = int.Parse(dgvBox.SelectedCells[0].Value.ToString());
SetBoxOrdinal(
ordinal,
out cartonLayer,
out cartonRow,
out cartonCol,
out boxLayer,
out boxRow,
out boxCol);
}
private void dgvBox_CellToolTipTextNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)
{
if (sender is DataGridView)
{
int palletColIndex = dgvPallet.SelectedCells.Count > 0 ?
dgvPallet.SelectedCells[0].ColumnIndex : 0;
int palletLayerIndex = dgvPalletLayer.SelectedCells.Count > 0 ?
dgvPalletLayer.SelectedCells[0].RowIndex : 0;
int palletUnitIndex = palletLayerIndex * objPackageType.NumCartonsPerLayerOfPallet + palletColIndex;
if (e.RowIndex < 0) return;
int ordinal = 0;
if (!int.TryParse(dgvBox.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out ordinal)) return;
string productSN = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["ProductSN"].ToString();
string boxPackageSN = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["BoxPackageSN"].ToString();
string cartonPackageSN = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["CartonPackageSN"].ToString();
string doStatus = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["Do"].ToString();
doStatus = doStatus == "2" ? "完成包装" : "未完成包装";
string cartonLayerSet = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["CartonLayer"].ToString();
string cartonRowSet = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["CartonRow"].ToString();
string cartonColSet = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["CartonCol"].ToString();
string boxLayerSet = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["BoxLayer"].ToString();
string boxRowSet = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["BoxRow"].ToString();
string boxColSet = palletUnitTables[palletUnitIndex].Rows[ordinal - 1]["BoxCol"].ToString();
string location = string.Format("大包装坐标:{0}层 {1}行 {2}列\r\n小包装坐标{3}层 {4}行 {5}列",
cartonLayerSet, cartonRowSet, cartonColSet, boxLayerSet, boxRowSet, boxColSet);
string hintText = string.Format("序号:{0}\n\r产品序列号:{1}\n\r小包装序列号:{2}\n\r大包装序列号:{3}\n\r状态:{4}\n\r{5}",
ordinal, productSN, boxPackageSN, cartonPackageSN, doStatus, location);
DevExpress.Utils.ToolTipControllerShowEventArgs tip = new DevExpress.Utils.ToolTipControllerShowEventArgs();
tip.Title = "";
tip.ToolTip = hintText;
tip.Appearance.Font = new Font("微软雅黑", 16, FontStyle.Bold);
tip.Appearance.Options.UseFont = true;
tip.ShowBeak = true;
tip.Rounded = true;////圆角
tip.RoundRadius = 7;//圆角率
tip.ToolTipStyle = DevExpress.Utils.ToolTipStyle.Windows7;
tip.ToolTipType = DevExpress.Utils.ToolTipType.SuperTip;
tip.IconType = DevExpress.Utils.ToolTipIconType.None;
tip.IconSize = DevExpress.Utils.ToolTipIconSize.Small;
toolTipController.ShowHint(tip);
}
}
private void dgvBox_SelectionChanged(object sender, EventArgs e)
{
if (dgvBox.SelectedCells.Count > 0)
{
int rowIndex = dgvBox.SelectedCells[0].RowIndex;
int colIndex = dgvBox.SelectedCells[0].ColumnIndex;
dgvBox.Rows[rowIndex].Cells[colIndex].Style.SelectionBackColor =
dgvBox.Rows[rowIndex].Cells[colIndex].Style.BackColor;
}
}
private void dgvBox_SizeChanged(object sender, EventArgs e)
{
DataGridView dtGrid = sender as DataGridView;
if (dtGrid.Rows.Count > 0)
{
int rowCount = dtGrid.Rows.Count;
int height = dtGrid.Height;
for (int i = 0; i < rowCount; i++)
{
dtGrid.Rows[i].Height = height / rowCount;
}
dtGrid.Rows[rowCount - 1].Height = height / rowCount - 3;
}
}
private void dgvBoxLayer_CellClick(object sender, DataGridViewCellEventArgs e)
{
int palletColIndex =
dgvPallet.SelectedCells.Count > 0 ?
dgvPallet.SelectedCells[0].ColumnIndex :
0;
int palletLayerIndex =
dgvPalletLayer.SelectedCells.Count > 0 ?
dgvPalletLayer.SelectedCells[0].RowIndex :
0;
int palletUnitIndex =
palletLayerIndex *
objPackageType.NumCartonsPerLayerOfPallet +
palletColIndex;
int rowIndex = dgvBoxLayer.SelectedCells[0].RowIndex;
int colIndex = dgvBoxLayer.SelectedCells[0].ColumnIndex;
int cartonLayerSet = 1;
if (dgvCartonLayer.SelectedCells.Count > 0)
{
cartonLayerSet = dgvCartonLayer.SelectedCells[0].RowIndex + 1;
}
int cartonRowSet = 1;
if (dgvCarton.SelectedCells.Count > 0)
{
cartonRowSet = dgvCarton.SelectedCells[0].RowIndex + 1;
}
int cartonColSet = 1;
if (dgvCarton.SelectedCells.Count > 0)
{
cartonColSet = dgvCarton.SelectedCells[0].ColumnIndex + 1;
}
int boxLayer = rowIndex + 1;
GenerateBox(
palletUnitIndex,
cartonLayerSet,
cartonRowSet,
cartonColSet,
boxLayer);
}
private void dgvBoxLayer_SelectionChanged(object sender, EventArgs e)
{
if (objPackageType == null) return;
if (dgvBoxLayer.SelectedCells.Count == 0)
return;
int rowIndex = dgvBoxLayer.SelectedCells[0].RowIndex;
int colIndex = dgvBoxLayer.SelectedCells[0].ColumnIndex;
dgvBoxLayer.Rows[rowIndex].Cells[colIndex].Style.SelectionBackColor =
dgvBoxLayer.Rows[rowIndex].Cells[colIndex].Style.BackColor;
}
private void edtProductSN_Enter(object sender, EventArgs e)
{
chkAllowRePrint.Checked = false;
btnRePrint.Enabled = false;
}
private void edtProductSN_KeyDown(object sender, KeyEventArgs e)
{
string strProcedureName = $"{className}.{MethodBase.GetCurrentMethod().Name}";
try
{
if (e.KeyCode == Keys.Enter)
{
string serialNumber = edtProductSN.Text.Trim().ToString();
if (string.IsNullOrEmpty(serialNumber))
{
IRAPMessageBox.Instance.ShowErrorMessage(
"产品序列号为空,请确认输入!",
caption);
return;
}
edtProductSN.Text = "";
List<WIPIDCode> wips = GetWIPPatterns(serialNumber);
if (wips.Count <= 0)
{
IRAPMessageBox.Instance.ShowErrorMessage(
$"无法解析{serialNumber},请重新扫描或输入!",
caption);
edtProductSN.Text = "";
edtProductSN.Focus();
return;
}
#region 产品路由检验
string errText = "";
foreach (WIPIDCode wip in wips)
{
if (wip.BarcodeStatus != 0)
{
errText += $"在制品:{wip.WIPPattern}|条码状态:{wip.BarcodeStatusStr}|";
break;
}
if (wip.RoutingStatus != 0)
{
errText += $"在制品{wip.WIPPattern}|路由状态:{wip.RoutingStatusStr}|";
}
}
if (errText != "")
{
IRAPMessageBox.Instance.ShowErrorMessage(
errText.Replace("|", "\n"),
caption);
WriteLog.Instance.Write(errText, strProcedureName);
edtProductSN.Text = "";
edtProductSN.Focus();
return;
}
#endregion
int palletUnitIndex = -1;
for (int i = 0; i < allNumCartonsInPallet; i++)
{
if (palletUnitTables[i].Rows[0]["Do"].ToString() != "2" &&
palletUnitTables[i].Rows[allBoxNum - 1]["Do"].ToString() != "2")
{
palletUnitIndex = i;
break;
}
if (palletUnitTables[i].Rows[0]["Do"].ToString() == "2" &&
palletUnitTables[i].Rows[allBoxNum - 1]["Do"].ToString() != "2")
{
palletUnitIndex = i;
break;
}
}
if (palletUnitIndex == -1)
return;
#region 计算正在包装的大包装内剩余的包装空位
int emptyCount = 0;
for (int i = 0; i < palletUnitTables[palletUnitIndex].Rows.Count; i++)
{
if (palletUnitTables[palletUnitIndex].Rows[i]["Do"].ToString() != "2")
{
emptyCount++;
}
}
#endregion
if (emptyCount < wips.Count)
{
IRAPMessageBox.Instance.ShowErrorMessage(
$"本次扫描到的待包装产品数为[{wips.Count}]," +
$"而大包装中的可包装位只有[{emptyCount}]," +
"无法批量包装,请直接扫描在制品上的条码一个一个包装。\n谢谢!",
caption);
edtProductSN.Text = "";
edtProductSN.Focus();
return;
}
foreach (WIPIDCode wip in wips)
{
int currentPalletLayer = (palletUnitIndex / objPackageType.NumCartonsPerLayerOfPallet) + 1;
int currentPalletCol = palletUnitIndex + 1 - (currentPalletLayer - 1) * objPackageType.NumCartonsPerLayerOfPallet;
for (int i = 0; i < allBoxNum; i++)
{
string doStatus = palletUnitTables[palletUnitIndex].Rows[i]["Do"].ToString();
//如果状态为待包装
if (doStatus == "1")
{
int ordinal = i + 1;
int cartonLayer, cartonRow, cartonCol, boxLayer, boxRow, boxCol;
SetBoxOrdinal(
ordinal,
out cartonLayer,
out cartonRow,
out cartonCol,
out boxLayer,
out boxRow,
out boxCol);
#region 保存事实并打印标签
//每包完一箱都要进行一次数据提交动作
//string wipPattern = GetWIPPattern(serialNumber); // 原来只支持单个在制品的包装
string wipPattern = wip.WIPPattern;
if (string.IsNullOrEmpty(wipPattern)) return;
string boxSerialNumber = palletUnitTables[palletUnitIndex].Rows[i]["BoxPackageSN"].ToString();
int boxNumOfInCarton = objPackageType.QtyPerColOfBox * objPackageType.QtyPerRowOfBox;
//已包装产品数量是Box容量整倍数时,需要申请Box序列号
if (i % boxNumOfInCarton == 0)
{
boxSerialNumber = GetNextPackageSN("BOX");
//更新内存表
for (int r = i; r < i + boxNumOfInCarton; r++)
{
palletUnitTables[palletUnitIndex].Rows[r]["BoxPackageSN"] = boxSerialNumber;
}
}
string cartonSerialNumber =
palletUnitTables[palletUnitIndex].Rows[i]["CartonPackageSN"].ToString();
//每个Carton需要申请一个新的交易号和标签号
if (i == 0)
{
//申请交易号
transactNo = GetTransactNo("-12");
if (transactNo == 0)
{
XtraMessageBox.Show("交易号申请失败!", "提示", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
//更新内存表
BatchUpdateMemTable(palletUnitIndex, "TransactNo", transactNo.ToString());
cartonSerialNumber = GetNextPackageSN("CRT");
edtCartonSN.Text = cartonSerialNumber;
BatchUpdateMemTable(palletUnitIndex, "CartonPackageSN", cartonSerialNumber);
}
string PalletSerialNumber = palletUnitTables[palletUnitIndex].Rows[i]["PalletPackageSN"].ToString();
string layerSerialNumber = palletUnitTables[palletUnitIndex].Rows[i]["PalletLayerSN"].ToString();
long factNo = GetNextSequenceNo("NextFactNo", 1);
FactPackaging factPackage = new FactPackaging();
factPackage.FactID = factNo;
factPackage.PackagingSpecNo = objPackageType.Ordinal;
factPackage.WIPCode = wipPattern;
factPackage.LayerIdxOfPallet = currentPalletLayer;
factPackage.CartonIdxOfLayer = currentPalletCol;
factPackage.LayerIdxOfCarton = cartonLayer;
factPackage.RowIdxOfCarton = cartonRow;
factPackage.ColIdxOfCarton = cartonCol;
factPackage.LayerIdxOfBox = boxLayer;
factPackage.RowIdxOfBox = boxRow;
factPackage.ColIdxOfBox = boxCol;
factPackage.BoxSerialNumber = boxSerialNumber;
factPackage.CartonSerialNumber = cartonSerialNumber;
factPackage.LayerSerialNumber = layerSerialNumber;
factPackage.PalletSerialNumber = PalletSerialNumber;
bool saveResult = usp_SaveFact_Packaging(factPackage, out OutputStr);
WriteLog.Instance.Write($"OutputStr={OutputStr}", strProcedureName);
if (!string.IsNullOrEmpty(OutputStr))
{
//IniFile.WriteString("OutputStr", transactNo.ToString(), OutputStr, attributeFileName);
XmlFile.SavaConfig(transactNo.ToString(), OutputStr, attributeFileName);
}
//如果数据提交动作数据库返回成功状态,则再进行
if (!saveResult) return;
//事实保存成功,打印标签
//判断是否已包满一Box,如果已满,则打印Box标签
if (boxRow == objPackageType.QtyPerRowOfBox &&
boxCol == objPackageType.QtyPerColOfBox &&
boxLayer == objPackageType.NumLayersOfBox)
{
if (!string.IsNullOrEmpty(OutputStr))
{
PrintLabel(objPackageType.T117LabelID_Box, boxSerialNumber, OutputStr);
}
}
//判断是否已已包满一大包装箱,如果已满,则打印Carton标签
if (ordinal == allBoxNum)
{
//Carton包满或点包装完成按钮时复核交易
if (ssp_CheckTransaction(transactNo))
{
//if (!string.IsNullOrEmpty(OutputStr))
//PrintLabel(objPackageType.T117LabelID_Carton, cartonSerialNumber, OutputStr);
}
}
if (objPackageType.T117LabelID_Layer > 0)
{
//判断是否已包满一托中的层,如果已满,则打印托层的标签
if (ordinal == allBoxNum && currentPalletCol == objPackageType.NumCartonsPerLayerOfPallet)
{
//if (!string.IsNullOrEmpty(OutputStr))
//PrintLabel(objPackageType.T117LabelID_Layer, layerSerialNumber, OutputStr);
}
//判断是否已包满一托的标签,如果已满,则打印托标签
if (ordinal == allBoxNum && currentPalletLayer == objPackageType.NumLayersOfPallet)
{
//if (!string.IsNullOrEmpty(OutputStr))
//PrintLabel(objPackageType.T117LabelID_Pallet, factPackage.PalletSerialNumber, OutputStr);
}
}
palletUnitTables[palletUnitIndex].Rows[i]["ProductSN"] = serialNumber;
palletUnitTables[palletUnitIndex].Rows[i]["TransactNo"] = transactNo;
palletUnitTables[palletUnitIndex].Rows[i]["FactNo"] = factNo;
#endregion
//改变Box状态,标识其已经包装完成
palletUnitTables[palletUnitIndex].Rows[i]["Do"] = 2;
//同时将下一个包装箱的状态设置为带包装
if (i < allBoxNum - 1)
{
palletUnitTables[palletUnitIndex].Rows[i + 1]["Do"] = 1;
}
//如果小包装箱已满,则需要换箱,即将Box的序列号向前推进1
if (boxRow == objPackageType.QtyPerRowOfBox &&
boxCol == objPackageType.QtyPerColOfBox)
{
SetBoxOrdinal(
ordinal + 1,
out cartonLayer,
out cartonRow,
out cartonCol,
out boxLayer,
out boxRow,
out boxCol);
}
if (ordinal == allBoxNum)
{
if (objPackageType.T117LabelID_Pallet > 0)
{
//判断托是否已满
if (currentPalletLayer == objPackageType.NumLayersOfPallet)
{
InitPackageStart(true);
return;
}
//如果大包装箱已满,则需要换箱,将此包装箱数据暂存至List中
if (palletUnitIndex < allNumCartonsInPallet)
{
palletUnitIndex += 1;
}
else
{
palletUnitIndex = 0;
}
GeneratePallet(currentPalletLayer);
GeneratePalletLayer();
}
else
{
//当Carton已包装满,则需要结束交易,进行初始化
InitPackageStart(true);
return;
}
}
GenerateBox(palletUnitIndex, cartonLayer, cartonRow, cartonCol, boxLayer);
GenerateBoxLayer(palletUnitIndex, cartonLayer, cartonRow, cartonCol, boxLayer);
GenerateCarton(palletUnitIndex, cartonLayer, cartonRow, cartonCol);
GenerateCartonLayer(palletUnitIndex);
break;
}
}
}
}
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
IRAPMessageBox.Instance.Show(
error.Message,
caption,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void chkAllowRePrint_EditValueChanged(object sender, EventArgs e)
{
if (chkAllowRePrint.Checked)
{
btnRePrint.Enabled = true;
edtBoxSN.Properties.ReadOnly = false;
edtCartonSN.Properties.ReadOnly = false;
edtPalletLayerSN.Properties.ReadOnly = false;
}
else
{
btnRePrint.Enabled = false;
edtBoxSN.Properties.ReadOnly = true;
edtCartonSN.Properties.ReadOnly = true;
edtPalletLayerSN.Properties.ReadOnly = true;
}
}
private void frmProductPackage_Activated(object sender, EventArgs e)
{
Options.Visible = true;
Options.btnSwitch.Enabled = true;
GetKanban_PackageTypes();
Options.OptionChanged += Options_OptionChanged;
}
private void XML2CDATA(string xml)
{
StringBuilder sxml = new StringBuilder(xml);
}
private void btnPackageFinish_Click(object sender, EventArgs e)
{
if (transactNo == 0)
{
IRAPMessageBox.Instance.ShowErrorMessage("尚未进行包装!", caption);
InitPackageStart(true);
return;
}
if (!chkStorePackage.Checked)
{
if (!ssp_CheckTransaction(transactNo))
return;
//打标签
//寻找最新大包装标签和小包装标签
string cartonSerialNumber = "";
string boxSerialNumber = "";
int ordinal = 0;
int cartonLayer = 0;
int cartonRow = 0;
int cartonCol = 0;
int boxLayer = objPackageType.NumLayersOfBox;
int boxRow = objPackageType.QtyPerRowOfBox;
int boxCol = objPackageType.QtyPerColOfBox;
if (string.IsNullOrEmpty(OutputStr))
{
//OutputStr = IniFile.ReadString("OutputStr", transactNo.ToString(), "", attributeFileName);
try
{
OutputStr = XmlFile.GetValue(transactNo.ToString(), attributeFileName);
}
catch (Exception error)
{
WriteLog.Instance.Write(
string.Format("无法读取暂存的 OutputStr:[{0}]", error.Message));
}
}
if (!string.IsNullOrEmpty(OutputStr))
{
for (int i = allNumCartonsInPallet - 1; i >= 0; i--)
{
Boolean bk = false;
for (int j = allBoxNum - 1; j >= 0; j--)
{
if (palletUnitTables[i].Rows[j]["ProductSN"].ToString().Trim() != "")
{
cartonSerialNumber = palletUnitTables[i].Rows[j]["CartonPackageSN"].ToString().Trim();
boxSerialNumber = palletUnitTables[i].Rows[j]["BoxPackageSN"].ToString().Trim();
ordinal = j + 1;
SetBoxOrdinal(
ordinal,
out cartonLayer,
out cartonRow,
out cartonCol,
out boxLayer,
out boxRow,
out boxCol);
bk = true;
break;
}
}
if (bk) break;
}
if (boxRow != objPackageType.QtyPerRowOfBox ||
boxCol != objPackageType.QtyPerColOfBox ||
boxLayer != objPackageType.NumLayersOfBox)
{
if (objPackageType.T117LabelID_Box > 0)
if (!string.IsNullOrEmpty(OutputStr))
PrintLabel(objPackageType.T117LabelID_Box, boxSerialNumber, OutputStr);
}
if (ordinal != allBoxNum)
{
if (objPackageType.T117LabelID_Carton > 0)
{
//if (!string.IsNullOrEmpty(OutputStr))
//PrintLabel(objPackageType.T117LabelID_Carton, cartonSerialNumber, OutputStr);
}
}
if (objPackageType.T117LabelID_Pallet > 0)
{
string palletSerialNumber = palletUnitTables[0].Rows[0]["PalletPackageSN"].ToString();
//if (!string.IsNullOrEmpty(OutputStr))
//PrintLabel(objPackageType.T117LabelID_Pallet, palletSerialNumber, OutputStr);
}
//IniFile.INIDeleteKey("OutputStr", transactNo.ToString(), attributeFileName);
XmlFile.SavaConfig(transactNo.ToString(), null, attributeFileName);
}
}
InitPackageStart(true);
}
private void btnPackageStart_Click(object sender, EventArgs e)
{
if (lpPackage.ItemIndex < 0)
{
IRAPMessageBox.Instance.ShowInformation("请选择包装规格", caption);
return;
}
InitPackageStart(false);
InitPackageLocation();
}
private void btnRePrint_Click(object sender, EventArgs e)
{
if (ft == null)
{
XtraMessageBox.Show("请将光标定位在您需要重新打印的标签文本框内!", "系统提示", MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
ft.Focus();
if (ft.Name == edtBoxSN.Name)
{
string boxSN = edtBoxSN.Text.Trim().ToString();
if (string.IsNullOrEmpty(boxSN))
{
XtraMessageBox.Show("小包装序列号为空!请选择或输入您需要进行重新打印的标签序列号!",
"系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
ft = null;
return;
}
if (!string.IsNullOrEmpty(OutputStr))
PrintLabel(objPackageType.T117LabelID_Box, boxSN, OutputStr);
}
else
if (ft.Name == edtCartonSN.Name)
{
string cartonSN = edtCartonSN.Text.Trim().ToString();
if (string.IsNullOrEmpty(cartonSN))
{
XtraMessageBox.Show("大包装序列号为空!请选择或输入您需要进行重新打印的标签序列号!",
"系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
ft = null;
return;
}
//if (!string.IsNullOrEmpty(OutputStr))
//PrintLabel(objPackageType.T117LabelID_Carton, cartonSN, OutputStr);
}
else
if (ft.Name == edtPalletLayerSN.Name)
{
string palletLayerSN = edtPalletLayerSN.Text.Trim().ToString();
if (string.IsNullOrEmpty(palletLayerSN))
{
XtraMessageBox.Show("托层序列号为空!请选择或输入您需要进行重新打印的标签序列号!",
"系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
ft = null;
return;
}
//if (!string.IsNullOrEmpty(OutputStr))
//PrintLabel(objPackageType.T117LabelID_Layer, palletLayerSN, OutputStr);
}
ft = null;
}
private void frmProductPackage_FormClosing(object sender, FormClosingEventArgs e)
{
Options.OptionChanged -= Options_OptionChanged;
Options.btnSwitch.Enabled = true;
}
private void frmProductPackage_KeyDown(object sender, KeyEventArgs e)
{
if ((!e.Alt) && !e.Control)
{
switch (e.KeyCode)
{
case Keys.F4:
if (btnPackageStart.Enabled)
{
btnPackageStart.PerformClick();
}
break;
case Keys.F5:
if (btnPackageFinish.Enabled)
{
btnPackageFinish.PerformClick();
}
break;
case Keys.F6:
if (btnRePrint.Enabled)
{
btnRePrint.PerformClick();
}
break;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
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.Navigation;
using System.Windows.Shapes;
namespace ShapesGraphics.Views.Templates
{
/// <summary>
/// Логика взаимодействия для CreateShapeBaseParams.xaml
/// </summary>
public partial class CreateShapeBaseParamsTemplate : UserControl
{
public CreateShapeBaseParamsTemplate()
{
InitializeComponent();
}
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (sender is TextBox textBox)
{
Regex regex = new Regex(@"(^-$)|(^-?\d+$)");
bool isValid = regex.IsMatch(textBox.Text) || string.IsNullOrEmpty(textBox.Text);
if (textBox.Text.Length > 0)
{
if (!regex.IsMatch(e.Text))
{
isValid = false;
}
if (e.Text == "-")
{
isValid = false;
}
}
e.Handled = !isValid;
}
else
{
e.Handled = false;
}
}
}
}
|
using ApplicationCore.Entities;
using Microsoft.EntityFrameworkCore;
namespace Infrastructure.Data.EntityConfigurations
{
public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Product> builder)
{
builder.HasKey(o => o.Id);
builder.Property<string>(o => o.Title).IsRequired(true);
builder.Property<string>(o => o.Description).IsRequired(false);
builder.Property<decimal>(o => o.Price).IsRequired().HasColumnType("decimal(8,2)");
builder.ToTable("Product", "dom");
}
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Poker;
using System.Collections.Generic;
namespace PokerTests
{
[TestClass]
public class HandToStringTests
{
[TestMethod]
public void PokerTestToStringWithNoCards()
{
Hand hand = new Hand(new List<ICard>());
string result = hand.ToString();
Assert.AreEqual(string.Empty, result);
}
[TestMethod]
public void PokerTestToStringWithOneCardTenSpades()
{
Card tenSpades = new Card(CardFace.Ten, CardSuit.Spades);
Hand hand = new Hand(new List<ICard>{ tenSpades });
string result = hand.ToString();
Assert.AreEqual("10♠", result);
}
[TestMethod]
public void PokerTestToStringWithFiveCards()
{
Hand hand = new Hand(new List<ICard>
{
new Card(CardFace.Seven, CardSuit.Diamonds),
new Card(CardFace.Ace, CardSuit.Hearts),
new Card(CardFace.Two, CardSuit.Clubs),
new Card(CardFace.Queen, CardSuit.Spades),
new Card(CardFace.Ten, CardSuit.Spades)
});
string result = hand.ToString();
Assert.AreEqual("7♦ A♥ 2♣ Q♠ 10♠", result);
}
[TestMethod]
public void PokerTestToStringWithSameCards()
{
Hand hand = new Hand(new List<ICard>
{
new Card(CardFace.Ten, CardSuit.Spades),
new Card(CardFace.Ten, CardSuit.Spades)
});
string result = hand.ToString();
Assert.AreEqual("10♠ 10♠", result);
}
}
}
|
using System.ComponentModel;
using Phenix.Core;
using Phenix.Core.Workflow;
namespace Phenix.Workflow.Activities
{
/// <summary>
/// 适用于特定自定义活动(这些活动使用 Execute 方法实现执行逻辑,该方法具有对运行时功能的完全访问权限)的抽象基类
/// </summary>
public abstract class NativeActivity : System.Activities.NativeActivity, IActivity
{
/// <summary>
/// 初始化
/// </summary>
protected NativeActivity()
: base()
{
DescriptionAttribute descriptionAttribute = AppUtilities.GetFirstCustomAttribute<DescriptionAttribute>(this.GetType());
if (descriptionAttribute != null)
DisplayName = descriptionAttribute.Description;
}
}
/// <summary>
/// 适用于特定自定义活动(这些活动使用 Execute 方法实现执行逻辑,该方法具有对运行时功能的完全访问权限)的抽象基类
/// </summary>
public abstract class NativeActivity<TResult> : System.Activities.NativeActivity<TResult>, IActivity
{
/// <summary>
/// 初始化
/// </summary>
protected NativeActivity()
: base()
{
DescriptionAttribute descriptionAttribute = AppUtilities.GetFirstCustomAttribute<DescriptionAttribute>(this.GetType());
if (descriptionAttribute != null)
DisplayName = descriptionAttribute.Description;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestTask
{
class Program
{
static double[] ChangeArray (double[] arr, int i1) // Метод выбрасывает из массива чисел те числа, с которыми были отработаны умножение и деление
{
for (int i = i1; i < arr.Length - 1; i++)
{
arr[i] = arr[i + 1];
}
Array.Resize(ref arr, arr.Length - 1);
return arr;
}
static char[] ChangeArray(char[] arr, int i1) // Метод выбрасывает из массива операций отработанные умножение и деление
{
for (int i = i1; i < arr.Length - 1; i++)
{
arr[i] = arr[i + 1];
}
Array.Resize(ref arr, arr.Length - 1);
return arr;
}
static string MainLogic(string expression) // Метод разбивает строку с учетом скобок
{
int counter = 0;
for (int i = 0; i < expression.Length; i++) // Проверяем, остались ли в строке какие-то действия, или так уже осталось только число-ответ
{
int tmp = Convert.ToInt32(expression[i]);
if ((tmp >= 48 && tmp <= 57) || tmp == 44) // Увеличиваем счетчик каждый раз когда символ является числом или точкой (для вещественных чисел)
counter++;
}
if ((counter == expression.Length) || expression[0] == '-') // Если счетчик совпадает с длиной строки или если строка начинается с минуса - значит результат найден
return expression;
string tmpexpression = null; // строка, в которую будет записыватся содержимое скобок
int counter_open = 0; // счетчик открывающих скобок
int counter_close = 0; // счетчик закрывающих скобок
for (int i = 0; i < expression.Length; i++)
{
if (expression[i] == '(')
counter_open++;
if (expression[i] == ')')
counter_close++;
if (counter_open != 0)
tmpexpression += expression[i]; // записываем в новую строку содержимое скобок
if ((counter_open == counter_close) && counter_open != 0)
break;
}
if (counter_open == 0)
tmpexpression = expression;
expression = expression.Replace(tmpexpression,Arifmetics(tmpexpression)); // заменяем содержимое скобок и сами скобки результатом вычислений
return MainLogic(expression);
}
static string Arifmetics(string expression) // метод считает операции + - * /
{
if (expression[0] == '(') // Этот блок удаляет из строки крайние скобки
{
string tmpexpression = null;
for (int i = 1; i < expression.Length - 1; i++)
{
tmpexpression += expression[i];
}
expression = tmpexpression;
}
int counter = 0;
for (int i = 0; i < expression.Length; i++) // Проверяем, есть ли в строке еще скобки
{
if (expression[i] == '(')
counter++;
}
if (counter > 0)
expression = MainLogic(expression); // Если скобки еще остались, вызываем метод, который их "раскрывает"
char[] symbols = { '+', '-', '*', '/' };
string[] numbers = expression.Split(symbols); // Выделяем из выражения все числа
for (int i = 0; i < numbers.Length; i++) // Удаляем из строкового массива чисел все пустые строки
{
if (numbers[i] == "")
{
if (i < numbers.Length - 1)
{
for (int j = i; j < numbers.Length - 1; j++)
{
numbers[j] = numbers[j + 1];
}
i--;
}
Array.Resize(ref numbers, numbers.Length - 1);
}
}
double[] doubleNumbers = new double[numbers.Length];
for (int i = 0; i < doubleNumbers.Length; i++) // Переводим все числа из строкового массива в интовый
{
doubleNumbers[i] = Convert.ToDouble(numbers[i]);
}
char[] operations = new char[0];
for (int i = 0; i < expression.Length; i++) // Записываем все действия в массив символов
{
int tmp = Convert.ToInt32(expression[i]);
if ((tmp >= 40 && tmp <= 43) || (tmp == 45) || (tmp == 47))
{
Array.Resize(ref operations, operations.Length + 1);
operations[operations.Length - 1] = Convert.ToChar(tmp);
}
}
for (int i = 0; i < operations.Length; i++) // Ищем в массиве действий умножение и деление, и выполняем их
{
if ((operations[i] == '*') || (operations[i] == '/'))
{
if (operations[i] == '*')
doubleNumbers[i] *= doubleNumbers[i + 1];
else
doubleNumbers[i] /= doubleNumbers[i + 1];
doubleNumbers = ChangeArray(doubleNumbers, i + 1); // Вызываем метод, который удаляет из массива чисел отработанный элемент
operations = ChangeArray(operations, i); // Вызываем метод, котороый удаляет из массива действий отработанное умножение или деление
}
else
continue;
}
double result = doubleNumbers[0];
for (int i = 0; i < operations.Length; i++) // Считаем сложение и вычитание
{
switch (operations[i])
{
case '+':
result += doubleNumbers[i + 1];
break;
case '-':
result -= doubleNumbers[i + 1];
break;
}
}
return Convert.ToString(result);
}
static void Main(string[] args)
{
string expression = null;
for (bool change = true; change; ) // Проверка выражения на корректность
{
change = false;
Console.Write("Введите математическое выражение: ");
expression = Console.ReadLine();
for (int i = 0; i < expression.Length; i++)
{
int tmp = Convert.ToInt32(expression[i]);
if (!((tmp >= 40 && tmp <= 43) || (tmp == 45) || (tmp >= 47 && tmp <= 57))) // Проверка на сторонние символы
{
Console.WriteLine("ОШИБКА! В вашем выражении присутствует символ {0}, повторите попытку", Convert.ToChar(tmp));
change = true;
}
if ((i == 0 && expression[i] == '-') || (expression[i] == '-' && expression[i - 1] == '(')) // Проверка на наличие отрицательных чисел
{
Console.WriteLine("ОШИБКА! Извините, программа не работает с отрицательными числами: -{0}", expression[i + 1]);
change = true;
}
if (i > 0)
{
if ((expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/') &&
(expression[i - 1] == '+' || expression[i - 1] == '-' || expression[i - 1] == '*' || expression[i - 1] == '/')) // Проверка на действия
{
Console.WriteLine("ОШИБКА! В вашем выражении два арифметических действия записаны рядом: {0}{1}", expression[i - 1], expression[i]);
change = true;
}
}
}
int counter_open = 0; // Счетчик открывающих скобок
int counter_close = 0; // Счетчик закрывающих скобок
int counter_error = 0; // Счетчик ошибок (для того чтоб не дублировать одинаковые ошибки)
for (int i = 0; i < expression.Length; i++)
{
if (expression[i] == '(')
counter_open++;
if (expression[i] == ')')
counter_close++;
if ((counter_close > 0) && (counter_open == 0) && (counter_error == 0)) // Проверка на правильную последовательность скобок
{
Console.WriteLine("ОШИБКА! Вы начали закрывать скобки, не успев их открыть");
change = true;
counter_error++;
}
if ((counter_open < counter_close) && (counter_error == 0))
{
Console.WriteLine("ОШИБКА! В ваше выражении закрывающих скобок больше, чем открывающих"); // Проверка на количество скобок
change = true;
counter_error++;
}
}
if (counter_open > counter_close)
{
Console.WriteLine("ОШИБКА! Где-то забыли закрыть скобки"); // Проверка на количество скобок
change = true;
}
}
Console.WriteLine("{0} = {1}", expression, MainLogic(expression));
}
}
}
|
//
// DataContextProviderBase.cs
//
// Author:
// nofanto ibrahim <nofanto.ibrahim@gmail.com>
//
// Copyright (c) 2011 sejalan
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sejalan.Framework.Provider;
using System.Configuration;
using DbLinq.Data.Linq;
namespace Sejalan.Framework.Data.DbLinq
{
/// <summary>
/// Base class for all DataContextProvider
/// </summary>
public abstract class DataContextProviderBase :ProviderBase
{
public string ConnectionString { get{return ConfigurationManager.ConnectionStrings[ this.Parameters["connectionStringName"]].ConnectionString;}}
public string SchemaName {get{return this.Parameters["schemaName"];}}
public string DatabaseId { get { return this.Parameters["databaseId"]; } }
protected DataContextProviderBase()
{
}
/// <summary>
/// Gets the <see cref="DataContext"/>.
/// </summary>
/// <value>The data context.</value>
public DataContext DataContext
{
get
{
return GetDataContext(this.ConnectionString);
}
}
/// <summary>
/// When overriden in derived class, gets the <see cref="DataContext"/>, using supplied connection string.
/// </summary>
/// <param name="connectionString">The connection string.</param>
/// <returns></returns>
protected abstract DataContext GetDataContext(string connectionString);
}
}
|
using Uintra.Core.Member.Models;
namespace Uintra.Core.Member.Profile.Models
{
public class ProfileViewModel
{
public string Photo { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public int? PhotoId { get; set; }
public string AllowedMediaExtensions { get; set; }
public string Department { get; set; }
public string Email { get; set; }
public MemberViewModel EditingMember { get; set; }
}
} |
using System;
namespace GitTFS_Migration.Application
{
static class GitTFS_Migration
{
[STAThread]
static void Main()
{
CompositionRoot.Wire(new ApplicationModule());
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
System.Windows.Forms.Application.Run(CompositionRoot.Resolve<MainForm>());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using KartObjects;
using System.Reflection;
using System.Data;
namespace KartExchangeEngine
{
public class Exchange1C_CSV : FileExchangeRelationJob
{
public Exchange1C_CSV(AbstractFlagMonitor flagMonitor)
: base(flagMonitor)
{
WorkingDir = flagMonitor.DirName;
}
public override string FriendlyName
{
get
{
return "Базовый обмен 1С CSV";
}
}
protected override void DoImport(List<string> DataList)
{
WriteLog("Начало процесса обмена");
DateTime dt = DateTime.Now;
int counter = 0;
foreach (var FileName in DataList)
{
bool wasError = false;
if (!Saver.DataContext.TranIsRunning)
Saver.DataContext.BeginTransaction();
using (StreamReader sr = new StreamReader(FlagMonitor.DirName + @"\" + FileName, Encoding.GetEncoding(1251)))
{
while (!sr.EndOfStream)
{
string st = sr.ReadLine();
string[] starr = st.Split(';');
List<RelationEntity> reList = (from d in RelationDesc.RelationEntities where d.refName.ToUpper() == starr[0].ToUpper() select d).ToList() ?? new List<RelationEntity>();
foreach (RelationEntity r in reList)
try
{
Entity entity = (Entity)Activator.CreateInstance(Type.GetType("KartExchangeEngine." + r.EntityName));
ProceedEntityRelationData(starr, r, entity);
}
catch (Exception e)
{
WriteLog("Ошибка обработки строки " + st + ":" + e.Message);
wasError = true;
}
counter++;
if (counter % 100 == 0)
WriteLog("Обработано " + counter +" записей");
if (counter % 5000 == 0)
{
if (Saver.DataContext.TranIsRunning)
Saver.DataContext.CommitTransaction();
Saver.DataContext.BeginTransaction();
WriteLog("Подтверждение транзакции");
}
}
TimeSpan ts=DateTime.Now-dt;
WriteLog("Обработан файл " + FileName +" за "+ts.Hours+":"+ts.Minutes+":"+ts.Seconds);
if (Saver.DataContext.TranIsRunning)
Saver.DataContext.CommitTransaction();
}
if (wasError)
MoveFileToErrorDir(FileName);
}
MoveFilesToCompleteDir(DataList);
DataList.Clear();
}
private void ProceedEntityRelationData(string[] starr, RelationEntity relationEntity, Entity entity)
{
foreach (KeyValuePair<string, string> pair in relationEntity.RelationRecords)
{
//Подключаем рефлексию по свойствам
foreach (PropertyInfo pi in entity.GetType().GetProperties())
{
if (pi.Name.ToUpper() == pair.Key.ToUpper())
if (starr[Int32.Parse(pair.Value)] != "")
{
if (pi.PropertyType == typeof(DateTime))
pi.SetValue(entity, Convert.ToDateTime(starr[Int32.Parse(pair.Value)]), null);
else
if (pi.PropertyType == typeof(Decimal))
pi.SetValue(entity, Convert.ToDecimal(starr[Int32.Parse(pair.Value)].Replace(",", decimalSeparator).Replace(".", decimalSeparator)), null);
else
if (pi.PropertyType == typeof(Int32))
pi.SetValue(entity, Convert.ToInt32(starr[Int32.Parse(pair.Value)]), null);
else
pi.SetValue(entity, starr[Int32.Parse(pair.Value)], null);
}
}
}
try
{
if (entity is ImportGoodGroupCSV)
Saver.SaveToDb<ImportGoodGroupCSV>(entity as ImportGoodGroupCSV);
if (entity is ImportGoodCSV)
Saver.SaveToDb<ImportGoodCSV>(entity as ImportGoodCSV);
if (entity is ImportBarcodeCSV)
Saver.SaveToDb<ImportBarcodeCSV>(entity as ImportBarcodeCSV);
if (entity is ImportPriceListCSV)
{
//Saver.DataContext.ExecuteNonQuery(" insert into TMP_IMPORTPRICECSV (PRICENAME, GOODCODE, PRICE, PERIODDATE) values('" + (entity as ImportPriceListCSV).PriceName + "'," + (entity as ImportPriceListCSV).GoodCode + "," + (entity as ImportPriceListCSV).Price + ",'" + (entity as ImportPriceListCSV).PeriodDate.ToString("dd.MM.yyyy") + "')");
Saver.SaveToDb<ImportPriceListCSV>(entity as ImportPriceListCSV);
}
if (entity is ImportSupplierCSV)
Saver.SaveToDb<ImportSupplierCSV>(entity as ImportSupplierCSV);
if (entity is ImportStoreCSV)
Saver.SaveToDb<ImportStoreCSV>(entity as ImportStoreCSV);
if (entity is ImportCustomerCSV)
Saver.SaveToDb<ImportCustomerCSV>(entity as ImportCustomerCSV);
}
catch (Exception e)
{
WriteLog("Ошибка обработки записи " + e.Message);
}
}
public override void DoExport(List<string> DataList)
{
WriteLog("Событие экспорта ");
DataTable dt2 = new DataTable();
Loader.DataContext.Fill("select * from v_exportdocs", ref dt2);
SaveToCSV(dt2, FlagMonitor.DirName + @"\" + "doc1.exc");
DataTable dt3 = new DataTable();
Loader.DataContext.Fill("select * from v_exportdocspec", ref dt3);
SaveToCSV(dt3, FlagMonitor.DirName + @"\" + "doc1.exc");
File.Delete((FlagMonitor as FileMaskMonitor).DirName+@"\"+(FlagMonitor as FileMaskMonitor).ExportFileMaskFlag);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace WebsiteManagerPanel.Framework.Extensions
{
public static class PrimitiveTypeExtensions
{
public static byte ToByte(this object value)
{
bool result = Byte.TryParse(value.ToString(), out var val);
return (result) ? val : Convert.ToByte(0);
}
public static short ToInt16(this object value)
{
bool result = Int16.TryParse(value.ToString(), out var val);
return (result) ? val : Convert.ToInt16(0);
}
public static int ToInt32(this object value)
{
bool result = Int32.TryParse(value.ToString(), out var val);
return (result) ? val : 0;
}
public static long ToInt64(this object value)
{
bool result = Int64.TryParse(value.ToString(), out var val);
return (result) ? val : 0L;
}
public static float ToFloat(this object value)
{
bool result = float.TryParse(value.ToString(), out var val);
return (result) ? val : 0.0F;
}
public static double ToDouble(this object value)
{
bool result = double.TryParse(value.ToString(), out var val);
return (result) ? val : 0.0D;
}
public static decimal ToDecimal(this object value)
{
bool result = Decimal.TryParse(value.ToString(), out var val);
return (result) ? val : 0.0M;
}
public static bool ToBool(this object value)
{
bool result = bool.TryParse(value.ToString(), out var val);
return (result) && val;
}
public static object ToType<T>(this object obj, T type)
{
//create instance of T type object:
var tmp = Activator.CreateInstance(Type.GetType(type.ToString()));
//loop through the properties of the object you want to covert:
foreach (PropertyInfo pi in obj.GetType().GetProperties())
{
try
{
//get the value of property and try
//to assign it to the property of T type object:
tmp.GetType().GetProperty(pi.Name).SetValue(tmp, pi.GetValue(obj, null), null);
}
catch
{
// ignored
}
}
//return the T type object:
return tmp;
}
public static Color ToColor(this string argb)
{
argb = argb.Replace("#", "");
byte a = Convert.ToByte("ff", 16);
byte pos = 0;
if (argb.Length == 8)
{
a = Convert.ToByte(argb.Substring(pos, 2), 16);
pos = 2;
}
byte r = Convert.ToByte(argb.Substring(pos, 2), 16);
pos += 2;
byte g = Convert.ToByte(argb.Substring(pos, 2), 16);
pos += 2;
byte b = Convert.ToByte(argb.Substring(pos, 2), 16);
return Color.FromArgb(a, r, g, b);
}
/// <summary>
/// IsNullOrEmpty
/// </summary>
/// <param name="theString"></param>
/// <returns></returns>
public static bool IsNotNullOrEmpty(this string theString)
{
return !string.IsNullOrEmpty(theString);
}
/// <summary>
/// IsNullOrEmptyOrWhiteSpace
/// </summary>
/// <param name="theString"></param>
/// <returns></returns>
public static bool IsNullOrEmptyOrWhiteSpace(this string theString)
{
return string.IsNullOrEmpty(theString) || theString.Trim() == string.Empty;
}
/// <summary>
/// Is strong Password
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static bool IsStrongPassword(this string s)
{
bool isStrong = Regex.IsMatch(s, @"[\d]");
if (isStrong) isStrong = Regex.IsMatch(s, @"[a-z]");
if (isStrong) isStrong = Regex.IsMatch(s, @"[A-Z]");
if (isStrong) isStrong = Regex.IsMatch(s, @"[\s~!@#\$%\^&\*\(\)\{\}\|\[\]\\:;'?,.`+=<>\/]");
if (isStrong) isStrong = s.Length > 7;
return isStrong;
}
}
}
|
using System;
namespace ProxySample
{
class Program
{
static void Main(string[] args)
{
IInternet internet = new ProxyInternet();
try
{
internet.ConnectTo("geeks.org");
internet.ConnectTo("abc.com");
}
catch (Exception e)
{
Console.WriteLine($"{e.StackTrace}");
//throw;
}
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using BlazorShared.Models.Patient;
using Microsoft.Extensions.Logging;
namespace FrontDesk.Blazor.Services
{
public class PatientService
{
private readonly HttpService _httpService;
private readonly ILogger<PatientService> _logger;
public PatientService(HttpService httpService, ILogger<PatientService> logger)
{
_httpService = httpService;
_logger = logger;
}
public async Task<PatientDto> CreateAsync(CreatePatientRequest patient)
{
return (await _httpService.HttpPostAsync<CreatePatientResponse>("patients", patient)).Patient;
}
public async Task<PatientDto> EditAsync(UpdatePatientRequest patient)
{
return (await _httpService.HttpPutAsync<UpdatePatientResponse>("patients", patient)).Patient;
}
public Task DeleteAsync(int patientId)
{
return _httpService.HttpDeleteAsync<DeletePatientResponse>("patients", patientId);
}
public async Task<PatientDto> GetByIdAsync(int patientId)
{
return (await _httpService.HttpGetAsync<GetByIdPatientResponse>($"patients/{patientId}")).Patient;
}
public async Task<List<PatientDto>> ListPagedAsync(int pageSize)
{
_logger.LogInformation("Fetching patients from API.");
return (await _httpService.HttpGetAsync<ListPatientResponse>($"patients")).Patients;
}
public async Task<List<PatientDto>> ListAsync(int clientId)
{
_logger.LogInformation("Fetching patients from API.");
return (await _httpService.HttpGetAsync<ListPatientResponse>($"patients?ClientId={clientId}")).Patients;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DungeonestDark
{
class Program
{
static void Main(string[] args)
{
int health = 100;
int coins = 0;
List<string> dungeonsRooms = Console.ReadLine()
.Split('|')
.ToList();
//Console.WriteLine(string.Join(" ",dungeonsRooms[0]));
for(int i=0;i<dungeonsRooms.Count;i++)
{
List<int> Room = new List<string>(dungeonsRooms)
.Select(int.Parse)
.ToList();
if(dungeonsRooms[i]=="potion")
{
health += Room[1];
if(health>100)
{
health = 100;
Console.WriteLine("$Your current health: {health} hp.");
}
}
else if(dungeonsRooms[i]=="chest")
{
int foundedCoins = Room[1];
Console.WriteLine("You found {foundedCoins} coins.");
}
else
{
string monster = dungeonsRooms[i];
int attackOfMonster = Room[1];
health = health - attackOfMonster;
if(health<=0)
{
Console.WriteLine($"You died! Killed by {monster}.");
}
else if(health>0)
{
Console.WriteLine($"You slayed {monster}.");
Console.WriteLine($"Best room: {i}");
}
}
}
string Input = Console.ReadLine();
if(string.IsNullOrEmpty(Input))
{
if(health>0)
{
Console.WriteLine($"You've made it!");
Console.WriteLine($"Coins: {coins}");
Console.WriteLine($"Health: {health}");
}
}
}
}
}
|
using Pe.Stracon.SGC.Aplicacion.TransferObject.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual
{
/// <summary>
/// Representa el objeto request de Plantilla Párrafo Variable
/// </summary>
/// <remarks>
/// Creación : GMD 20150529 <br />
/// Modificación : <br />
/// </remarks>
public class PlantillaParrafoVariableRequest : Filtro
{
/// <summary>
/// Código de Plantilla Párrafo Variable
/// </summary>
public string CodigoPlantillaParrafoVariable { get; set; }
/// <summary>
/// Código de Plantilla Párrafo
/// </summary>
public string CodigoPlantillaParrafo { get; set; }
/// <summary>
/// Código de Variable
/// </summary>
public string CodigoVariable { get; set; }
/// <summary>
/// Orden
/// </summary>
public Int16? Orden { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SentimentAnalysis.UserControls
{
public partial class SentinentReport : UserControl
{
public int TweetCount { get; set; }
public int Analysed { get; set; }
public int Positive { get; set; }
public int Negative { get; set; }
public SentinentReport()
{
InitializeComponent();
}
private void SentinentReport_Load(object sender, EventArgs e)
{
}
public void sLoad()
{
lblAnalysed.Text = Analysed.ToString();
lblNegative.Text = Negative.ToString();
lblPositive.Text = Positive.ToString();
lblTweetCount.Text = TweetCount.ToString();
}
}
}
|
using System;
namespace TY.SPIMS.POCOs
{
public class PurchasePaymentDisplayModel
{
public string VoucherNumber { get; set; }
public DateTime Date { get; set; }
public decimal Amount { get; set; }
}
}
|
//**********************************************************************************
//* Copyright (C) 2007,2016 Hitachi Solutions,Ltd.
//**********************************************************************************
#region Apache License
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
//**********************************************************************************
//* クラス名 :OAuth2AndOIDCEnum
//* クラス日本語名 :OAuth2 / OIDCで使用する列挙型クラス
//*
//* 作成者 :生技 西野
//* 更新履歴 :
//*
//* 日時 更新者 内容
//* ---------- ---------------- -------------------------------------------------
//* 2019/02/06 西野 大介 新規作成
//**********************************************************************************
namespace Touryo.Infrastructure.Framework.Authentication
{
/// <summary>OAuth2 / OIDCで使用する列挙型クラス</summary>
public static class OAuth2AndOIDCEnum
{
#region ResponseMode
/// <summary>ResponseMode</summary>
public enum ResponseMode : int
{
/// <summary>query</summary>
query,
/// <summary>fragment</summary>
fragment,
/// <summary>form_post</summary>
form_post
}
#endregion
#region AuthMethods
/// <summary>AuthMethods</summary>
public enum AuthMethods : int
{
/// <summary>client_secret_basic</summary>
client_secret_basic,
/// <summary>client_secret_post</summary>
client_secret_post,
/// <summary>client_secret_jwt</summary>
client_secret_jwt,
/// <summary>private_key_jwt</summary>
private_key_jwt,
/// <summary>tls_client_auth</summary>
tls_client_auth
}
#endregion
#region ClientMode
/// <summary>ClientMode</summary>
public enum ClientMode : int
{
/// <summary>normal</summary>
normal,
/// <summary>fapi1</summary>
fapi1,
/// <summary>fapi2</summary>
fapi2
}
#endregion
}
}
|
using Common.Business;
using Common.Log;
using Contracts.MLA;
using Entity;
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Threading.Tasks;
namespace Clients.Addendum
{
/// <summary>
/// Proxy class for asynchronous update operations.
/// </summary>
[CallbackBehavior(AutomaticSessionShutdown = true, ConcurrencyMode = ConcurrencyMode.Reentrant,
UseSynchronizationContext = false, MaxItemsInObjectGraph = Int32.MaxValue,
IncludeExceptionDetailInFaults = Constants.IncludeExceptionDetailInFaults,
TransactionTimeout = "00:30:00")]
public class AddendumUpdateAsyncProxy : DuplexClientBase<IMLAAsyncUpdateService>, IMLAAsyncUpdateService
{
#region Constructors
/// <summary>
/// Creates a new instance of AddendumUpdateAsyncProxy.
/// </summary>
/// <param name="callbackInstance">The instance context for callbacks.</param>
/// <param name="endpoint">The endpoint to use.</param>
public AddendumUpdateAsyncProxy(InstanceContext callbackInstance, ServiceEndpoint endpoint)
: base(callbackInstance, endpoint)
{
//Set inner timeouts to prevent the system from hanging during a load.
InnerChannel.OperationTimeout = TimeSpan.FromMinutes(30);
InnerDuplexChannel.OperationTimeout = TimeSpan.FromMinutes(30);
InnerChannel.AllowOutputBatching = true;
InnerDuplexChannel.AllowOutputBatching = true;
BindingElementCollection bec = base.Endpoint.Binding.CreateBindingElements();
TcpTransportBindingElement tcp = bec.Find<TcpTransportBindingElement>();
tcp.ChannelInitializationTimeout = TimeSpan.FromMinutes(1);
}
#endregion
#region Public Methods
/// <summary>
/// Cancels the Save operation.
/// </summary>
public void CancelSaveAddendumAsync()
{
try
{
Channel.CancelSaveAddendumAsync();
}
catch (CommunicationObjectAbortedException)
{
Logging.Log("Cancel request was aborted", "Addendum.Async.Update.Service", "CancelSaveAddendumAsync");
}
}
/// <summary>
/// Cancels the Update operation.
/// </summary>
public void CancelUpdateAddendaAsync()
{
try
{
Channel.CancelUpdateAddendaAsync();
}
catch (CommunicationObjectAbortedException)
{
Logging.Log("Cancel request was aborted.", "Addendum.Async.Update.Service", "CancelUpdateAddendaAsync");
}
}
/// <summary>
/// Saves the requested addenda.
/// </summary>
/// <param name="userState">The MLATableLoader to use.</param>
/// <returns>True if successful; otherwise false.</returns>
public Task<bool> SaveAddendumAsync(object userState)
{
try
{
return Channel.SaveAddendumAsync(userState);
}
catch (Exception e)
{
Logging.Log(e, "AddendumUpdateAsyncProxy", "SaveAddendumAsync");
return null;
}
}
/// <summary>
/// Sends a portion of the requested IDs to the server.
/// </summary>
/// <param name="ids">The IDs to send.</param>
/// <remarks>This method is necessary because WCF cannot handle large chunks of data (e.g., 10000 IDs) all at once.
/// The time it takes the client to send all of the list to the server is not perceptible to the user.</remarks>
public void SendNextChunk(List<int> ids)
{
Channel.SendNextChunk(ids);
}
/// <summary>
/// Sends a portion of the requested addenda to the server.
/// </summary>
/// <param name="addenda">The addenda to send.</param>
/// <remarks>This method is necessary because WCF cannot handle large chunks of data (e.g., 10000 IDs) all at once.
/// The time it takes the client to send all of the list to the server is not perceptible to the user.</remarks>
public void SendNextChunkAddenda(MLAAddendum[] addenda)
{
Channel.SendNextChunkAddenda(addenda);
}
/// <summary>
/// Sends a portion of the requested rights strings to the server.
/// </summary>
/// <param name="rights">The rights strings to send.</param>
/// <remarks>This method is necessary because WCF cannot handle large chunks of data (e.g., 10000 IDs) all at once.
/// The time it takes the client to send all of the list to the server is not perceptible to the user.</remarks>
public void SendNextChunkString(List<string> rights)
{
Channel.SendNextChunkString(rights);
}
/// <summary>
/// Updates the requested addenda asynchronously.
/// </summary>
/// <param name="userState">The MLATableLoader to use.</param>
/// <returns>True if successful; otherwise false.</returns>
public Task<bool> UpdateAddendaAsync(object userState)
{
try
{
return Channel.UpdateAddendaAsync(userState);
}
catch (Exception e)
{
Logging.Log(e, "AddendumUpdateAsyncProxy", "UpdateAddendaAsync");
return null;
}
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GodaddyWrapper.Responses
{
public class CloudImageActionListResponse
{
public CloudImageActionResponse Results { get; set; }
public PaginationResponse Pagination { get; set; }
}
}
|
using System;
namespace _01._Spring_Vacation_Trip
{
class Program
{
static void Main(string[] args)
{
int daysOfTheTrip = int.Parse(Console.ReadLine());
decimal budget = decimal.Parse(Console.ReadLine());
int countOfPeople = int.Parse(Console.ReadLine());
decimal fuelPerKm = decimal.Parse(Console.ReadLine());
decimal foodExpensesPerPerson = decimal.Parse(Console.ReadLine());
decimal priceForOneNightPerPerson = decimal.Parse(Console.ReadLine());
if (countOfPeople > 10)
{
priceForOneNightPerPerson *= 0.75m;
}
decimal currentExpenses = daysOfTheTrip * countOfPeople * (foodExpensesPerPerson + priceForOneNightPerPerson);
for (int i = 1; i <= daysOfTheTrip; i++)
{
decimal travelDistance = decimal.Parse(Console.ReadLine());
currentExpenses += travelDistance * fuelPerKm;
if (i % 3 == 0 || i % 5 == 0)
{
currentExpenses *= 1.4m;
}
if (i % 7 == 0)
{
currentExpenses -= currentExpenses/countOfPeople;
}
if (currentExpenses > budget)
{
Console.WriteLine($"Not enough money to continue the trip. You need {(currentExpenses - budget):f2}$ more.");
return;
}
}
Console.WriteLine($"You have reached the destination. You have {(budget - currentExpenses):f2}$ budget left.");
}
}
}
|
using DeMo.Models.model;
using System;
using System.Linq;
namespace DeMo.Models
{
public class LoginDAO
{
DADB db = new DADB();
// KIểm tra đăng nhập
public bool Login(String tk, String mk)
{
//dem so lan xuat hien tu databases
var rs = db.TaiKhoans.Count(x => x.TenTk == tk && x.MatKhau == mk);
if (rs > 0)
{
return true;
}
else
return false;
}
//lay các giá trị quyền truy cập của tài khoản
public String Role(String tk)
{
// String roles = db.TaiKhoans.SqlQuery("select Role from TaiKhoan where TenTk='@id' ", new SqlParameter("@id", tk)).ToString();
var r = from p in db.TaiKhoans where p.TenTk == tk select p;
String role = "";
foreach (TaiKhoan taiKhoan in r)
{
role = taiKhoan.Role.ToString();
}
return role;
}
//Lấy mã của tìa khoản MÃ Giáo Viên hoặc Mã Phụ Huynh
public String Ma(String tk)
{
String ma = "";
var r = from p in db.TaiKhoans where p.TenTk == tk select p;
int role = int.Parse(Role(tk));
if (role == 3)
{
foreach (TaiKhoan taikhoan in r)
{
ma = taikhoan.MaGV.ToString();
}
}
else if (role == 2)
{
foreach (TaiKhoan taikhoan in r)
{
ma = taikhoan.MaPH.ToString();
}
}
return ma;
}
//lấy mã học sinh
public String MaHS(String maph)
{
String MaHS = "";
var ma = (from m in db.PhuHuynhs where m.MaPH == maph select m).ToList();
foreach(PhuHuynh ph in ma)
{
MaHS = ph.MaHS;
}
return MaHS;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
public class DistanceTextEffect : MonoBehaviour {
private void OnEnable () {
transform.DOScale (new Vector3 (0.5f, 0.5f, 1), 0.2f).SetEase (Ease.Linear).OnComplete (() =>
transform.DOScale (Vector3.one, 0.3f).SetLoops (5, LoopType.Yoyo).OnComplete (() => transform.DOScale (Vector3.zero, 0.4f).OnComplete(() => transform.parent.gameObject.SetActive (false)))
);
}
} |
using Aurigma.GraphicsMill;
using Aurigma.GraphicsMill.AdvancedDrawing;
using Aurigma.GraphicsMill.AdvancedDrawing.Effects;
internal class PlainAndBoundedTextExample
{
private static void Main(string[] args)
{
DrawPlainAndBoundedText();
DrawMultilinePlainText();
}
/// <summary>
/// Draws plain and bounded texts with different parameters.
/// </summary>
private static void DrawPlainAndBoundedText()
{
using (var bitmap = new Bitmap(400, 250, PixelFormat.Format24bppRgb, new RgbColor(255, 255, 255, 255)))
using (var graphics = bitmap.GetAdvancedGraphics())
{
var brush = new SolidBrush(new RgbColor(0x41, 0x41, 0x41));
var dummyText = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras elementum quam ac nisi varius gravida. Mauris ornare, dolor et scelerisque volutpat, enim urna commodo odio, consequat fermentum sem arcu sit amet nisl. Aliquam tincidunt id neque in gravida. Mauris mollis est vulputate suscipit facilisis.";
var boundedTextRect = new System.Drawing.RectangleF(200f, 20f, 180f, 150f);
var texts = new Text[]
{
new PlainText("Horizontal", graphics.CreateFont("Times New Roman", 22f), brush)
{
Position = new System.Drawing.PointF(50f, 38f)
},
new PlainText("Vertical", graphics.CreateFont("Arial", 24f), brush)
{
Vertical = true,
Position = new System.Drawing.PointF(20f, 10f),
Effect = new Glow(new RgbColor(0x66, 0xaf, 0xe9), 5)
},
new BoundedText(dummyText, graphics.CreateFont("Verdana", 14f), brush)
{
Alignment = TextAlignment.Center,
Rectangle = boundedTextRect
}
};
foreach (var text in texts)
{
graphics.DrawText(text);
}
graphics.DrawRectangle(new Pen(new RgbColor(0x4e, 0xb5, 0xe6)), boundedTextRect);
bitmap.Save("../../../../_Output/PlainAndBoundedText.png");
}
}
/// <summary>
/// Draws multiline plain text.
/// </summary>
private static void DrawMultilinePlainText()
{
using (var bitmap = new Bitmap(600, 250, PixelFormat.Format24bppRgb, new RgbColor(255, 255, 255, 255)))
using (var graphics = bitmap.GetAdvancedGraphics())
{
var brush = new SolidBrush(new RgbColor(0x41, 0x41, 0x41));
var dummyText = @"Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Cras
elementum quam ac nisi varius gravida.
Mauris ornare, dolor et scelerisque volutpat, enim
urna commodo odio,
consequat fermentum sem arcu sit amet nisl.
Aliquam tincidunt id neque
in gravida. Mauris mollis est
vulputate suscipit facilisis.";
var text = new PlainText(dummyText, graphics.CreateFont("Verdana", 20f), brush)
{
Position = new System.Drawing.PointF(10f, 30f)
};
graphics.DrawText(text);
bitmap.Save("../../../../_Output/DrawMultilinePlainText.png");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TreasurePopupSetup : MonoBehaviour {
public Transform slotTransform;
public GameObject[] weapons;
public GameObject treasure;
public GameObject shield;
int randomInt;
DiamondsSetup diamonds;
WeaponPrefab weapon;
WeaponPanelOperator weaponPanelOperator;
ShieldPanel shieldPanel;
void Awake(){
LevelManager.popupON = true;
randomInt = Random.Range(1, 8);
if (randomInt == 1)
Instantiate(weapons[Random.Range(0, weapons.Length)], transform.position, Quaternion.identity, slotTransform);
if (randomInt == 2 || randomInt == 3){
Instantiate(shield, transform.position, Quaternion.identity, slotTransform);
shieldPanel = FindObjectOfType<ShieldPanel>();
}
if (randomInt != 1 && randomInt != 2 && randomInt != 3)
Instantiate(treasure, transform.position, Quaternion.identity, slotTransform);
weaponPanelOperator = FindObjectOfType<WeaponPanelOperator>();
}
void OnMouseDown(){
TakeTreasures();
LevelManager.popupON = false;
Destroy(gameObject);
}
void TakeTreasures(){
if (randomInt == 1){
weapon = GetComponentInChildren<WeaponPrefab>();
weaponPanelOperator.ChangeWeapon(weapon, weapon.weaponType);
}
if (randomInt == 2 || randomInt == 3)
shieldPanel.PlusShield();
if (randomInt != 1 && randomInt != 2 && randomInt != 3){
diamonds = FindObjectOfType<DiamondsSetup>();
DimondCounter.treasureCount += diamonds.treasureValue;
}
}
}
|
namespace DFC.ServiceTaxonomy.GraphSync.Enums
{
public enum ValidationScope
{
ModifiedSinceLastValidation,
AllItems
}
}
|
using System;
using System.Windows.Controls;
using System.Windows.Input;
namespace DameGUI.Components
{
/// <summary>
/// Interaction logic for PlayBar.xaml
/// </summary>
public partial class PlayBar : StackPanel
{
public PlayBar()
{
InitializeComponent();
pause.MouseDown += pause_MouseDown;
play.MouseDown += play_MouseDown;
}
public event EventHandler<ClickEventArgs> Clicked;
public void Set(ClickEventArgs.Actions action, bool trigger)
{
switch (action)
{
case ClickEventArgs.Actions.Pause:
pause.Visibility = System.Windows.Visibility.Visible;
//play.Visibility = System.Windows.Visibility.Collapsed;
if (Clicked != null && trigger) { this.Clicked(this, new ClickEventArgs(ClickEventArgs.Actions.Pause)); }
break;
case ClickEventArgs.Actions.Play:
pause.Visibility = System.Windows.Visibility.Collapsed;
//play.Visibility = System.Windows.Visibility.Visible;
if (Clicked != null && trigger) { this.Clicked(this, new ClickEventArgs(ClickEventArgs.Actions.Play)); }
break;
}
}
private void pause_MouseDown(object sender, MouseButtonEventArgs e)
{
Set(ClickEventArgs.Actions.Play, true);
}
private void play_MouseDown(object sender, MouseButtonEventArgs e)
{
Set(ClickEventArgs.Actions.Pause, true);
}
public class ClickEventArgs : EventArgs
{
public ClickEventArgs(Actions action)
{
this.Action = action;
}
public enum Actions { Pause, Play }
public Actions Action { get; set; }
}
}
} |
using FoodPricer.Core.Order.Beverage;
using FoodPricer.Core.Order.Dessert;
using FoodPricer.Core.Order.Meal;
using FoodPricer.Core.Order.MealPlan;
namespace FoodPricer.Core.Order.Offer.MealPlan
{
public class SandwichMaxMealPlan : IMealPlan
{
public double Price => 16;
public bool IsEligible(Order order)
{
return order.Meal is Sandwich && order.Beverage is LargeBeverage && order.Dessert is SpecialDessert;
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
namespace ClaimDi.DataAccess.Entity
{
public class Insurer
{
public string InsID { get; set; }
public string InsName { get; set; }
public string InsNameEn { get; set; }
public string InsOicCode { get; set; }
public string InsOicName { get; set; }
public string InsTel { get; set; }
public bool IsContact { get; set; }
public string Description { get; set; }
public string Logo { get; set; }
public bool IsActive { get; set; }
public int Sort { get; set; }
public int InsType { get; set; }
public DateTime? CreateDate { get; set; }
public DateTime? UpdateDate { get; set; }
public string CreateBy { get; set; }
public string UpdateBy { get; set; }
public virtual List<EmailConfig> EmailConfig { get; set; }
public virtual List<TemplateESlip> TemplateESlips { get; set; }
public virtual ConfigFeature ConfigFeature { get; set; }
}
public class InsurerConfig : EntityTypeConfiguration<Insurer>
{
public InsurerConfig()
{
// Table & Column Mappings
ToTable("Insurer");
Property(t => t.InsID).HasColumnName("Ins_id");
Property(t => t.InsName).HasColumnName("Ins_name").HasMaxLength(150);
Property(t => t.InsNameEn).HasColumnName("Ins_name_en").HasMaxLength(150);
Property(t => t.InsOicCode).HasColumnName("Ins_oic_code").HasMaxLength(5);
Property(t => t.InsOicName).HasColumnName("Ins_oic_name").HasMaxLength(150);
Property(t => t.InsType).HasColumnName("Ins_type");
Property(t => t.InsTel).HasColumnName("Ins_tel");
Property(t => t.IsContact).HasColumnName("isContact");
Property(t => t.Description).HasColumnName("description");
Property(t => t.Logo).HasColumnName("logo").HasMaxLength(250);
Property(t => t.IsActive).HasColumnName("isActive");
Property(t => t.Sort).HasColumnName("sort");
Property(t => t.CreateDate).HasColumnName("create_date");
Property(t => t.UpdateDate).HasColumnName("update_date");
Property(t => t.CreateBy).HasColumnName("create_by");
Property(t => t.UpdateBy).HasColumnName("update_by");
// Primary Key
HasKey(t => t.InsID);
HasMany(t => t.EmailConfig).WithRequired().HasForeignKey(m => m.InsId);
HasMany(t => t.TemplateESlips).WithRequired().HasForeignKey(m => m.InsId);
HasOptional(t => t.ConfigFeature).WithRequired();
}
}
} |
using EmberKernel.Services.Command.Parsers;
using System;
using System.Collections.Generic;
using System.Text;
namespace EmberKernel.Services.Command.Attributes
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
public class CommandHandlerAttribute: Attribute
{
public string Command { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class ChangeDirection : MonoBehaviour {
private float m_angle = 0;
// Update is called once per frame
void Update () {
m_angle += 0.05f;
float angle = 180f * Mathf.Sin(m_angle) / 5f;
Vector3 rot = transform.rotation.eulerAngles;
rot.x = angle;
transform.eulerAngles = rot;
}
}
|
using System;
using System.Data;
using System.Web;
using System.IO;
using System.Text;
using System.Data.Common;
using System.Data.SqlClient;
public class CRUD {
private SqlConnection CRUDconnection;
public CRUD() {
// database connection
CRUDconnection = new SqlConnection("user id=USER; password=PASSWORD; Data Source=SERVERNAME; database=DBNAME;");
}
public CRUD(string connectionString) {
// database connection
CRUDconnection = new SqlConnection(connectionString);
}
public bool Create(string tableName, string[] columnNames, string[] insertValues) {
string columnsString = " (";
string valuesString = " VALUES (";
string query = "INSERT INTO " + tableName;
string commar = ", ";
if (columnNames.Length != insertValues.Length) {
//check if the amount of columns and amount of values match. If not we'll return false without executing any sql.
//Console.WriteLine("Number of Columns and number of Values mismatch.");
return false;
}
//build the query
for (int i = 0; i < columnNames.Length; i++) {
if (i == columnNames.Length -1) {
commar = "";
}
columnsString += columnNames[i] + commar;
valuesString += "@" + columnNames[i] + commar;
}
//remove trailing commars
query += columnsString + ") ";
query += valuesString + ") ";
//open the connection
try {
CRUDconnection.Open();
SqlCommand CRUDcommand = new SqlCommand(query, CRUDconnection);
for (int i = 0; i < columnNames.Length; i++) {
CRUDcommand.Parameters.Add(new SqlParameter("@" + columnNames[i], insertValues[i]));
}
CRUDcommand.ExecuteNonQuery();
CRUDconnection.Close();
} catch (Exception e) {
//Console.WriteLine(e.ToString());
}
return true;
}
// read operations.
// 1. select *
// 2. select specified column
// 3. select specified columns
// 1.
public DataTable Read(string tableName) {
string query = "SELECT * FROM " + tableName;
return executeRead(query);
}
// 2.
public DataTable Read(string tableName, string columnName) {
string query = "SELECT " + columnName + " FROM " + tableName;
return executeRead(query);
}
// 3.
public DataTable Read(string tableName, string[] columnNames) {
string commar = ", ";
string query = "SELECT ";
for (int i = 0; i < columnNames.Length; i++) {
if (i == columnNames.Length -1) {
commar = "";
}
query += columnNames[i] + commar;
}
query += " FROM " + tableName;
return executeRead(query);
}
// Select specified columns where conditionColumns == conditionValues
public DataTable Read_Where(string tableName, string[] columnNames, string[] conditionColumns, string[] conditionValues) {
if (conditionColumns.Length != conditionValues.Length) {
//check if the amount of columns and amount of values match. If not we'll return null without executing any sql.
//Console.WriteLine("Number of Columns and number of Values mismatch.");
return null;
}
string commar = ", ";
string condition = "";
string query = "SELECT ";
for (int i = 0; i < columnNames.Length; i++) {
if (i == columnNames.Length -1) {
commar = "";
}
query += columnNames[i] + commar;
}
query += " FROM " + tableName + " WHERE ";
for (int i = 0; i < conditionColumns.Length; i++) {
condition += conditionColumns[i] + " = " + "@" + conditionColumns[i] + "Check";
if (i != conditionColumns.Length -1) {
condition += " AND ";
}
}
query += condition;
return executeRead(query, conditionColumns, conditionValues);;
}
// Select * where conditionColumns == conditionValues
public DataTable Read_Where(string tableName, string[] conditionColumns, string[] conditionValues) {
if (conditionColumns.Length != conditionValues.Length) {
//check if the amount of columns and amount of values match. If not we'll return null without executing any sql.
//Console.WriteLine("Number of Columns and number of Values mismatch.");
return null;
}
string columnsString = "";
string condition = "";
string query = "SELECT *";
query += " FROM " + tableName + " WHERE ";
for (int i = 0; i < conditionColumns.Length; i++) {
condition += conditionColumns[i] + " = " + "@" + conditionColumns[i] + "Check";
if (i != conditionColumns.Length -1) {
condition += " AND ";
}
}
query += condition;
return executeRead(query, conditionColumns, conditionValues);
}
public bool Update(string tableName, string[] columnNames, string[] insertValues, string[] conditionColumns, string[] conditionValues) {
string commar = ", ";
string condition = "";
string columnsString = " SET ";
string query = "UPDATE " + tableName;
if (columnNames.Length != insertValues.Length || conditionColumns.Length != conditionValues.Length) {
//check if the amount of columns and amount of values match. If not we'll return false without executing any sql.
//Console.WriteLine("Number of Columns and number of Values mismatch.");
return false;
}
//build the query
for (int i = 0; i < columnNames.Length; i++) {
if (i == columnNames.Length -1) {
commar = "";
}
columnsString += columnNames[i] + "=";
columnsString += "@" + columnNames[i] + commar;
}
query += columnsString + " WHERE ";
for (int i = 0; i < conditionColumns.Length; i++) {
condition += conditionColumns[i] + " = " + "@" + conditionColumns[i] + "Check";
if (i != conditionColumns.Length -1) {
condition += " AND ";
}
}
query += condition;
//open the connection
try {
CRUDconnection.Open();
SqlCommand CRUDcommand = new SqlCommand(query, CRUDconnection);
for (int i = 0; i < columnNames.Length; i++) {
CRUDcommand.Parameters.Add(new SqlParameter("@" + columnNames[i], insertValues[i]));
}
for (int i = 0; i < conditionColumns.Length; i++) {
CRUDcommand.Parameters.Add(new SqlParameter("@" + conditionColumns[i] + "Check", conditionValues[i]));
}
CRUDcommand.ExecuteNonQuery();
CRUDconnection.Close();
} catch (Exception e) {
//Console.WriteLine(e.ToString());
}
return true;
}
public bool Delete(string tableName, string condition) {
string query = "DELETE FROM" + tableName + " WHERE " + condition;
try {
CRUDconnection.Open();
SqlCommand CRUDcommand = new SqlCommand(query, CRUDconnection);
CRUDcommand.ExecuteNonQuery();
CRUDconnection.Close();
} catch (Exception e) {
//Console.WriteLine(e.ToString());
}
return true;
}
protected DataTable executeRead(string query) {
SqlDataReader CRUDreader = null;
DataTable dt = new DataTable();
try {
CRUDconnection.Open();
SqlCommand CRUDcommand = new SqlCommand(query, CRUDconnection);
dt.Load(CRUDcommand.ExecuteReader());
CRUDconnection.Close();
} catch (Exception e) {
//Console.WriteLine(e.ToString());
}
return dt;
}
protected DataTable executeRead(string query, string[] conditionColumns, string[] conditionValues) {
SqlDataReader CRUDreader = null;
DataTable dt = new DataTable();
try {
CRUDconnection.Open();
SqlCommand CRUDcommand = new SqlCommand(query, CRUDconnection);
for (int i = 0; i < conditionColumns.Length; i++) {
CRUDcommand.Parameters.Add(new SqlParameter("@" + conditionColumns[i] + "Check", conditionValues[i]));
}
dt.Load(CRUDcommand.ExecuteReader());
CRUDconnection.Close();
} catch (Exception e) {
//Console.WriteLine(e.ToString());
}
return dt;
}
}
} |
using System.Collections.Generic;
using UnityEngine;
namespace Thesis {
public sealed class CityMapManager
{
private const float _tolerance = 5f;
private static readonly CityMapManager _instance = new CityMapManager();
public static CityMapManager Instance
{
get { return _instance; }
}
private List<Block> _blocks;
public IList<Block> blocks
{
get { return _blocks.AsReadOnly(); }
}
private List<BuildingLot> _lots;
public IList<BuildingLot> lots
{
get { return _lots.AsReadOnly(); }
}
private List<Vector3> _nodes;
public IList<Vector3> nodes
{
get { return _nodes.AsReadOnly(); }
}
private List<Road> _roads;
public IList<Road> roads
{
get { return _roads; }
}
private List<Sidewalk> _sidewalks;
public IList<Sidewalk> sidewalks
{
get { return _sidewalks; }
}
private List<BuildingLot> _drawableLots;
public IList<BuildingLot> drawableLots
{
get { return _drawableLots; }
}
private CityMapManager ()
{
_blocks = new List<Block>();
_nodes = new List<Vector3>();
_lots = new List<BuildingLot>();
_roads = new List<Road>();
_sidewalks = new List<Sidewalk>();
_drawableLots = new List<BuildingLot>();
}
public void Add (Block block)
{
_blocks.Add(block);
}
public void Add (BuildingLot lot)
{
_lots.Add(lot);
}
public int Add (Vector3 node)
{
var n = _nodes.FindIndex(0, delegate (Vector3 v) {
return (Mathf.Abs(v.x - node.x) <= _tolerance &&
Mathf.Abs(v.z - node.z) <= _tolerance);
});
if (n == -1)
_nodes.Add(node);
return n;
}
public void AddRoad (Block block)
{
Road r = new Road(block);
r.name = "road";
r.material = MaterialManager.Instance.Get("mat_road");
_roads.Add(r);
}
public void DrawRoads ()
{
foreach (Road r in _roads)
{
r.FindVertices();
r.FindTriangles();
r.Draw();
r.gameObject.SetActive(true);
}
}
public void DestroyRoads ()
{
foreach (Road r in _roads)
r.Destroy();
}
public void AddSidewalk (Block block)
{
Sidewalk s = new Sidewalk(block);
s.name = "sidewalk";
s.material = MaterialManager.Instance.Get("mat_sidewalk");
_sidewalks.Add(s);
}
public void DrawSidewalks ()
{
foreach (Sidewalk s in _sidewalks)
{
s.FindVertices();
s.FindTriangles();
s.Draw();
s.gameObject.SetActive(true);
}
}
public void DestroySidewalks ()
{
foreach (Sidewalk s in _sidewalks)
s.Destroy();
}
public void AddDrawableLot (BuildingLot lot)
{
lot.name = "buildinglot";
lot.material = MaterialManager.Instance.Get("mat_lot");
_drawableLots.Add(lot);
}
public void DrawLots ()
{
foreach (BuildingLot lot in _drawableLots)
{
lot.FindVertices();
lot.FindTriangles();
lot.Draw();
lot.gameObject.SetActive(true);
}
}
public void DestroyLots ()
{
foreach (BuildingLot lot in _drawableLots)
lot.Destroy();
}
public void Clear ()
{
_blocks.Clear();
_lots.Clear();
_nodes.Clear();
DestroyRoads();
_roads.Clear();
DestroySidewalks();
_sidewalks.Clear();
DestroyLots();
_drawableLots.Clear();
}
}
} // namespace Thesis |
using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Reg : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["Usd"] != null) //防止已登录用户注册
{
Response.Redirect("UpLoad.aspx");
}
}
protected void Submit2_ServerClick(object sender, EventArgs e)
{
int myQx = 1; //一般情况下用户只能注册普通用户(学生)
users user = new users(); //使用用户操作类(参见App_Code)
if (user.checkUserName(this.txtUserName.Text)) //检查重名
{
Response.Write("<script>alert('此用户已经存在!');</script>");
}
else
{
if (this.txtVisit.Text == "我是老师") //教师用户验证注册
{
myQx = 2;
}
if (user.insertUsers(this.txtUserName.Text, this.txtUserPwd.Text,myQx)) //调用方法,添加一条记录
{
DirectoryInfo di;
di = Directory.CreateDirectory(Server.MapPath("./") + "files\\" + this.txtUserName.Text); //建立用户文件夹
File.CreateText(Server.MapPath("./") + "files\\" + this.txtUserName.Text + "\\note.txt");
Ck(this.txtUserName.Text,myQx); //建立cookie
Response.Write("<script>alert('新用户注册成功!');</script>");
Response.Write("<SCRIPT>window.location.href=\"Lo.aspx\"</SCRIPT>");
}
}
}
protected void Ck(string namek,int qx)
{
HttpCookie myCoo = new HttpCookie("Usd"); //用户名字段
myCoo.Value = namek;
Response.Cookies.Add(myCoo);
myCoo = new HttpCookie("Qx"); //权限字段
myCoo.Value = qx.ToString();
Response.Cookies.Add(myCoo);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using OrbisEngine.ItemSystem;
public class TestItem : Item {
public TestItem()
{
m_Components = new List<IComponent>() {
new TestComponent(this),
new OtherTestComponent(this),
new ItemStats(this)
};
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResourcesList : MonoBehaviour
{
public static ResourcesList _resourcesList;
[Header("Resources")]
public int _food;
public int _meds;
public int _wood;
public int _stone;
public int _steelScrap;
public int _electronicComponents;
public int _electricity;
[Header("Melee")]
public int _knifes;
public int _sharpMelee;
public int _dullMelee;
[Header("Guns")]
public int _shotguns;
public int _pistols;
public int _snipers;
public int _machineGuns;
[Header("Ammo")]
public int _shotgunAmmo;
public int _pistolAmmo;
public int _sniperAmmo;
public int _machineGunAmmo;
[Header("UI")]
public List<GameObject> _ResourceCategories;
private void Start()
{
_resourcesList = this;
DontDestroyOnLoad(this);
gameObject.SetActive(false);
}
public void SelectCategory(int category)
{
_ResourceCategories[category].SetActive(true);
for (int i = 0; i < _ResourceCategories.Count; i++)
{
if (i != category)
{
_ResourceCategories[i].SetActive(false);
}
}
}
}
|
using System;
using System.Collections.Generic;
public class Turma : IImprimivel
{
private string _nome;
private string _serie;
private List<Aluno> EST = new List<Aluno>();
private Professor x;
private Professor y;
public string Nome
{
get
{
return this._nome;
}
}
public Professor X
{
get
{
return this.x;
}
}
public Professor Y
{
get
{
return this.y;
}
}
public string Serie
{
get
{
return this._serie;
}
}
public Turma(string nome, string serie, Professor x, Professor y)
{
this._nome = nome;
this._serie = serie;
this.x = x;
this.y = y;
}
public void AdicionarAluno(Aluno x)
{
EST.Add(x);
}
public void Imprimir(bool escreval = false)
{
Console.WriteLine("Número da Turma:\t{0}", this.Nome);
Console.WriteLine("Serie:\t{0}", this.Serie);
Console.WriteLine("Professores:\t{0}", this.X.Nome + " e " + this.Y.Nome);
Console.Write("Alunos:\t");
foreach (var p in EST)
{
Console.Write(" ");
p.Imprimir(true);
}
Console.WriteLine();
}
}
|
using System.Collections.Generic;
using System.ServiceModel;
namespace Services
{
[ServiceContract]
public interface IBlogService
{
[OperationContract]
IEnumerable<BlogDto> GetBlogs();
[OperationContract]
void AddBlog(BlogDto blog);
[OperationContract]
void RemoveBlog(int blogId);
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class StageSelectButton : MonoBehaviour {
//ゲームを管理するスクリプト
public GameManager GM;
//ステージに関するテキスト
public Text turnText;
public Text guardianText;
public Animator ssFrameAnim;
public int stageNum = 0;
public int stagePattern = 0;
// Use this for initialization
void Start () {
GM = GameObject.Find ("GameManager").GetComponent<GameManager> ();
}
// Update is called once per frame
void Update () {
}
public void OnBottonClick() {
TextAsset _textdata;
string dataPath;
char[] newline = {'\r', '\n', };
string[] dataInfo;
string[] eachInfo;
dataPath = "Text/StageData/StageData" + stagePattern + "/stagedata";
_textdata = Resources.Load(dataPath) as TextAsset;
dataInfo = _textdata.text.Split(newline);
eachInfo = dataInfo [5].Split (',');
int guardianNum = int.Parse(eachInfo [0]);
eachInfo = dataInfo [6].Split (',');
int turnNum = int.Parse(eachInfo [0]);
turnText.text = turnNum + "ターン";
guardianText.text = guardianNum + "体";
GM.selectStage = stagePattern;
ssFrameAnim.SetTrigger("isOpen");
ssFrameAnim.SetInteger("StageNum", stageNum);
}
}
|
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Eda.Integrations.Delivery
{
/// <summary>
/// The contract for the delivery geo service.
/// </summary>
public interface IDeliveryGeoService
{
/// <summary>
/// Gets available countries.
/// </summary>
/// <param name="start">The beginning of the name.</param>
/// <param name="ct">The cancellation token</param>
/// <returns>
/// The list of available countries.
/// </returns>
Task<IReadOnlyList<ICountry>> GetCountries(string start, CancellationToken ct = default);
/// <summary>
/// Gets available regions in the <paramref name="country"/>.
/// </summary>
/// <param name="country">The country.</param>
/// <param name="start">The beginning of the name.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>
/// The list of available countries.
/// </returns>
Task<IReadOnlyList<IRegion>> GetRegions(ICountry country, string start, CancellationToken ct = default);
/// <summary>
/// Gets available cities in the <paramref name="region"/>.
/// </summary>
/// <param name="region">The region.</param>
/// <param name="start">The beginning of the name.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>
/// The list of available cities.
/// </returns>
Task<IReadOnlyList<ICity>> GetCities(IRegion region, string start,
CancellationToken ct = default);
/// <summary>
/// Gets available streets in the <paramref name="city"/>.
/// </summary>
/// <param name="city">The city.</param>
/// <param name="start">The beginning of the name.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>
/// The list of available streets.
/// </returns>
Task<IReadOnlyList<IStreet>> GetStreets(ICity city, string start, CancellationToken ct = default);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IWorkFlow.DataBase;
namespace IWorkFlow.ORM
{
//Sys_CommonWords
[Serializable]
[DataTableInfo("Sys_CommonWords", "")]
public class Sys_CommonWords : QueryInfo
{
/// <summary>
/// 自动增长ID
/// </summary>
[DataField("ID", "Sys_CommonWords")]
public int? ID
{
get { return _id; }
set { _id = value; }
}
private int? _id;
/// <summary>
/// 常用语
/// </summary>
[DataField("WordsItem", "Sys_CommonWords")]
public string WordsItem
{
get { return _wordsitem; }
set { _wordsitem = value; }
}
private string _wordsitem;
/// <summary>
/// 用户UID
/// </summary>
[DataField("UserID", "Sys_CommonWords")]
public string UserID
{
get { return _userid; }
set { _userid = value; }
}
private string _userid;
/// <summary>
/// 录入控件的全局路径标识
/// </summary>
[DataField("ControlUrl", "Sys_CommonWords")]
public string ControlUrl
{
get { return _controlurl; }
set { _controlurl = value; }
}
private string _controlurl;
}
} |
using System.Security.Claims;
using Microsoft.AspNetCore.SignalR;
namespace DattingApp.API
{
public class CustomUserIdProvider : IUserIdProvider
{
public string GetUserId(HubConnectionContext connection)
{
var conn = connection.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
return conn;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace GameProject
{
class SalesManager : ISalesService
{
public void Buy(Sale sale)
{
Console.WriteLine("Satın alınan oyun: " + sale.GameName + " Fiyat: " + sale.GamePrice);
}
}
}
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EmployeeManagement.Controllers
{
[Route("Error")]
public class ErrorController : Controller
{
private readonly ILogger<ErrorController> _logger;
public ErrorController(ILogger<ErrorController> logger)
{
_logger = logger;
}
[AllowAnonymous]
public IActionResult Index()
{
var expectionHandlerFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
_logger.LogError($" Path :{expectionHandlerFeature.Path} Error : {expectionHandlerFeature.Error} ");
return View("Error");
}
[Route("{statusCode}")]
public IActionResult HttpStatusCodehandler(int statusCode)
{
var statusCodeHandlerFeature = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
switch (statusCode)
{
case 404:
_logger.LogError($"Path : {statusCodeHandlerFeature.OriginalPath}");
ViewBag.ErrorMessage = "Sorry, the requested page could not be found.";
return View("NotFound");
}
return View("Error");
}
}
}
|
namespace Funding.Services.Interfaces
{
using System.Threading.Tasks;
public interface IUserService
{
Task<bool> EmailExist(string email);
Task<bool> isDeleted(string email);
Task<string> GetUserFullName(string email);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BelindaWrightCPA.Models
{
public class LoanCalculatorItemModel
{
public DateTime Month { get; private set; }
public double MonthlyPayment { get; private set; }
public double InterestRate { get; private set; }
public double InterestAccrued { get; private set; }
public double Principle { get; private set; }
public LoanCalculatorItemModel(
DateTime month,
double payment,
double interestAccrued,
double interestRate,
double principleLeft)
{
this.Month = month;
this.MonthlyPayment = payment;
this.InterestAccrued = interestAccrued;
this.InterestRate = interestRate;
this.Principle = principleLeft;
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using Properties.Core.Interfaces;
using Properties.Core.Objects;
using Properties.Infrastructure.Data;
using Properties.Infrastructure.Data.Interfaces;
namespace Properties.Tests.UnitTests.Repositories
{
[TestFixture]
// ReSharper disable once InconsistentNaming
public class CheckRepository_TestFixture
{
private readonly Mock<DbSet<Property>> _mockDbSet = new Mock<DbSet<Property>>();
private readonly Mock<IPropertiesContext> _mockContext = new Mock<IPropertiesContext>();
private readonly Mock<IDbSettings> _mockDbSettings = new Mock<IDbSettings>();
private readonly Mock<IMapToExisting<PropertyCheck, PropertyCheck>> _mockCheckMapper = new Mock<IMapToExisting<PropertyCheck, PropertyCheck>>();
private IPropertyCheckRepository _checkRepository;
[SetUp]
public void Setup()
{
_mockDbSettings.Setup(x => x.ConnectionString).Returns("TestConectionString");
_mockContext.Setup(x => x.Properties).Returns(_mockDbSet.Object);
_mockContext.Setup(x => x.SaveChanges()).Returns(1);
_mockCheckMapper.Setup(x => x.Map(It.IsAny<PropertyCheck>(), It.IsAny<PropertyCheck>())).Returns(true);
_checkRepository = new PropertyCheckRepository(_mockContext.Object, _mockCheckMapper.Object);
}
[Test]
public void CheckRepository_NullPropertiesContext_ThrowsException()
{
//act
Assert.Throws<ArgumentNullException>(() => new PropertyCheckRepository(null, _mockCheckMapper.Object));
}
[Test]
public void CheckRepository_NullCheckMapper_ThrowsException()
{
//act
Assert.Throws<ArgumentNullException>(() => new PropertyCheckRepository(_mockContext.Object, null));
}
[Test]
public void GetChecksForProperty_Must_GetChecksForPropertyReference()
{
//arrange
const string reference = "ABCD1234";
SetupDataForTest(new List<Property>
{
new Property
{
PropertyReference = reference,
Checks = new List<PropertyCheck> {new PropertyCheck {PropertyCheckReference = reference}}
},
new Property
{
PropertyReference = "12345678",
Checks = new List<PropertyCheck> {new PropertyCheck {PropertyCheckReference = "123456"}}
},
}.AsQueryable());
//act
var result = _checkRepository.GetChecksForProperty(reference);
//assert
result.Any().Should().BeTrue();
result.First().PropertyCheckReference.Should().Be(reference);
}
[Test]
public void GetCheckForProperty_Must_GetMatchingCheckForPropertyReference()
{
//arrange
const string reference = "ABCD1234";
SetupDataForTest(new List<Property>
{
new Property
{
PropertyReference = reference,
Checks =
new List<PropertyCheck>
{
new PropertyCheck {PropertyCheckReference = reference},
new PropertyCheck {PropertyCheckReference = "12345678"}
}
},
}.AsQueryable());
//act
var result = _checkRepository.GetCheckForProperty(reference, reference);
//assert
result.PropertyCheckReference.Should().Be(reference);
}
[Test]
public void CreateCheck_EmptyPropertyReference_Returns_False()
{
//act
var result = _checkRepository.CreateCheck(string.Empty, new PropertyCheck());
//assert
result.Should().BeFalse();
}
[Test]
public void CreateCheck_SavesPropertyToContext_ReturnsTrue()
{
//arrange
const string reference = "ABCD1234";
_mockContext.ResetCalls();
SetupDataForTest(new List<Property>
{
new Property
{
PropertyReference = reference,
},
}.AsQueryable());
//act
var result = _checkRepository.CreateCheck(reference, new PropertyCheck());
//assert
result.Should().BeTrue();
_mockContext.Verify(x => x.SaveChanges(), Times.Once);
}
[Test]
public void UpdateCheck_CheckDoesNotExist_ReturnsFalse()
{
//arrange
const string reference = "ABCD1234";
SetupDataForTest(new List<Property>
{
new Property
{
PropertyReference = reference,
Checks = new List<PropertyCheck> {new PropertyCheck {PropertyCheckReference = "12345678"}}
},
}.AsQueryable());
//act
var result = _checkRepository.UpdateCheck(reference, reference, new PropertyCheck());
//assert
result.Should().BeFalse();
}
[Test]
public void UpdateCheck_SoftDeletedCheckExists_ReturnsFalse()
{
//arrange
const string reference = "ABCD1234";
SetupDataForTest(new List<Property>
{
new Property
{
PropertyReference = reference,
Checks =
new List<PropertyCheck>
{
new PropertyCheck {PropertyCheckReference = reference, DateDeleted = DateTime.UtcNow.AddDays(-1)}
}
},
}.AsQueryable());
//act
var result = _checkRepository.UpdateCheck(reference, reference, new PropertyCheck());
//assert
result.Should().BeFalse();
}
[Test]
public void UpdateCheck_CheckDoesExist_CallsCheckMapper()
{
//arrange
const string reference = "ABCD1234";
SetupDataForTest(new List<Property>
{
new Property
{
PropertyReference = reference,
Checks = new List<PropertyCheck> {new PropertyCheck {PropertyCheckReference = reference}}
},
}.AsQueryable());
//act
var result = _checkRepository.UpdateCheck(reference, reference, new PropertyCheck());
//assert
result.Should().BeTrue();
_mockCheckMapper.Verify(x => x.Map(It.IsAny<PropertyCheck>(), It.IsAny<PropertyCheck>()), Times.Once);
}
[Test]
public void UpdateCheck_CheckDoesExist_ReturnsTrue()
{
//arrange
const string reference = "ABCD1234";
_mockContext.ResetCalls();
SetupDataForTest(new List<Property>
{
new Property
{
PropertyReference = reference,
Checks = new List<PropertyCheck> {new PropertyCheck {PropertyCheckReference = reference}}
},
}.AsQueryable());
//act
var result = _checkRepository.UpdateCheck(reference, reference, new PropertyCheck());
//assert
result.Should().BeTrue();
_mockContext.Verify(x => x.SaveChanges(), Times.Once);
}
[Test]
public void DeleteCheck_UpdatesDateDeleted_SavesCheckToContext_ReturnsTrue()
{
//arrange
const string reference = "ABCD1234";
_mockContext.ResetCalls();
SetupDataForTest(new List<Property>
{
new Property
{
PropertyReference = reference,
Checks = new List<PropertyCheck> {new PropertyCheck {PropertyCheckReference = reference}}
},
}.AsQueryable());
//act
var result = _checkRepository.DeleteCheck(reference, reference);
//assert
result.Should().BeTrue();
_mockContext.Verify(x => x.SaveChanges(), Times.Once);
}
[Test]
public void DeleteCheck_SoftDeletedCheck_ReturnsFalse()
{
//arrange
const string reference = "ABCD1234";
_mockContext.ResetCalls();
SetupDataForTest(new List<Property>
{
new Property
{
PropertyReference = reference,
Checks =
new List<PropertyCheck>
{
new PropertyCheck {PropertyCheckReference = reference, DateDeleted = DateTime.UtcNow.AddDays(-1)}
}
},
}.AsQueryable());
//act
var result = _checkRepository.DeleteCheck(reference, reference);
//assert
result.Should().BeFalse();
_mockContext.Verify(x => x.SaveChanges(), Times.Never);
}
private void SetupDataForTest(IQueryable<Property> data)
{
_mockDbSet.As<IQueryable<Property>>().Setup(m => m.Provider).Returns(data.Provider);
_mockDbSet.As<IQueryable<Property>>().Setup(m => m.Expression).Returns(data.Expression);
_mockDbSet.As<IQueryable<Property>>().Setup(m => m.ElementType).Returns(data.ElementType);
_mockDbSet.As<IQueryable<Property>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
}
}
}
|
using System;
namespace Task8
{
class Program
{
static void Main(string[] args)
{
int n1 = 0;
int n2 = 1;
int n3 = 0;
Console.Write("Enter the number of elements: ");
int number = Convert.ToInt32(Console.ReadLine());
Program prgrm = new Program();
prgrm.Sequence(number, n1, n2, n3);
}
public void Sequence(int Number, int n1, int n2, int n3) {
for(int i=0; i < Number; i++) {
Console.WriteLine(n1);
n3 = n1 + n2;
n1 = n2;
n2 = n3;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.