text stringlengths 13 6.01M |
|---|
namespace ReceptiAPI.Konstante
{
public static class KonstantneVrednosti
{
public static string GreskaNaServerskojStrani = @"Greska na serverskoj strani.";
public static string GreskaPrilikomPristupaBaziPodataka = @"Greska prilikom pristupa bazi podataka.";
public static string EntitetNijePronadjen = @"Entitet nije pronadjen.";
}
}
|
using System.Collections;
using System.Collections.Generic;
using AlmenaraGames;
using UnityEngine;
/// <summary>
/// Reads the stick inputs and increases wing flap amp in response to input
/// Holds the wings in a public variable so we can set it in the prefab for the model
/// </summary>
public class WingFlap : MonoBehaviour
{
//Wings
public MeshRenderer[] LeftWingMeshRenderers;
public MeshRenderer[] RightWingMeshRenderers;
//Tunings
public float MinAmp;
public float MaxAmp;
public float FlapSoundTime;
//Bool to prevent changing all the time
private bool _hasInputLeft;
private bool _hasInputRight;
//PlayerController ref
private PlayerController _pc;
//Sounds
private MultiAudioSource _flapSoundSource;
private float _soundTimer;
// Start is called before the first frame update
void Start()
{
_hasInputLeft = false;
_hasInputRight = false;
_pc = GetComponentInParent<PlayerController>();
foreach (MeshRenderer mr in LeftWingMeshRenderers)
{
mr.material.SetFloat("_Amplitude", MinAmp);
}
foreach (MeshRenderer mr in RightWingMeshRenderers)
{
mr.material.SetFloat("_Amplitude", MinAmp);
}
_soundTimer = FlapSoundTime;
_flapSoundSource = GetComponent<MultiAudioSource>();
}
// Update is called once per frame
void Update()
{
InputResponse();
}
void InputResponse()
{
//If the player has not pushed the left stick and pushes it, set the wings to max
if (_pc.ReadLeftInput().magnitude > 0 && !_hasInputLeft)
{
Debug.Log("Input left");
_hasInputLeft = true;
foreach (MeshRenderer mr in LeftWingMeshRenderers)
{
mr.material.SetFloat("_Amplitude", MaxAmp);
}
}
//otherwise if the player has pushed the left stick and lets it go, return the amp to min
else if (_pc.ReadLeftInput().magnitude <= 0.01f && _hasInputLeft)
{
Debug.Log("Stop Input Left");
_hasInputLeft = false;
foreach (MeshRenderer mr in LeftWingMeshRenderers)
{
mr.material.SetFloat("_Amplitude", MinAmp);
}
}
//Separate checks for the right
if (_pc.ReadRightInput().magnitude > 0 & !_hasInputRight)
{
_hasInputRight = true;
foreach (MeshRenderer mr in RightWingMeshRenderers)
{
mr.material.SetFloat("_Amplitude", MaxAmp);
}
}
else if (_pc.ReadRightInput().magnitude <= 0.01f && _hasInputRight)
{
_hasInputRight = false;
foreach (MeshRenderer mr in RightWingMeshRenderers)
{
mr.material.SetFloat("_Amplitude", MinAmp);
}
}
SoundOnFlaps();
}
void SoundOnFlaps()
{
_soundTimer -= Time.deltaTime;
if (_soundTimer <= 0)
{
_flapSoundSource.Play();
_soundTimer = FlapSoundTime;
}
}
}
|
using Anywhere2Go.Business.Master;
using Anywhere2Go.DataAccess;
using Anywhere2Go.DataAccess.Object;
using Anywhere2Go.Library;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace Claimdi.WCF.Public
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Announcement" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Announcement.svc or Announcement.svc.cs at the Solution Explorer and start debugging.
public partial class Announcement : Authorization, IAnnouncement
{
CultureInfo ci = new CultureInfo("th-TH");
string statusUploadPictureClaim = "8001";
string statusUploadPictureClaimText = "รอกรอกรายงาน";
public Announcement()
{
Authorize();
}
public BaseResult<APIAnnouncementListResponse> AnnouncementList(APIAnnouncementSearch anouncementSearchModel)
{
BaseResult<APIAnnouncementListResponse> res = new BaseResult<APIAnnouncementListResponse>();
res.Result = new APIAnnouncementListResponse();
res.Result.Criteria = DateTime.Now.ToString(Constant.Format.ApiDateFormat);
try
{
if (_authenStatus == true)
{
// DataGroupEnum dataGroup = (DataGroupEnum)Enum.Parse(typeof(DataGroupEnum), anouncementSearchModel.accId);
var validationResult = DataAnnotation.ValidateEntity<APIAnnouncementSearch>(anouncementSearchModel);
if (validationResult.HasError)
{
res.StatusCode = Constant.ErrorCode.RequiredData;
res.Message = validationResult.HasErrorMessage;
}
else
{
DateTime? lastSyncedDateTime = null;
if (!string.IsNullOrEmpty(anouncementSearchModel.Criteria))
{
var dtValue = new DateTime();
if (DateTime.TryParseExact(anouncementSearchModel.Criteria, Constant.Format.ApiDateFormat,
System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dtValue))
{
lastSyncedDateTime = dtValue;
}
}
res = GetAnnouncementAPI(anouncementSearchModel, res, lastSyncedDateTime, null, true);
}
if (res.Result.Announcements.Count == 0)
{
res = new BaseResult<APIAnnouncementListResponse>();
res.Result = new APIAnnouncementListResponse();
res.Result.Criteria = DateTime.Now.ToString(Constant.Format.ApiDateFormat);
}
}
else
{
res.StatusCode = Constant.ErrorCode.Unauthorized;
res.Message = Constant.ErrorMessage.Unauthorized;
}
}
catch (Exception ex)
{
res.StatusCode = Constant.ErrorCode.SystemError;
res.Message = Constant.ErrorMessage.SystemError;
res.SystemErrorMessage = ex.Message;
}
return res;
}
public BaseResult<APIAnnouncementActiveResponse> GetAnnouncementListActive(APIAnnouncementSearch anouncementSearchModel)
{
BaseResult<APIAnnouncementActiveResponse> res = new BaseResult<APIAnnouncementActiveResponse>();
res.Result = new APIAnnouncementActiveResponse();
try
{
if (_authenStatus == true)
{
// DataGroupEnum dataGroup = (DataGroupEnum)Enum.Parse(typeof(DataGroupEnum), anouncementSearchModel.accId);
var validationResult = DataAnnotation.ValidateEntity<APIAnnouncementSearch>(anouncementSearchModel);
if (validationResult.HasError)
{
res.StatusCode = Constant.ErrorCode.RequiredData;
res.Message = validationResult.HasErrorMessage;
}
else
{
//DateTime? lastSyncedDateTime = null;
//if (!string.IsNullOrEmpty(anouncementSearchModel.Criteria))
//{
// var dtValue = new DateTime();
// if (DateTime.TryParseExact(anouncementSearchModel.Criteria, Constant.Format.ApiDateFormat,
// System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dtValue))
// {
// lastSyncedDateTime = dtValue;
// }
//}
res = GetAnnouncementActiveAPI(anouncementSearchModel, res,null, true);
}
if (res.Result.Announcements.Count == 0)
{
res = new BaseResult<APIAnnouncementActiveResponse>();
res.Result = new APIAnnouncementActiveResponse();
}
}
else
{
res.StatusCode = Constant.ErrorCode.Unauthorized;
res.Message = Constant.ErrorMessage.Unauthorized;
}
}
catch (Exception ex)
{
res.StatusCode = Constant.ErrorCode.SystemError;
res.Message = Constant.ErrorMessage.SystemError;
res.SystemErrorMessage = ex.Message;
}
return res;
}
private BaseResult<APIAnnouncementListResponse> GetAnnouncementAPI(APIAnnouncementSearch searchModel, BaseResult<APIAnnouncementListResponse> res, DateTime? lastSyncedDateTime, SortingCriteria sorting, bool checkExpire)
{
AnnouncementLogic announce = new AnnouncementLogic();
var obj = announce.GetAnnouncementAPI(searchModel, true, lastSyncedDateTime, checkExpire, sorting);
res.Result.Announcements = new List<APIAnnouncementInfo>();
if (obj.Announcements.Count > 0)
{
res.Result.Announcements = new List<APIAnnouncementInfo>();
res.Result.next_page = obj.next_page;
res.Result.page_size = obj.page_size;
res.Result.total_record = obj.total_record;
res.Result.previous_page = obj.previous_page;
res.Result.this_page = obj.this_page;
for (int i = 0; i < obj.Announcements.Count; i++)
{
var item = obj.Announcements[i];
res.Result.Announcements.Add(new APIAnnouncementInfo
{
Id = item.Id.ToString(),
ContentUrl = item.ContentUrl,
DatetimeSend= item.DatetimeSend.Value.ToString("dd MMM yy", ci),
UpdateDate = item.UpdateDate.Value.ToString(Constant.Format.ApiDateFormat),
ShortDesc =item.ShortDesc,
Title = item.Title,
});
}
}
return res;
}
private BaseResult<APIAnnouncementActiveResponse> GetAnnouncementActiveAPI(APIAnnouncementSearch searchModel, BaseResult<APIAnnouncementActiveResponse> res, SortingCriteria sorting, bool checkExpire)
{
AnnouncementLogic announce = new AnnouncementLogic();
var obj = announce.GetAnnouncementActiveAPI(searchModel,true, null, checkExpire, sorting);
res.Result.Announcements = new List<APIBaseAnnouncementActive>();
if (obj.Count > 0)
{
res.Result.Announcements = new List<APIBaseAnnouncementActive>();
for (int i = 0; i < obj.Count; i++)
{
var item = obj[i];
res.Result.Announcements.Add(new APIBaseAnnouncementActive
{
Id = item.Id.ToString()
});
}
}
return res;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KartLib.Entities;
using KartObjects;
using AxisPosCore;
using System.Threading;
using KartLib;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using AxisEq;
using KartObjects.Entities;
using KartObjects.Entities.Documents;
using KartSystem.Common;
namespace KartSystem
{
public partial class InvoiceDocsEditor : XBaseDocEditor, IInvoiceDocumentEditView
{
public InvoiceDocsEditor()
{
InitializeComponent();
ViewObjectType = ObjectType.InvoiceDocument;
gcDocSpec = gcInvoiceDocEditor;
gvDocSpec = gvInvoiceDocEditor;
}
public InvoiceDocsEditor(InvoiceDocument doc)
: base(doc)
{
InvoiceDocument = doc;
InitializeComponent();
gcDocSpec = gcInvoiceDocEditor;
gvDocSpec = gvInvoiceDocEditor;
InitView();
///Подписываемся на события изменения данных
gvDocSpec.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(gvGoodDocSpec_CellValueChanged);
}
public override void RefreshView()
{
if (!InvoiceDocument.IsNew)
presenter.refresh();
SetGoodRecordsDataSource(InvoiceGoodRecords);
gvDocSpec.RefreshData();
}
public Dictionary<long, List<Assortment>> _assortmentNamesByGoodIds = new Dictionary<long, List<Assortment>>();
public Dictionary<long, List<Assortment>> AssortmentNamesByGoodIds
{
get
{
return _assortmentNamesByGoodIds;
}
set
{
_assortmentNamesByGoodIds = value;
}
}
public override void InitView()
{
Multiplicator = 1;
IsReversal = false;
IsTradeOper = true;
presenter = new InvoiceDocPresenter(this, Multiplicator);
deExtDate.EditValue = InvoiceDocument.ExtDate;
teExtNum.Text = InvoiceDocument.ExtNumber;
base.InitView();
siGenerateBarcode.Enabled = !ReadOnlyMode;
sbFindGood.Enabled = !ReadOnlyMode;
teExtNum.Enabled = !ReadOnlyMode;
deExtDate.Enabled = !ReadOnlyMode;
sbMarkupAll.Enabled = !ReadOnlyMode;
lueOrganization.Enabled = !ReadOnlyMode;
if (KartDataDictionary.getAxiTradeParamValueAsBool(AxiParamNames.AutoSelectDocumentSupplier))
lueGoodSuppliers.EditValue = lueSuppliers.EditValue;
}
protected override void SaveData()
{
User ActiveUser = KartDataDictionary.User;
(InvoiceDocument as Document).IdUser = ActiveUser.Id;
InvoiceDocument.ExtNumber = teExtNum.EditValue as string;
if (deExtDate.EditValue != null)
InvoiceDocument.ExtDate = (DateTime)deExtDate.EditValue;
InvoiceDocument.IdOrganization = (long?)lueOrganization.EditValue;
base.SaveData();
}
/*
private void FindDocSpecByBarcode(string _barcode)
{
Barcode barcodeFromDB = KartDataDictionary.GetBarcode(_barcode);
if (barcodeFromDB != null)
{
Good goodFromDB = KartDataDictionary.GetGood(barcodeFromDB.IdGood.ToString());
if (goodFromDB != null)
{
long ?idAssortment=null;
if (KartDataDictionary.getAxiTradeParamValueAsBool(AxiParamNames.UseAssortment))
idAssortment = barcodeFromDB.IdAssortment;
else
{
idAssortment = KartDataDictionary.GetFirstIdAssortment(goodFromDB);
barcodeFromDB.IdAssortment = idAssortment;
}
InvoiceGoodSpecRecord currInvoiceGoodSpecRecord = InvoiceGoodRecords.FirstOrDefault(gr => { return gr.IdGood == goodFromDB.Id && gr.IdAssortment == idAssortment; }) as InvoiceGoodSpecRecord;
if (currInvoiceGoodSpecRecord == null)
{
currInvoiceGoodSpecRecord = InvoiceGoodRecords.FirstOrDefault(gr => { return gr.IdGood == goodFromDB.Id && gr.IdAssortment == null; }) as InvoiceGoodSpecRecord;
}
if (currInvoiceGoodSpecRecord != null)
{
currInvoiceGoodSpecRecord.Quantity = currInvoiceGoodSpecRecord.Quantity + cbSearchGood.Quantity;
InvoiceCurrGoodSpecRecord = currInvoiceGoodSpecRecord;
return;
}
//SetFiltersChecked();
currInvoiceGoodSpecRecord = InvoiceGoodRecords.FirstOrDefault(gr => { return gr.IdGood == goodFromDB.Id && gr.IdAssortment == idAssortment; }) as InvoiceGoodSpecRecord;
if (currInvoiceGoodSpecRecord == null)
{
currInvoiceGoodSpecRecord = InvoiceGoodRecords.FirstOrDefault(gr => { return gr.IdGood == goodFromDB.Id && gr.IdAssortment == null; }) as InvoiceGoodSpecRecord;
}
if (currInvoiceGoodSpecRecord != null)
{
InvoiceCurrGoodSpecRecord = currInvoiceGoodSpecRecord;
return;
}
if (ReadOnlyMode)
MessageBox.Show("Товар в накладной не найден.", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
CreateNewGoodSpecRecord(barcodeFromDB, goodFromDB);
return;
}
if (MessageBox.Show("Товар не найден. Завести новый товар ?", "Внимание", MessageBoxButtons.YesNo,MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) ;
{
if (!ReadOnlyMode)
AddNewGood(new Barcode() { barcode=_barcode});
}
}
else
{
if (ReadOnlyMode)
MessageBox.Show("Товар в накладной не найден.", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
if (MessageBox.Show("Штрихкод не найден. Завести новый товар ?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
{
if (KartDataDictionary.IsBarcode(_barcode))
{
barcodeFromDB = new Barcode();
barcodeFromDB.barcode = _barcode;
}
if (!ReadOnlyMode)
AddNewGood(barcodeFromDB);
}
}
}
*/
protected override void TryFindGood(Good good)
{
bool find = false;
for (int i = 0; i < gvDocSpec.RowCount; i++)
if ((gvDocSpec.GetRow(i) as DocGoodSpecRecord).IdGood == good.Id)
{
if (KartDataDictionary.getAxiTradeParamValueAsBool(AxiParamNames.SearchActsQuantity) && (!ReadOnlyMode))
(gvDocSpec.GetRow(i) as DocGoodSpecRecord).Quantity = (gvDocSpec.GetRow(i) as DocGoodSpecRecord).Quantity + cbSearchGood.Quantity;
SetGvDocSpecFocusedRowHandle(i);
(presenter as BaseDocEditorPresenter).saveGoodRecord();
RefreshCurrDocSpecRecord();
find = true;
break;
}
if ((!find) && (!ReadOnlyMode))
CreateNewGoodSpecRecord(Loader.DbLoadSingle<Barcode>("idgood=" + good.Id), good);
gcDocSpec.Focus();
gvDocSpec.FocusedColumn = gvDocSpec.Columns["Quantity"];
}
protected override void CreateNewGoodSpecRecord(Barcode barcode, Good goodFromDb)
{
InvoiceGoodSpecRecord newInvoiceGoodSpecRecord = new InvoiceGoodSpecRecord();
newInvoiceGoodSpecRecord.Barcode = barcode.barcode;
newInvoiceGoodSpecRecord.IdAssortment = barcode.IdAssortment ?? 0;
newInvoiceGoodSpecRecord.NameGood = goodFromDb.Name;
newInvoiceGoodSpecRecord.IdDocument = InvoiceDocument.Id;
newInvoiceGoodSpecRecord.IdGood = goodFromDb.Id;
newInvoiceGoodSpecRecord.Quantity = (cbSearchGood.Quantity == 0) ? 1 : cbSearchGood.Quantity;
newInvoiceGoodSpecRecord.NdsRate = goodFromDb.NDS;
newInvoiceGoodSpecRecord.IdGoodGroup = goodFromDb.IdGoodGroup;
(presenter as InvoiceDocPresenter).getDocPrice(goodFromDb, newInvoiceGoodSpecRecord);
//(presenter as InvoiceDocPresenter).saveGoodRecord();
InvoiceGoodRecords.Add(newInvoiceGoodSpecRecord);
gvDocSpec.RefreshData();
InvoiceCurrGoodSpecRecord = newInvoiceGoodSpecRecord;
(presenter as InvoiceDocPresenter).saveGoodRecord();
RefreshView();
InvoiceCurrGoodSpecRecord = newInvoiceGoodSpecRecord;
}
private void CreateNewInvoiceGoodSpecRecord(Barcode barcode, Good goodFromDB, Assortment assortment)
{
InvoiceGoodSpecRecord newInvoiceGoodSpecRecord = new InvoiceGoodSpecRecord();
newInvoiceGoodSpecRecord.Barcode = barcode != null ? barcode.barcode : null;
if (assortment != null)
newInvoiceGoodSpecRecord.IdAssortment = assortment.Id;
newInvoiceGoodSpecRecord.IdDocument = InvoiceDocument.Id;
if (goodFromDB != null)
{
newInvoiceGoodSpecRecord.NameGood = goodFromDB.Name;
newInvoiceGoodSpecRecord.IdGood = goodFromDB.Id;
}
newInvoiceGoodSpecRecord.Quantity = 1;
InvoiceGoodRecords.Add(newInvoiceGoodSpecRecord);
gvInvoiceDocEditor.SelectRow(gvInvoiceDocEditor.RowCount - 1);
(presenter as InvoiceDocPresenter).saveGoodRecord(newInvoiceGoodSpecRecord);
(presenter as InvoiceDocPresenter).refresh();
RefreshView();
InvoiceCurrGoodSpecRecord = newInvoiceGoodSpecRecord;
}
//InvoiceDocument _Document;
public InvoiceDocument InvoiceDocument
{
get
{
return base.Document as InvoiceDocument;
}
set
{
base.Document = value;
}
}
List<InvoiceGoodSpecRecord> _invoiceGoodRecords;
public IList<InvoiceGoodSpecRecord> InvoiceGoodRecords
{
get
{
return _invoiceGoodRecords;
}
set
{
_invoiceGoodRecords = value as List<InvoiceGoodSpecRecord>;
}
}
//InvoiceGoodSpecRecord _currGoodSpecRecord;
public InvoiceGoodSpecRecord InvoiceCurrGoodSpecRecord
{
get
{
return gvInvoiceDocEditor.GetFocusedRow() as InvoiceGoodSpecRecord;
}
set
{
//base.currGoodSpecRecord = value;
if (value == null) return;
if (value is InvoiceGoodSpecRecord)
{
for (int i = 0; i < gvDocSpec.RowCount; i++)
{
if (
(((gvDocSpec.GetRow(i) as InvoiceGoodSpecRecord).IdGood == value.IdGood)) && (!KartDataDictionary.IsUseAssortment()) ||
(((gvDocSpec.GetRow(i) as InvoiceGoodSpecRecord).IdAssortment == (value as InvoiceGoodSpecRecord).IdAssortment) && (KartDataDictionary.IsUseAssortment()))
)
{
if (cbPosByGroup.Checked)
tvGoodGroups.SetFocusedNode(tvGoodGroups.FindNodeByKeyID((long)value.IdGoodGroup));
//gvDocSpec.FocusedRowHandle = i;
SetGvDocSpecFocusedRowHandle(i);
break;
}
}
}
else
{
for (int i = 0; i < gvDocSpec.RowCount; i++)
{
if ((gvDocSpec.GetRow(i) as DocGoodSpecRecord).IdGood == value.IdGood)
{
if (cbPosByGroup.Checked)
tvGoodGroups.SetFocusedNode(tvGoodGroups.FindNodeByKeyID((long)value.IdGoodGroup));
//gvDocSpec.FocusedRowHandle = i;
SetGvDocSpecFocusedRowHandle(i);
break;
}
}
}
}
}
public InvoiceAssortSpecRecord InvoiceCurrAssortSpecRecord
{
get { return gcDocSpec.FocusedView.GetRow(((DevExpress.XtraGrid.Views.Base.ColumnView)gcDocSpec.FocusedView).FocusedRowHandle) as InvoiceAssortSpecRecord; }
}
public override IList<DocGoodSpecRecord> GoodRecords
{
get
{
return _invoiceGoodRecords != null ? _invoiceGoodRecords.ConvertAll(igsr => { return igsr as DocGoodSpecRecord; }) : null;
}
set
{
InvoiceGoodRecords = (value as List<DocGoodSpecRecord>).ConvertAll(d => { return d as InvoiceGoodSpecRecord; }); // as List<InvoiceGoodSpecRecord>;
SetGoodRecordsDataSource(InvoiceGoodRecords);
gvDocSpec.RefreshData();
//Устанавливаем первую активную запись
if (InvoiceGoodRecords != null && InvoiceGoodRecords.Count > 0)
currGoodSpecRecord = InvoiceGoodRecords[0];
}
}
public override DocGoodSpecRecord currGoodSpecRecord
{
get
{
return InvoiceCurrGoodSpecRecord;
}
set
{
InvoiceCurrGoodSpecRecord = value as InvoiceGoodSpecRecord;
}
}
public ObjectType ViewObjectType { get; set; }
List<Assortment> _currAssortmentList;
private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
InvoiceGoodSpecRecord currInvoiceGoodSpecRecord = gvInvoiceDocEditor.GetFocusedRow() as InvoiceGoodSpecRecord;
repositoryItemComboBox1.Items.Clear();
if (currInvoiceGoodSpecRecord != null && _assortmentNamesByGoodIds.ContainsKey(currInvoiceGoodSpecRecord.IdGood) && _assortmentNamesByGoodIds[currInvoiceGoodSpecRecord.IdGood] != null)
{
_currAssortmentList = _assortmentNamesByGoodIds[currInvoiceGoodSpecRecord.IdGood];
repositoryItemComboBox1.Items.AddRange(_assortmentNamesByGoodIds[currInvoiceGoodSpecRecord.IdGood].Select(g => { return g.NameDB ?? ""; }).ToArray());//.Select(g=>g.Name).ToArray());
//goodAttributeBindingSource.DataSource = assortmentAttributeNamesByAttrTypes[currAGA.IdAttributeType];
}
}
private void repositoryItemComboBox1_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
{
string assortmentNameDB = e.NewValue as string;
if (_currAssortmentList != null)
{
Assortment assort = _currAssortmentList.SingleOrDefault(a => { return a.NameDB == assortmentNameDB; });
if (assort != null)
InvoiceCurrGoodSpecRecord.IdAssortment = assort.Id;
(presenter as InvoiceDocPresenter).saveGoodRecord();
(presenter as InvoiceDocPresenter).refresh();
}
}
private void gridControl1_EmbeddedNavigator_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
{
if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Append)
{
e.Handled = true;
}
}
protected override void SetGoodRecordsDataSource(object ds)
{
if (this.gcDocSpec.InvokeRequired)
{
SetDataSourceCallback d = new SetDataSourceCallback(SetGoodRecordsDataSource);
this.Invoke(d, new object[] { ds });
}
else
{
invoiceGoodSpecRecordBindingSource.DataSource = null;
invoiceGoodSpecRecordBindingSource.DataSource = ds;
gcDocSpec.RefreshDataSource();
}
}
protected override void refreshTotals()
{
base.refreshTotals();
teMargin.Text = ((Document as Document).MarginSumDoc - (Document as Document).SumDoc).ToString();
}
protected override void NotFoundBarcodeLogic(string _barcode)
{
Good g = null;
if (KartDataDictionary.getAxiTradeParamValueAsBool(AxiParamNames.UseAxiCloud))
g = (presenter as InvoiceDocPresenter).GetGoodFromCloud(_barcode);
if (g == null)
{
if (MessageBox.Show(@"Товар не найден. Завести новый товар ?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
{
if (!ReadOnlyMode)
AddNewGood(new Barcode() { barcode = _barcode }, g);
}
else
gvDocSpec.Focus();
}
else
if (!ReadOnlyMode)
AddNewGood(new Barcode() { barcode = _barcode }, g);
}
/*
protected override void TryFindBarcode(string p)
{
if (insertNewGoodinHandleMode)
{
gvInvoiceDocEditor.SetFocusedRowCellValue("Barcode", p);
insertNewGoodinHandleMode = false;
}
else FindDocSpecByBarcode(p);
//teCurrBarcode.SelectAll();
}
*/
private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
{
(presenter as InvoiceDocPresenter).saveGoodRecord();
(presenter as InvoiceDocPresenter).refresh();
gcDocSpec.RefreshDataSource();
}
Good _currGood;
private void sbFindGood_Click(object sender, EventArgs e)
{
Assortment assortment = KartHelper.FindAssortment(out _currGood);
if (_currGood == null) return;
if (!presenter.DocLocked)
CreateNewInvoiceGoodSpecRecord(assortment != null ? KartDataDictionary.GetBarcode(assortment.Barcode) : null, _currGood, assortment);
}
private void siGenerateBarcode_Click(object sender, EventArgs e)
{
AddNewGood(null, null);
RefreshView();
}
private void ceLabelsPrint_CheckedChanged(object sender, EventArgs e)
{
ceCountFromSpec.Enabled = ceLabelsPrint.Checked;
}
private void InvoiceDocsEditor_KeyUp(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.G)
{
this.InvokeOnClick(siGenerateBarcode, null);
}
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
{
InvokeOnClick(sbFindGood, null);
}
}
protected override void RefreshCurrDocSpecRecord()
{
InvoiceGoodSpecRecord r = (presenter as BaseDocEditorPresenter).RefreshRecord<InvoiceGoodSpecRecord>();
if (r != null)
{
//currGoodSpecRecord as = r;
InvoiceCurrGoodSpecRecord.MarginPrice = r.MarginPrice;
InvoiceCurrGoodSpecRecord.Barcode = r.Barcode;
InvoiceCurrGoodSpecRecord.Quantity = r.Quantity;
InvoiceCurrGoodSpecRecord.ChangingPrice = r.ChangingPrice;
}
//InvoiceCurrGoodSpecRecord.MarginPrice = r.Price;
int RowHandle = gvDocSpec.FocusedRowHandle;
gvDocSpec.RefreshRow(RowHandle);
}
public bool IsEditable
{
get { return true; }
}
public bool IsInsertable
{
get { return true; }
}
public bool UseSubmenu
{
get { return true; }
}
public bool IsDeletable
{
get { return true; }
}
public bool IsPrintable
{
get { return false; }
}
private void tcDocEditor_SelectedPageChanged_1(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
{
this.Text = addCaption;
}
private void InvoiceDocsEditor_Shown(object sender, EventArgs e)
{
if (!DesignMode)
lueSuppliers.Focus();
}
private void repositoryItemTextEdit5_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
{
double value;
if (double.TryParse(e.NewValue.ToString(), out value))
{ }
}
private void simpleButton1_Click(object sender, EventArgs e)
{
MarkupForm frmMarkup = new MarkupForm();
if (frmMarkup.ShowDialog() == DialogResult.OK)
{
(presenter as InvoiceDocPresenter).MarkupDocument(frmMarkup.MarkupPercent, frmMarkup.Round);
}
RefreshView();
}
private void ceChangingPrice_CheckedChanged(object sender, EventArgs e)
{
if (ceChangingPrice.Checked)
{
if (gvDocSpec.RowCount == 0)
{
(presenter as BaseDocEditorPresenter).refresh();
}
gvDocSpec.ClearSelection();
for (int i = 0; i < gvDocSpec.RowCount; i++)
{
if ((gvDocSpec.GetRow(i) as InvoiceGoodSpecRecord).ChangingPrice)
{
gvDocSpec.SelectRow(i);
}
}
}
else
{
gvDocSpec.ClearSelection();
}
}
protected override void PrintDoc()
{
if ((ceChangingPrice.Checked && SelectedAssortment.Count == 0))
{
ceChangingPrice.Checked = false;
cePricePrint.Checked = false;
MessageBox.Show(@"Нет позиций, меняющих прайс!", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
base.PrintDoc();
}
protected override List<long> SelectedAssortment
{
get
{
if (gvDocSpec.RowCount == 0)
{
if (ceChangingPrice.Checked)
return (from a in InvoiceGoodRecords where a.ChangingPrice select a.IdAssortment).ToList();
else
return (from a in InvoiceGoodRecords where a.IdDocument != 0 select a.IdAssortment).ToList();
}
else
{
List<long> resultList = new List<long>(); ;
int[] selectedRows = gvDocSpec.GetSelectedRows();
if (selectedRows.Count() > 1)
{
foreach (int i in selectedRows)
{
resultList.Add((long)gvDocSpec.GetRowCellValue(i, "IdAssortment"));
}
}
else
{
if (ceChangingPrice.Checked)
resultList = (from a in InvoiceGoodRecords where a.ChangingPrice select a.IdAssortment).ToList();
else
resultList = (from a in InvoiceGoodRecords where a.IdDocument != 0 select a.IdAssortment).ToList();
}
return resultList;
}
}
}
FormWait frmWait;
private void sbScales_Click(object sender, EventArgs e)
{
List<TradeScale> _TradeScale = Loader.DbLoad<TradeScale>("");
if (_TradeScale == null)
{
MessageBox.Show(@"В системе нет весов.", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
List<Store> _Store = new List<Store>();
_Store.AddRange(from st in KartDataDictionary.sStores from t in _TradeScale where t.IdStore == st.Id select st);
DepartChoiseForm frmDepartChoise = new DepartChoiseForm(_Store);
System.Windows.Forms.DialogResult Result = frmDepartChoise.ShowDialog();
Store s = null;
if (Result == System.Windows.Forms.DialogResult.Cancel)
{
frmDepartChoise.Close();
/*s = frmDepartChoise.SelectedStore;
if (s != null)
{
if (s.GeneratePlu)
presenter.ApplyGoodsToStore(frmDepartChoise.SelectedStore);
}
if (Loader.DataContext.TranIsRunning)
Loader.DataContext.CommitRetaining();*/
}
if (Result == System.Windows.Forms.DialogResult.Yes)
{
s = frmDepartChoise.SelectedStore;
if (s != null)
if (s.GeneratePlu)
presenter.ApplyGoodsToStore(frmDepartChoise.SelectedStore);
TradeScale gk = KartDataDictionary.sTradeScales.FirstOrDefault(q => q.IdStore == s.Id) as TradeScale;
try
{
frmWait = new FormWait("Формирование данных ...");
AxisEq.AbstractScaleLoader sl = AxisEq.AbstractScaleLoader.GetLoader(gk, "plu2.txt", Settings.GetExecPath());
sl.WriteToLog("Начало прогрузки весов");
// Процесс формирования запускаем отдельным потоком
Thread thread = new Thread(new ThreadStart(
delegate
{
if (gk != null && gk.IdStore.HasValue)
{
List<ScaleGoodDepart> goods = Loader.DbLoad<ScaleGoodDepart>("char_length(barcode)<14 and IdStore=" + gk.IdStore.Value) ?? new List<ScaleGoodDepart>();
sl.SendPLUsToScale(goods.Where(g =>
{
return (KartDataDictionary.sMeasures.FirstOrDefault(m => { return m.Id == g.IdMeasure; }) ?? new Measure()).IsWeight;
}).ToList(), Settings.GetExecPath());
}
Thread.Sleep(100);
frmWait.CloseWaitForm();
})) { IsBackground = true };
thread.Start();
frmWait.ShowDialog();
frmWait.Dispose();
frmWait = null;
}
catch (Exception exc)
{
ExtMessageBox.ShowError(string.Format("При формировании данных произошли ошибки.\r\n{0}", exc.Message));
frmWait.CloseWaitForm();
}
frmDepartChoise.Close();
}
if (Result == System.Windows.Forms.DialogResult.OK)
{
Store x = frmDepartChoise.SelectedStore;
if (x != null)
if (x.GeneratePlu)
presenter.ApplyGoodsToStore(frmDepartChoise.SelectedStore, SelectedAssortment);
}
}
private void gvInvoiceDocEditor_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
if (e.Column.Name == "MarginPercent")
currGoodSpecRecord.MarginPrice = currGoodSpecRecord.Price * Convert.ToDecimal(e.Value);
}
private void deExtDate_DoubleClick(object sender, EventArgs e)
{
deExtDate.DateTime = DateTime.Today;
}
List<WhOrganization> _WhOrganization;
private void lueWarehouses_Properties_EditValueChanged(object sender, EventArgs e)
{
if (lueWarehouses.EditValue != null)
{
_WhOrganization = Loader.DbLoad<WhOrganization>("IDWAREHOUSE=" + (long)lueWarehouses.EditValue) ?? new List<WhOrganization>();
lueOrganization.Properties.DataSource = _WhOrganization;
lueOrganization.EditValue = InvoiceDocument.IdOrganization;
}
}
private void InvoiceDocsEditor_FormClosed(object sender, FormClosedEventArgs e)
{
gvDocSpec.CellValueChanged -= gvGoodDocSpec_CellValueChanged;
}
}
} |
using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace MakePayroll {
/// <summary>
/// Логика взаимодействия для Report.xaml
/// </summary>
public partial class ReportWindow : Window {
ReportWindowViewModel view;
public ReportWindow() {
InitializeComponent();
view = new ReportWindowViewModel();
}
private void Button_Click(object sender, RoutedEventArgs e) {
var reportDataSource = new Microsoft.Reporting.WinForms.ReportDataSource();
DataSet dataSet = new DataSet();
dataSet.BeginInit();
reportDataSource.Name = "DataSet1";
reportDataSource.Value = dataSet.CreatePayroll;
_reportViewer.LocalReport.DataSources.Add(reportDataSource);
_reportViewer.LocalReport.ReportEmbeddedResource = "MakePayroll.PayrollReport.rdl";
dataSet.EndInit();
var tableAdapter = new DataSetTableAdapters.CreatePayrollTableAdapter();
tableAdapter.ClearBeforeFill = true;
DateTime start = (view.start.Equals(DateTime.MinValue)) ? new DateTime(1800, 1, 1) : view.start;
DateTime end = (view.end.Equals(DateTime.MinValue)) ? new DateTime(9999, 1, 1) : view.end;
tableAdapter.Fill(dataSet.CreatePayroll, start, end);
ReportParameter p1 = new ReportParameter("start", start.ToShortDateString());
ReportParameter p2 = new ReportParameter("end", end.ToShortDateString());
List<ReportParameter> list = new List<ReportParameter>();
list.Add(p1);
list.Add(p2);
_reportViewer.LocalReport.SetParameters(list);
_reportViewer.RefreshReport();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace GK.Api.Core
{
/// <summary>
/// Contains information about the assembly hosting a .NET Core Web API.
/// </summary>
public class BuildInfo
{
public string AssemblyName { get; set; }
public string AssemblyDescription { get; set; }
public string AssemblyVersion { get; set; }
public static BuildInfo FromType(Type type) => FromAssembly(type.Assembly);
public static BuildInfo FromAssembly(Assembly assembly)
{
var name = assembly?.GetName();
if (name == null)
return new BuildInfo();
return new BuildInfo
{
AssemblyName = assembly.GetName().Name,
AssemblyDescription = assembly.GetCustomAttribute<AssemblyDescriptionAttribute>()?.Description,
AssemblyVersion = assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()?.Version,
};
}
}
}
|
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 TubesAI
{
public partial class Log : Form
{
public static string history;
public Log()
{
InitializeComponent();
LogText.Text = history;
Paste();
LogText.SelectionStart = LogText.Text.Length;
LogText.ScrollToCaret();
}
public void addText(string text, Color color)
{
this.LogText.SelectionStart = this.LogText.TextLength;
this.LogText.SelectionLength = 0;
this.LogText.SelectionColor = color;
this.LogText.AppendText(text + "\n");
this.LogText.SelectionColor = this.LogText.ForeColor;
this.LogText.ScrollToCaret();
}
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LogText.Clear();
history = "";
}
private void Log_FormClosing(object sender, FormClosingEventArgs e)
{
history = LogText.Text;
Copy();
}
private void Log_FormClosed(object sender, FormClosedEventArgs e)
{
DatabaseScript.logForm = new Log();
}
private void Copy()
{
Clipboard.SetText(LogText.Rtf, TextDataFormat.Rtf);
}
private void Paste()
{
if (Clipboard.ContainsText(TextDataFormat.Rtf))
{
LogText.Rtf = Clipboard.GetText(TextDataFormat.Rtf);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ifelseswitch
{
class Program
{
static void Main(string[] args)
{
atividade5();
Console.ReadKey();
#region Ativiade 1
void atividade()
{
int opcao;
Console.Write("código de origem de um produto");
Console.Write("\n");
Console.Write("\n1.Sul");
Console.Write("\n2.Norte");
Console.Write("\n3.Leste");
Console.Write("\n4.Oeste");
Console.Write("\n5 a 6.Nordeste");
Console.Write("\n7,8 e 9.Sudeste");
Console.Write("\n10 até 20.Centro oeste");
Console.Write("\n21 até 30.Noroeste");
Console.Write("\n");
Console.Write("\nDigite o codido do Produto: ");
opcao = int.Parse(Console.ReadLine());
if (opcao == 1)
{
Console.Write("\n O produto é do sul");
}
else if (opcao==2)
{
Console.Write("\n O produto é do Norte");
}
else if (opcao == 3)
{
Console.Write("\n O produto é do leste");
}
else if (opcao == 4)
{
Console.Write("\n O produto é do oeste");
}
else if (opcao == 5 && opcao == 6)
{
Console.Write("\n O produto é do nordeste");
}
else if (opcao >=7 && opcao <= 9)
{
Console.Write("\n O produto é do suldeste");
}
else if (opcao >= 10 && opcao <= 20)
{
Console.Write("\n O produto é do Centro oeste");
}
else if (opcao >= 21 && opcao <= 30)
{
Console.Write("\n O produto é do noroeste");
}
else
{
Console.Write("\n Código invalido");
}
}
#endregion
#region Atividade 2
void atividade2()
{
double salario, total;
int cargo;
Console.Write("Cargos");
Console.Write("\n");
Console.Write("\n1. Escriturário ");
Console.Write("\n2. Secretário ");
Console.Write("\n3. Caixa ");
Console.Write("\n4. Gerente ");
Console.Write("\n5. Diretor\n ");
Console.Write("\nInforme seu cargo: ");
cargo = int.Parse(Console.ReadLine());
Console.Write("\nInforme seu Salário: ");
salario = Double.Parse(Console.ReadLine());
if (cargo==1)
{
total = (salario * 0.5) + salario;
Console.Write("\nSeu cargo é de Escriturário, Seu salário era " + salario + " deve um aumento de 50% e foi para " + total);
}
else if (cargo==2)
{
total = (salario * 0.35) + salario;
Console.Write("\nSeu cargo é de Secretário, Seu salário era" + salario + " deve um aumento de 35% e foi para " + total);
}
else if (cargo==3)
{
total = (salario * 0.2) + salario;
Console.Write("\nSeu cargo é de Caixa, Seu salário " + salario + " deve um aumento de 20% e foi para " + total);
}
else if (cargo==4)
{
total = (salario * 0.1) + salario;
Console.Write("\nSeu cargo é de Gerente, Seu salário era " + salario + " deve um aumento de 10% e foi para " + total);
}
else if (cargo==5)
{
total = (salario * 0.05) + salario;
Console.Write("\nSeu cargo é de Diretor, Seu salário era " + salario + " deve um aumento de 05% e foi para " + total);
}
else
{
Console.Write("\nCargo não Reconhecido");
}
}
#endregion
#region Atividade 3
void atividade3()
{
int num, opçao, r;
Console.Write("1 - Verificar se o número é par");
Console.Write("\n2 - Calcular raiz quadrada");
Console.Write("\n3 - Calcular quadrado do número");
Console.Write("\n");
Console.Write("\nDigite um numero inteiro: ");
num = int.Parse(Console.ReadLine());
Console.Write("\nEscolha uma das opção a cima: ");
opçao = int.Parse(Console.ReadLine());
if (opçao==1)
{
r = num % 2;
if (r == 0)
{
Console.WriteLine("\no número " + num + " é par");
}
else
{
Console.WriteLine("\no número " + num + " não é par");
}
}
else if (opçao==2)
{
Console.WriteLine("\nRaiz quadrada:" + (Math.Sqrt(num)));
}
else if (opçao==3)
{
Console.WriteLine("\no número " + num + " elevado ao quadrado é " + (num * num));
}
else
{
Console.Write("\nOpção invalida");
}
}
#endregion
#region Atividade 4
void atividade4()
{
string nome, curso;
double semana;
Console.Write("cursos\n");
Console.Write("\nB. para curso básico ");
Console.Write("\nI. para curso intermediário ");
Console.Write("\nA. para curso Avançado \n");
Console.Write("\nDigite seu nome: ");
nome = Console.ReadLine();
Console.Write("\nDigite quantos dias na Semana: ");
semana = double.Parse(Console.ReadLine());
Console.Write("\nDigite o tipo do curso: ");
curso = Console.ReadLine().ToUpper();
if (curso=="B")
{
Console.Write("\nO aluno " + nome + " do curso basico frequenta o curso por " + semana + " dias na semana,o custo total sera " + (semana * 7) * 15);
}
else if (curso=="I")
{
Console.Write("\nO aluno " + nome + " do curso intermediário frequenta o curso por " + semana + " dias na semana ,\no custo total sera " + (semana * 8.5) * 20);
}
else if (curso=="A")
{
Console.Write("\nO aluno " + nome + " do curso avançado frequenta o curso por " + semana + " dias na semana,\no custo total sera " + (semana * 10) * 25);
}
else
{
Console.Write("\nNão foi possivel identificar o tipo de Curso");
}
}
#endregion
#region Atividade 5
void atividade5()
{
int codigo;
Console.Write("\n101.Qtde de salários mínimo:10");
Console.Write("\n102.Qtde de salários mínimo:11");
Console.Write("\n103.Qtde de salários mínimo:12");
Console.Write("\n104.Qtde de salários mínimo:13");
Console.Write("\n105.Qtde de salários mínimo:14");
Console.Write("\n106.Qtde de salários mínimo:15");
Console.Write("\n");
Console.Write("\nDigite o codigo do seu cargo: ");
codigo = int.Parse(Console.ReadLine());
if (codigo==101)
{
Console.Write("\ntotal: " + (998 * 10));
}
else if (codigo==102)
{
Console.Write("\ntotal: " + (998 * 11));
}
else if (codigo==103)
{
Console.Write("\ntotal: " + (998 * 12));
}
else if (codigo==104)
{
Console.WriteLine("\ntotal: " + (998 * 13));
}
else if (codigo==105)
{
Console.WriteLine("\ntotal: " + (998 * 14));
}
else if (codigo==106)
{
Console.WriteLine("\ntotal: " + (998 * 15));
}
else
{
Console.WriteLine("\nCodigo desconhecido\n");
}
}
#endregion
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Globalization;
using CompanyX.Common;
using CompanyX.Common.Enums;
using CompanyX.Common.Helpers;
using CompanyX.Contracts;
using CompanyX.Data;
using CompanyX.Service;
using System.Data.Entity.Core.Objects;
using System.Configuration;
using System.Diagnostics;
namespace CompanyX.BL
{
public class TrackingProcessing
{
private static string _accessKey = ConfigurationManager.AppSettings["AccessKey"];
private static int _threadSleepTimeOut = int.Parse(ConfigurationManager.AppSettings["ThreadSleepTimeOut"]);
private static Dictionary<XmlClassLibrary.DeliveryStatusCode, CompanyXStatuses> CompanyXEventTypes = new Dictionary<XmlClassLibrary.DeliveryStatusCode, CompanyXStatuses>
{
{ XmlClassLibrary.DeliveryStatusCode.PickedUp, new CompanyXStatuses { Code = "TR01-AA", Description = "Some Description 1" } },
{ XmlClassLibrary.DeliveryStatusCode.Debited, new CompanyXStatuses { Code = "TR02-BB", Description = "Some Description 2" } },
{ XmlClassLibrary.DeliveryStatusCode.Departed, new CompanyXStatuses { Code = "TR02-CC", Description = "Some Description 3" } },
{ XmlClassLibrary.DeliveryStatusCode.Arrived, new CompanyXStatuses { Code = "TR03-DD", Description = "Some Description 4" } },
{ XmlClassLibrary.DeliveryStatusCode.OnLastMile, new CompanyXStatuses { Code = "TR03-EE", Description = "Some Description 5" } },
{ XmlClassLibrary.DeliveryStatusCode.Delivered, new CompanyXStatuses { Code = "TR05-FF", Description = "Some Description 6" } }
};
private static void ProcessTrackings()
{
using (var context = new CompanyXEntities())
{
var ordersForClosing = (from th in context.TrackingHistories
join t in context.Trackings on th.DocumentNumber equals t.DocumentNumber
where th.Code == XmlClassLibrary.DeliveryStatusCode.Delivered.ToString()
select th.DocumentNumber).ToList();
//Удаляем все доставленные заказы из очереди
if (ordersForClosing.Count() > 0)
{
var removeList = context.Trackings.Where(x => ordersForClosing.Contains(x.DocumentNumber));
if (removeList.Count() > 0)
{
context.Trackings.RemoveRange(removeList);
context.SaveChanges();
}
}
//Список всех заказов, которые лежат в очереди
var pkgListInQueue = (from tr in context.Trackings
join req in context.Requests on tr.RequestId equals req.Id
select new
{
DocumentNumber = tr.DocumentNumber,
MessageNumber = tr.MessageNumber,
RequestId = tr.RequestId,
PkgInfDocumentNumber = req.DocumentNumber,
}).Distinct().OrderBy(x => x.RequestId).ToList();
foreach (var trackingInfo in pkgListInQueue)
{
var newOrderStatuses = GetNewDeliveryStatus(trackingInfo.DocumentNumber);
if (newOrderStatuses == null)
return;
//Появился новый статус заказа
if (newOrderStatuses != null && newOrderStatuses.Count > 0)
{
//
var pkginf = context.Requests.FirstOrDefault(r => r.DocumentNumber == trackingInfo.PkgInfDocumentNumber && r.RequestType == MessageType.PKGINF.ToString());
var requestBody = pkginf.RequestBody;
var requestBase = (PKGINF)Helpers.GetRequest(XElement.Parse(requestBody));
//
//Уведомляем CompanyX о новом статусе
int sequenceNumber = 1;
foreach (var pkgItem in requestBase.PKGList.PKGItem)
{
var trkinf = GenerateTrkinf(trackingInfo.PkgInfDocumentNumber, trackingInfo.DocumentNumber, newOrderStatuses, pkgItem.CartonNumber, sequenceNumber);
if (trkinf == null)
return;
sequenceNumber++;
var trkinfXml = Helpers.Serialize<TRKINF>(trkinf, "http://edi.sec.CompanyX.com/GLS_ECC_LE/ELEM");
if (Helpers.CheckAllowedMessageTypeIdentifierForOut(trkinf) == true)
{
//Отправляем в Out в том случае, если есть интересующие CompanyX события
if (trkinf.EvnList.EvnItem.Count > 0)
{
CompanyXService service = new CompanyXService();
try
{
service.Out(trkinfXml.ToString());
}
catch (Exception ex)
{
Thread.Sleep(60000);
service.Out(trkinfXml.ToString());
}
}
}
}
foreach (var status in newOrderStatuses)
{
var trackingHistory = new TrackingHistory()
{
Code = status.Code.ToString(),
Status = status.Description,
DocumentNumber = trackingInfo.DocumentNumber,
MessageNumber = trackingInfo.MessageNumber,
RequestId = trackingInfo.RequestId,
};
context.TrackingHistories.Add(trackingHistory);
}
if (newOrderStatuses.Count > 0)
{
context.SaveChanges();
}
}
}
}
}
private static List<XmlClassLibrary.DeliveryStatus> GetNewDeliveryStatus(string clientsNumber)
{
var response = GetPegasResponse(clientsNumber);
if (response == null)
return null;
var serviceList = response.OrderList.Select(x => x.ServiceList).FirstOrDefault();
if (serviceList.Count == 0)
return null;
var deliveryStatuses = serviceList.Select(x => x.StatusList).FirstOrDefault().ToList();
var deliveryStatusList = new List<XmlClassLibrary.DeliveryStatus>();
foreach (var d in deliveryStatuses)
{
if (!deliveryStatusList.Select(x => x.Code).Contains(((XmlClassLibrary.DeliveryStatus)d).Code))
deliveryStatusList.Add((XmlClassLibrary.DeliveryStatus)d);
}
//TEST code. Disabled.
#region GENERATE TEST STATUSES
var GenerateTestStatuses = ConfigurationManager.AppSettings["GenerateTestStatuses"];
if (GenerateTestStatuses == "True")
{
deliveryStatusList.Add(
new XmlClassLibrary.DeliveryStatus()
{
Code = XmlClassLibrary.DeliveryStatusCode.PickedUp,
Date = DateTime.Now,
Description = XmlClassLibrary.DeliveryStatusCode.PickedUp.ToString()
}
);
deliveryStatusList.Add(
new XmlClassLibrary.DeliveryStatus()
{
Code = XmlClassLibrary.DeliveryStatusCode.Debited,
Date = DateTime.Now,
Description = XmlClassLibrary.DeliveryStatusCode.Debited.ToString()
}
);
deliveryStatusList.Add(
new XmlClassLibrary.DeliveryStatus()
{
Code = XmlClassLibrary.DeliveryStatusCode.Departed,
Date = DateTime.Now,
Description = XmlClassLibrary.DeliveryStatusCode.Departed.ToString()
}
);
deliveryStatusList.Add(
new XmlClassLibrary.DeliveryStatus()
{
Code = XmlClassLibrary.DeliveryStatusCode.Delivered,
Date = DateTime.Now,
Description = XmlClassLibrary.DeliveryStatusCode.Delivered.ToString()
}
);
}
//TEST code END
#endregion
List<string> existingStatusList = null;
using (var context = new CompanyXEntities())
{
existingStatusList = context.TrackingHistories.Where(x => x.DocumentNumber == clientsNumber).Select(x => x.Code).ToList();
}
var ret = new List<XmlClassLibrary.DeliveryStatus>();
ret.AddRange(deliveryStatusList);
foreach (var item in deliveryStatusList)
{
if (item.Code.HasValue)
{
if (existingStatusList.Contains(item.Code.Value.ToString()))
ret.Remove(item);
}
}
return ret;
}
private static TRKINF GenerateTrkinf(string pkgInfdocumentNumber, string documentNumber, List<XmlClassLibrary.DeliveryStatus> statusList, string cartonId, int sequenceNumber)
{
TRKINF trkinf;
using (var context = new CompanyXEntities())
{
var pkginf = context.Requests.FirstOrDefault(r => r.DocumentNumber == pkgInfdocumentNumber && r.RequestType == MessageType.PKGINF.ToString());
var requestBody = pkginf.RequestBody;
var requestBase = (PKGINF)Helpers.GetRequest(XElement.Parse(requestBody));
var matItems = new List<MatItemForTRKINF>();
int sequenceMatNumber = 1;
foreach (var item in requestBase.MatList.MatItem)
{
matItems.Add(new MatItemForTRKINF()
{
ChargeableWeight = item.CargoInformation.ChargeableWeight,
ChargeableWeightCode = item.CargoInformation.ChargeableWeightCode, //"KG"
GoodsDescription = "",
GrossWeight = item.CargoInformation.GrossWeight,
GrossWeightCode = item.CargoInformation.GrossWeightCode, //"KG"
ItemNumber = item.Material.ItemNumber,
Material = item.Material.MaterialName,
Quantity = item.CargoInformation.Quantity,
QuantityCode = item.CargoInformation.QuantityCode,
SequenceNumber = sequenceMatNumber.ToString(),
Volume = item.CargoInformation.Volume,
VolumeCode = item.CargoInformation.VolumeCode
});
sequenceMatNumber++;
}
var pegasResponse = GetPegasResponse(documentNumber);
if (pegasResponse == null)
return null;
DateTime? estimateDatetime = null;
if (pegasResponse.OrderList[0] != null)
{
if (pegasResponse.OrderList[0].ServiceList[0] is XmlClassLibrary.DeliveryService)
{
estimateDatetime = ((XmlClassLibrary.DeliveryService)pegasResponse.OrderList[0].ServiceList[0]).PlannedDeliveryDate;
}
}
var evnItems = new List<EvnItem>();
int sequenceStatusNumber = 1;
foreach (var status in statusList)
{
if (status.Code.HasValue && (status.Code == XmlClassLibrary.DeliveryStatusCode.PickedUp
|| status.Code == XmlClassLibrary.DeliveryStatusCode.Debited
|| status.Code == XmlClassLibrary.DeliveryStatusCode.Departed
|| status.Code == XmlClassLibrary.DeliveryStatusCode.Arrived
|| status.Code == XmlClassLibrary.DeliveryStatusCode.OnLastMile
|| status.Code == XmlClassLibrary.DeliveryStatusCode.Delivered))
{
evnItems.Add(new EvnItem()
{
ActualDate = status.Date.HasValue ? status.Date.Value.ToString("yyyyMMdd") : DateTime.Now.ToString("yyyyMMdd"),
ActualTime = status.Date.HasValue ? status.Date.Value.ToString("HHmmss") : DateTime.Now.ToString("HHmmss"),
CityCode = "MOW",
CityName = "Moscow",
CountryCode = "RU",
CountryName = "Russian Fed.",
CurrentEvent = "X",
Description = CompanyXEventTypes[status.Code.Value].Description,
EstimateDate = estimateDatetime.HasValue ? estimateDatetime.Value.ToString("yyyyMMdd") : "",
EstimateTime = estimateDatetime.HasValue ? estimateDatetime.Value.ToString("hhmmss") : "",
EventName = CompanyXEventTypes[status.Code.Value].Description,
EventType = CompanyXEventTypes[status.Code.Value].Code,
SequenceNumber = sequenceStatusNumber.ToString()
});
sequenceStatusNumber++;
}
}
var performersNumber = pegasResponse.OrderList.FirstOrDefault().PerformersNumber;
//Если в новых статусах не было ни одной из интересующих CompanyX статус , то MessageFunctionCodeEnum = Original(т.е. первая отправка информации по трэкингу),
//в противном случае апдейтим запрос
var notFirstDelivery = sequenceNumber > 1 || context.TrackingHistories.Where(x => x.DocumentNumber == documentNumber
&& (x.Code == XmlClassLibrary.DeliveryStatusCode.PickedUp.ToString()
|| x.Code == XmlClassLibrary.DeliveryStatusCode.Debited.ToString()
|| x.Code == XmlClassLibrary.DeliveryStatusCode.Departed.ToString()
|| x.Code == XmlClassLibrary.DeliveryStatusCode.Arrived.ToString()
|| x.Code == XmlClassLibrary.DeliveryStatusCode.OnLastMile.ToString()
|| x.Code == XmlClassLibrary.DeliveryStatusCode.Delivered.ToString())).Any();
var messageFunctionCode = notFirstDelivery == true ? MessageFunctionCodeEnum.Update : MessageFunctionCodeEnum.Original;
float volumeWeight = 0;
float.TryParse(requestBase.TotalCargoInformation.Volume, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out volumeWeight);
float gw = 0;
float.TryParse(requestBase.TotalCargoInformation.GrossWeight, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out gw);
Thread.Sleep(1000);
trkinf = new TRKINF()
{
DocumentDate = DateTime.Now.ToString("yyyyMMdd"),
DocumentNumber = performersNumber,
EvnList = new EvnList() { EvnItem = evnItems },
MatList = new MatListForTRKINF() { MatItem = matItems },
MessageFunctionCode = ((int)messageFunctionCode).ToString(),
MessageName = "Tracking Information",
MessageNumber = String.Format("TRKINF_{0}_{1}-{2}", performersNumber, DateTime.Now.ToString("hhmmss"), sequenceNumber.ToString()),
MessageReceiverIdentifier = "TAAA",
MessageReceiverName = requestBase.MessageSenderName, // "CompanyX",
MessageSenderIdentifier = "TAAA0000",
MessageSenderName = requestBase.MessageReceiverName, //"Logistic operator",
MessageTypeIdentifier = MessageType.TRKINF.ToString(),
PackingNo = requestBase.PKGList.PKGItem.Where(x => x.CartonNumber == cartonId).FirstOrDefault().CartonNumber,
RelatedDocumentDate = requestBase.RelatedDocumentNumber.RelatedDocumentDate,
RelatedDocumentNumber = requestBase.RelatedDocumentNumber.Number,
RelatedMessageNumber = requestBase.RelatedDocumentNumber.RelatedMessageNumber,
RelatedMessageTypeIdentifier = "OUTDLY",
TotalChargeableWeight = sequenceNumber > 1 ? "0" : volumeWeight * 167 > gw ? (Math.Ceiling((volumeWeight * 167) / 0.5) * 0.5).ToString().Replace(',', '.') : (Math.Ceiling(gw / 0.5) * 0.5).ToString().Replace(',', '.'),
TotalChargeableWeightCode = "KG",
TotalGrossWeight = requestBase.TotalCargoInformation.GrossWeight,
TotalGrossWeightCode = requestBase.TotalCargoInformation.GrossWeightCode,
TotalQuantity = requestBase.TotalCargoInformation.Quantity,
TotalQuantityCode = requestBase.TotalCargoInformation.QuantityCode,
TotalVolume = requestBase.TotalCargoInformation.Volume,
TotalVolumeCode = requestBase.TotalCargoInformation.VolumeCode,
TrackingType = "PACK"
};
}
return trkinf;
}
private static XmlClassLibrary.Response GetPegasResponse(string clientsNumber)
{
Thread.Sleep(_threadSleepTimeOut);
XmlClassLibrary.Response response = null;
try
{
var orderList = new List<XmlClassLibrary.Order>();
orderList.Add(new XmlClassLibrary.Order()
{
ClientsNumber = clientsNumber
});
XmlClassLibrary.OrderRequest order = new XmlClassLibrary.OrderRequest();
order.Mode = XmlClassLibrary.Enums.OrderRequestMode.Status;
order.OrderList = orderList;
APIService.UI_ServiceClient client = new APIService.UI_ServiceClient();
client.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
string orderXml = XmlClassLibrary.XMLService.SerializeToXMLString(order, typeof(XmlClassLibrary.Request));
var responseXml = client.SubmitRequest(new Guid(_accessKey), orderXml);
response = Helpers.Deserialize<XmlClassLibrary.Response>(responseXml);
}
catch (Exception ex)
{
EventLog eventLog = new EventLog("Application");
eventLog.Source = "Application";
eventLog.WriteEntry(String.Format("Source: {0} Message: {1} Data: {2}", ex.Source, ex.Message, ex.Data));
return null;
}
return response;
}
}
}
|
using Core;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading.Tasks;
namespace DBCore
{
public static class ReportsDB
{
public static async Task<List<ReportsIssuedEmployee>> GetEmployeeIssuedBetweenDateAsync(DateTime dateIn, DateTime dateOut)
{
List<ReportsIssuedEmployee> list = new List<ReportsIssuedEmployee>();
using (SqlConnection connection = Connection.Connect.SqlConnect())
{
try
{
await connection.OpenAsync();
SqlCommand query = new SqlCommand("SELECT * FROM [dbo].[Report_MasterIssuedBetween] (@dateIn, @dateOut)", connection);
query.Parameters.AddWithValue("@dateIn", dateIn);
query.Parameters.AddWithValue("@dateOut", dateOut);
SqlDataReader reader = await query.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
ReportsIssuedEmployee item = new ReportsIssuedEmployee(Convert.ToInt32(reader["ID_Order"]),
Convert.ToDateTime(reader["Time_Order"]), Convert.ToDateTime(reader["Time_Issued"]),
Convert.ToString(reader["Client"]), Convert.ToString(reader["Equipment"]),
Convert.ToDouble(reader["EmployeePrice"]), Convert.ToDouble(reader["Price"]));
list.Add(item);
}
}
catch (Exception e)
{
list = null;
Log.Loging("DBCore.ReportsDB.GetEmployeeIssuedBetweenDateAsync(DateTime dateIn, DateTime dateOut): " + e.Message);
}
return list;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using DomainModel.Entity.AmountClasses;
using DomainModel.StatePattern.InstallmentState;
using Infrostructure.Exeption;
namespace DomainModel.Entity.PaymentType
{
/// <summary>
/// قسط
/// </summary>
public class Installment
{
public Installment(Amount installmentAmount, DateTime payDate)
{
ValidateForInstallmentAmount(installmentAmount);
Id = Guid.NewGuid();
InstallmentAmount = installmentAmount;
PayDate = payDate;
AddState(new Created());
}
/// <summary>
/// شناسه
/// </summary>
public Guid Id { get; private set; }
/// <summary>
/// مبلغ قسط
/// </summary>
public Amount InstallmentAmount { get; private set; }
/// <summary>
/// مبلغ جریمه
/// </summary>
public Amount Penalty { get; private set; } = new Amount(0);
/// <summary>
/// تاریخ پرداخت
/// </summary>
public DateTime PayDate { get; private set; }
/// <summary>
/// مبلغ سود
/// </summary>
public Amount Comision { get; private set; } = new Amount(0);
/// <summary>
/// تاریخچه حالات
/// </summary>
public IEnumerable<StateBaseInstallment> StateBaseHistory { get; private set; } = new List<StateBaseInstallment>();
/// <summary>
/// حالت
/// </summary>
public StateBaseInstallment CurrentState => StateBaseHistory.OrderByDescending(s => s.PlacedDate).FirstOrDefault();
public void SetComision(Amount comision)
{
ValidateForComision(comision);
Comision = comision;
}
public void SetPenalty()
{
int index = 0;
var today = DateTime.Now;
if (today > PayDate)
{
if (today.Year == PayDate.Year)
{
index = today.DayOfYear - PayDate.DayOfYear;
}
else if (today.Year > PayDate.Year)
{
if (today.DayOfYear < PayDate.DayOfYear || today.DayOfYear > PayDate.DayOfYear)
{
index = today.DayOfYear - (365 - PayDate.DayOfYear);
}
if (today.DayOfYear == PayDate.DayOfYear)
{
index = 365;
}
}
for (int i = 1; i <= index; i++)
{
var penalty = InstallmentAmount.Division(100).Multiplication(2 * i);
ValidateForPenalty(penalty);
Penalty = penalty;
}
}
}
public void PaidInstallment()
{
AddState(new Paid());
}
private void AddState(StateBaseInstallment stateBase)
{
var stateBases = StateBaseHistory.ToList();
stateBases.Add(stateBase);
StateBaseHistory = stateBases;
}
//Validations
private void ValidateForInstallmentAmount(Amount installmentAmount)
{
if (installmentAmount == null)
throw new InvalidInstallmentAmountExeption();
}
private void ValidateForPenalty(Amount penalty)
{
if (penalty == null)
throw new InvalidPenaltyExeption();
}
private void ValidateForComision(Amount comision)
{
if (comision == null)
throw new InvalidComisionExeption();
}
}
}
|
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using AzureFunctions.Extensions.Swashbuckle.Attribute;
using AzureFunctions.Extensions.Swashbuckle;
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
namespace OpenApiSample
{
public static class MainFunctions
{
[SwaggerIgnore]
[FunctionName("Swagger")]
public static async Task<HttpResponseMessage> Swagger(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "Swagger/json")] HttpRequestMessage req,
[SwashBuckleClient] ISwashBuckleClient swashBuckleClient)
{
return swashBuckleClient.CreateSwaggerDocumentResponse(req);
}
[SwaggerIgnore]
[FunctionName("SwaggerUi")]
public static async Task<HttpResponseMessage> SwaggerUi(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "Swagger/ui")] HttpRequestMessage req,
[SwashBuckleClient] ISwashBuckleClient swashBuckleClient)
{
return swashBuckleClient.CreateSwaggerUIResponse(req, "swagger/json");
}
/**
* This function returns static text
*/
[FunctionName("SayHello")]
public static async Task<IActionResult> SayHello([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log)
{
return new OkObjectResult("Hello there !");
}
/**
* This function returns Hello with name passed in GET Parameter
* Expl : SayHello/Hamza
*/
[FunctionName("SayHelloNamed")]
public static async Task<IActionResult> SayHelloNamed([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "SayHello/{name}")] HttpRequest req, String name, ILogger log)
{
return new OkObjectResult("Hello " + name + " !");
}
/**
* This function returns the sum of two numbers passed in GET
* Expl : Add/12/5
*/
[FunctionName("Calculate")]
public static async Task<IActionResult> Calculate([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Add/{N1}/{N2}")] HttpRequest req, int N1, int N2, ILogger log)
{
return new OkObjectResult("Result is : " + (N1 + N2));
}
/**
* This function returns the sum of two numbers passed in POST
*/
[FunctionName("PostCalculate")]
public static async Task<IActionResult> PostCalculate([HttpTrigger(AuthorizationLevel.Anonymous, "Post", Route = "Add")][RequestBodyType(typeof(PostCalculateBody), "PostCalculateBody")] HttpRequest req, ILogger log)
{
using (var reader = new StreamReader(req.Body,encoding: Encoding.UTF8,detectEncodingFromByteOrderMarks: false))
{
String bodyString = await reader.ReadToEndAsync();
PostCalculateBody postCalculateBody = JsonConvert.DeserializeObject<PostCalculateBody>(bodyString);
return new OkObjectResult(postCalculateBody.calculate());
}
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class IntroDialogue : MonoBehaviour {
public Text introText;
public float interLetterTime;
// Use this for initialization
void Start () {
StartCoroutine(addText("WELL " + StatsManager.playerName + ", LET'S GET RIGHT TO IT. A RECENT 'SCAVENGING HUNT' " +
"FROM OUR ALLIES IN TORONTO YIELDED SOME DISTURBING INFORMATION. A GROUP OF THUGS RECENTLY CAME " +
"ACROSS SOME DATA ABOUT HIDDEN STOCKPILES OF NUCLEAR WEAPONS AND VARIOUS CIA PROJECTS. " +
"WE DON'T KNOW HOW THEY FOUND THIS INFO OR HOW THEY INTEND TO USE IT, BUT IT'S IN HOT WATER " +
"ALL THE SAME. IF THIS INFO GETS OUT, IT COULD BE USED FOR BLACKMAIL, OR WORSE, " +
"TO START A NUCLEAR WAR. YOU NEED TO GET INTO THEIR HANGOUT, DESTROY THAT DATA AND GET OUT QUIETLY. " +
"WE MAKE THE NEWS ENOUGH AS IT IS."));
}
IEnumerator addText(string text){
int textLength=text.Length;
for (int i = 0; i <= textLength; i++) {
introText.text = text.Substring (0, i);
yield return new WaitForSeconds (interLetterTime);
}
}
}
|
using System;
using System.Windows.Markup;
namespace Shimakaze.Toolkit.Csf.Markup
{
public class I18nExtension : MarkupExtension
{
public string Key { get; set; }
public I18nExtension() { }
public I18nExtension(string key) : this() => this.Key = key;
public override object ProvideValue(IServiceProvider serviceProvider) => Properties.Resource.ResourceManager.GetString(this.Key);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Restaurant.Models;
namespace Restaurant.Repositories
{
public class MemberRepository : IMemberRepository
{
private ApplicationDbContext context;
private Message message;
public MemberRepository(ApplicationDbContext ctx)//going to take a instants of context
{
context = ctx;
}
public List<Member> GetMemberBylastname()
{
var members = new List<Member>();
members.Add(new Member() { FirstName = "Megan", LastName = "Kale", Joined = new DateTime(2006, 8, 22) });
members.Add(new Member() { FirstName = "Jame", LastName = "Abe", Joined = new DateTime(2002, 10, 2) });
members.Add(new Member() { FirstName = "Rena", LastName = "Frampton", Joined = new DateTime(2013, 3, 12) });
return members;
}
public IEnumerable<Member> GetAllMember()
{
return context.Members.ToList();
}
}
}
|
using System;
using System.Collections.Generic;
using Alabo.Domains.Enums;
using Alabo.Domains.Services;
using Alabo.Framework.Core.Admins.Configs;
using Alabo.Framework.Core.Enums.Enum;
using Alabo.Industry.Cms.Articles.Domain.Entities;
using MongoDB.Bson;
namespace Alabo.Industry.Cms.Articles.Domain.Services {
public interface IChannelService : IService<Channel, ObjectId> {
List<DataField> DataFields(string channelId);
bool Check(string script);
void InitialData();
/// <summary>
/// 获取频道分类类型
/// </summary>
/// <param name="channel"></param>
Type GetChannelClassType(Channel channel);
/// <summary>
/// 获取频道标签类型
/// </summary>
/// <param name="channel"></param>
Type GetChannelTagType(Channel channel);
/// <summary>
/// 根据频道获取Id
/// </summary>
/// <param name="channelType"></param>
ObjectId GetChannelId(ChannelType channelType);
}
} |
using gView.Framework.Data;
using gView.Framework.Geometry;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System.Collections.Generic;
namespace gView.DataSources.MongoDb.Json
{
public class SpatialCollectionItem
{
public SpatialCollectionItem()
{
this.GeneralizationLevel = 0;
}
public SpatialCollectionItem(IGeometryDef geomDef, IFieldCollection fields)
{
AddFields(fields);
this.GeometryDef = new GeometryDefinition()
{
HasM = geomDef.HasM,
HasZ = geomDef.HasZ,
GeometryType = geomDef.GeometryType,
SrefId = 4326
};
}
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("name")]
public string Name { get; set; }
[BsonElement("geometryDef")]
public GeometryDefinition GeometryDef { get; set; }
[BsonElement("fields")]
public IEnumerable<Field> Fields { get; set; }
private void AddFields(IFieldCollection fields)
{
if (fields == null)
{
return;
}
List<Field> fieldCollection = new List<Field>();
for (int i = 0; i < fields.Count; i++)
{
var field = fields[i];
if (field.type == FieldType.ID ||
field.type == FieldType.Shape)
{
continue;
}
fieldCollection.Add(new Field()
{
Name = field.name,
FieldType = field.type
});
}
this.Fields = fieldCollection;
}
[BsonElement("bounds")]
public Bounds FeatureBounds { get; set; }
[BsonElement("generalizationLevel")]
public int GeneralizationLevel { get; set; }
#region Classes
public class GeometryDefinition
{
[BsonElement("hasZ")]
public bool HasZ { get; set; }
[BsonElement("hasM")]
public bool HasM { get; set; }
[BsonElement("srefId")]
public int SrefId { get; set; }
[BsonElement("geometryType")]
public GeometryType GeometryType { get; set; }
}
public class Field
{
[BsonElement("name")]
public string Name { get; set; }
[BsonElement("type")]
public FieldType FieldType { get; set; }
}
public class Bounds
{
public Bounds() { }
public Bounds(IEnvelope envelpe)
{
this.MinX = envelpe.minx;
this.MinY = envelpe.miny;
this.MaxX = envelpe.maxx;
this.MaxY = envelpe.maxy;
}
[BsonElement("minx")]
double MinX { get; set; }
[BsonElement("miny")]
double MinY { get; set; }
[BsonElement("maxx")]
double MaxX { get; set; }
[BsonElement("maxy")]
double MaxY { get; set; }
public IEnvelope ToEnvelope()
{
return new Envelope(MinX, MinY, MaxX, MaxY);
}
}
#endregion
}
}
|
using BookApi.Domain.Intefaces;
using BookApi.Domain.Models;
using BookApi.Infrastructure.Data.EntityFramework.Context;
namespace BookApi.Infrastructure.Data.Repositories.EF
{
public class EFBookRepository : EFRepository<Book>, IBookRepository
{
public EFBookRepository(BookDbContext db) : base(db)
{
}
}
} |
using System;
using System.Collections.Generic;
using ContentPatcher.Framework.Tokens;
namespace ContentPatcher.Framework
{
/// <summary>A generic token context.</summary>
/// <typeparam name="TToken">The token type to store.</typeparam>
internal class GenericTokenContext<TToken> : IContext where TToken : class, IToken
{
/*********
** Accessors
*********/
/// <summary>The available tokens.</summary>
public IDictionary<TokenName, TToken> Tokens { get; } = new Dictionary<TokenName, TToken>();
/*********
** Accessors
*********/
/// <summary>Save the given token to the context.</summary>
/// <param name="token">The token to save.</param>
public void Save(TToken token)
{
this.Tokens[token.Name] = token;
}
/// <summary>Get whether the context contains the given token.</summary>
/// <param name="name">The token name.</param>
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
public bool Contains(TokenName name, bool enforceContext)
{
return this.GetToken(name, enforceContext) != null;
}
/// <summary>Get the underlying token which handles a key.</summary>
/// <param name="name">The token name.</param>
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
/// <returns>Returns the matching token, or <c>null</c> if none was found.</returns>
public IToken GetToken(TokenName name, bool enforceContext)
{
return this.Tokens.TryGetValue(name.GetRoot(), out TToken token) && this.ShouldConsider(token, enforceContext)
? token
: null;
}
/// <summary>Get the underlying tokens.</summary>
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
public IEnumerable<IToken> GetTokens(bool enforceContext)
{
foreach (TToken token in this.Tokens.Values)
{
if (this.ShouldConsider(token, enforceContext))
yield return token;
}
}
/// <summary>Get the current values of the given token for comparison.</summary>
/// <param name="name">The token name.</param>
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
/// <returns>Return the values of the matching token, or an empty list if the token doesn't exist.</returns>
/// <exception cref="ArgumentNullException">The specified key is null.</exception>
public IEnumerable<string> GetValues(TokenName name, bool enforceContext)
{
IToken token = this.GetToken(name, enforceContext);
return token?.GetValues(name) ?? new string[0];
}
/*********
** Private methods
*********/
/// <summary>Get whether a given token should be considered.</summary>
/// <param name="token">The token to check.</param>
/// <param name="enforceContext">Whether to only consider tokens that are available in the context.</param>
private bool ShouldConsider(IToken token, bool enforceContext)
{
return !enforceContext || token.IsReady;
}
}
/// <summary>A generic token context.</summary>
internal class GenericTokenContext : GenericTokenContext<IToken> { }
}
|
using Microsoft.EntityFrameworkCore;
using senai_hroads_webApi.Contexts;
using senai_hroads_webApi.Domains;
using senai_hroads_webApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace senai_hroads_webApi.Repositories
{
public class TipoHabilidadeRepository : ITipoHabilidadeRepository
{
HroadsContext _context = new HroadsContext();
public void Atualizar(int id, TipoHabilidade tipoAtualizado)
{
TipoHabilidade tipoBuscado = _context.TipoHabilidades.Find(id);
if (tipoAtualizado.Tipo != null)
{
tipoBuscado.Tipo = tipoAtualizado.Tipo;
}
_context.TipoHabilidades.Update(tipoBuscado);
_context.SaveChanges();
}
public TipoHabilidade BuscarPorId(int id)
{
return _context.TipoHabilidades.FirstOrDefault(e => e.IdTipo == id);
}
public void Cadastrar(TipoHabilidade novoTipoHabilidade)
{
_context.TipoHabilidades.Add(novoTipoHabilidade);
}
public void Deletar(int id)
{
TipoHabilidade tipoBuscado = _context.TipoHabilidades.Find(id);
_context.TipoHabilidades.Remove(tipoBuscado);
_context.SaveChanges();
}
public List<TipoHabilidade> Listar()
{
return _context.TipoHabilidades.Include(e => e.Habilidades).ToList();
}
}
} |
using System;
using Framework.Core.Common;
using OpenQA.Selenium;
using Tests.Data.Van.Input;
using Tests.Pages.Van.Main.Common;
namespace Tests.Pages.Van.Main.VoterBatchPages
{
public class VoterBatchDetailsPage : VanBasePage
{
#region Page Element Declarations
public IWebElement NameField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemNewPersonBatchName_VANInputItemDetailsItemNewPersonBatchName_NewPersonBatchName")); } }
public IWebElement CommitteeDropdown { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemCommitteeID_VANInputItemDetailsItemCommitteeID_CommitteeID")); } }
public IWebElement StateDropdown { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemStateCode_VANInputItemDetailsItemStateCode_StateCode")); } }
public IWebElement FormDropdown { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemDataEntryFormFormatID_VANInputItemDetailsItemDataEntryFormFormatID_DataEntryFormFormatID")); } }
public IWebElement ProgramType { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemBatchProgramTypeID_VANInputItemDetailsItemBatchProgramTypeID_BatchProgramTypeID")); } }
public IWebElement ApplicantRadioButton { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemNewPersonTypeID_VANInputItemDetailsItemNewPersonTypeID_NewPersonTypeID_0")); } }
public IWebElement PledgeRadioButton { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemNewPersonTypeID_VANInputItemDetailsItemNewPersonTypeID_NewPersonTypeID_1")); } }
public IWebElement SaveButton { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_Save")); } }
#endregion
public VoterBatchDetailsPage(Driver driver) : base(driver) { }
#region Methods
#region Create New Batch Methods
/// <summary>
/// Fills the fields on the VoterBatchDetails page, and submits
/// </summary>
/// <param name="voterBatch"></param>
public void CreateNewBatch(VoterBatch voterBatch)
{
FillNewBatch(voterBatch);
_driver.Click(SaveButton);
}
/// <summary>
/// Fills the fields on the VoterBatchDetails page
/// </summary>
/// <param name="voterBatch"></param>
public void FillNewBatch(VoterBatch voterBatch)
{
_driver.ClearAndSendKeysIfStringNotNullOrEmpty(NameField, voterBatch.Name);
SelectBatchDropdowns(voterBatch);
SelectNewPersonType(voterBatch);
}
/// <summary>
/// Selects the dropdown fields on the VoterBatchDetails page by text, if the passed voterBatch.{Committee, State, Form, ProgramType} is not empty or null
/// </summary>
/// <param name="voterBatch"></param>
public void SelectBatchDropdowns(VoterBatch voterBatch)
{
_driver.SelectOptionByTextIfStringNotNullOrEmpty(CommitteeDropdown, voterBatch.Committee);
_driver.SelectOptionByTextIfStringNotNullOrEmpty(StateDropdown, voterBatch.State);
_driver.SelectOptionByTextIfStringNotNullOrEmpty(FormDropdown, voterBatch.Form);
_driver.SelectOptionByTextIfStringNotNullOrEmpty(ProgramType, voterBatch.ProgramType);
}
/// <summary>
/// Clicks the New Person Type radio button if the passed voterBatch.NewPersonType is neither null nor empty
/// </summary>
/// <param name="voterBatch"></param>
public void SelectNewPersonType(VoterBatch voterBatch)
{
if (String.IsNullOrEmpty(voterBatch.NewPersonType)) return;
if (voterBatch.NewPersonType.ToUpper().StartsWith("A"))
_driver.Click(ApplicantRadioButton);
else if (voterBatch.NewPersonType.ToUpper().StartsWith("P"))
_driver.Click(PledgeRadioButton);
}
#endregion
#region Validation Methods
// TODO: Add more validation
/// <summary>
/// Checks to see if the name of the voter batch in the Edit Batch page is correct
/// </summary>
/// <param name="voterBatch"></param>
/// <returns>True if the name is correctly created</returns>
public bool VoterBatchWasCreated(VoterBatch voterBatch)
{
//_driver.WaitForElementPresent(NameField);
return NameField.GetAttribute("value").Equals(voterBatch.Name);
}
#endregion
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassicCraft
{
public class Boss : Entity
{
public enum BossType
{
NoArmor,
LightArmor,
HeavyArmor
}
public Boss(Boss b)
: base(null, b.Level, b.Armor, b.MaxLife)
{
}
public Boss(int level = 63, int customArmor = 4400, int maxLife = 100000)
: base(null, level, customArmor, maxLife)
{
}
public Boss(Simulation s, Boss b)
: base(s, b.Level, b.Armor, b.MaxLife)
{
}
public Boss(Simulation s, int level = 63, int customArmor = 4400, int maxLife = 100000)
: base(s, level, customArmor, maxLife)
{
}
public Boss(Simulation s, int level = 63, BossType type = BossType.LightArmor, int maxLife = 100000)
: base(s, level, ArmorByType(type), maxLife)
{
}
public static int ArmorByType(BossType type)
{
switch(type)
{
case BossType.HeavyArmor: return 5600;
case BossType.LightArmor: return 4400;
default: return 0;
}
}
public override double BlockChance()
{
return 0;
}
public override double ParryChance()
{
return 0;
}
public override string ToString()
{
return string.Format("Level {0}, {1} Armor\n", Level, Armor);
}
}
}
|
using OpenQA.Selenium;
namespace Kliiko.Ui.Tests.WebPages.Blocks
{
class ContactList : WebPage
{
private static readonly By ButtonRecruiter = By.XPath("//*[@id='dashboard-contact-lists']//*[@href='#/resources/survey']");
public static void ExpectWebElements()
{
}
public static void ClickRecruiter()
{
Web.Click(ButtonRecruiter);
}
}
}
|
namespace SubC.Attachments {
using UnityEngine;
using ClingyPhysics;
[System.Serializable]
public struct AngleLimits {
public float min;
public float max;
public AngleLimits(float min = 0, float max = 359) {
this.min = min;
this.max = max;
}
public static bool operator ==(AngleLimits lhs, AngleLimits rhs) {
if (System.Object.ReferenceEquals(lhs, null) && System.Object.ReferenceEquals(rhs, null))
return true;
if (System.Object.ReferenceEquals(lhs, null) || System.Object.ReferenceEquals(rhs, null))
return false;
return lhs.min == rhs.min && lhs.max == rhs.max;
}
public static bool operator !=(AngleLimits lhs, AngleLimits rhs) {
if (System.Object.ReferenceEquals(lhs, null) && System.Object.ReferenceEquals(rhs, null))
return false;
if (System.Object.ReferenceEquals(lhs, null) || System.Object.ReferenceEquals(rhs, null))
return true;
return lhs.min != rhs.min || lhs.max != rhs.max;
}
public override bool Equals(object obj) {
if (obj == null || GetType() != obj.GetType())
return false;
return (AngleLimits) obj == this;
}
public override int GetHashCode() {
return (min + max).GetHashCode();
}
public JointAngleLimits2D ToJointAngleLimits2D() {
JointAngleLimits2D limits = new JointAngleLimits2D();
limits.min = min;
limits.max = max;
return limits;
}
}
} |
using Cs_Gerencial.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Aplicacao.Interfaces
{
public interface IAppServicoConjuntos: IAppServicoBase<Conjuntos>
{
}
}
|
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using SuperMario.Collision;
namespace SuperMario.Entities.Mario
{
public class DeadMario : StaticEntity
{
public DeadMario(Vector2 screenLocation) : base(screenLocation)
{
this.CurrentSprite = new Sprite(MarioTextureStorage.DeadMario, new Rectangle(0, 0, 15, 14));
}
public override List<MovementDirectionsEnum.MovementDirection> Collide(Entity entity, ICollisions collisions)
{
return new List<MovementDirectionsEnum.MovementDirection>();
}
public override void Reset()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CarritoCompras.Modelo
{
public class Despacho
{
public string personaContacto { get; set; }
public string direccion { get; set; }
public string departamento { get; set; }
public string provincia { get; set; }
public string distrito { get; set; }
public string celular { get; set; }
public Double latitud { get; set;}
public Double longuitud { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace AudioClasses
{
[System.Serializable]
public class SoundEffect
{
[SerializeField]
private AudioClip audioClip;
public AudioClip Clip { get { return audioClip; } private set { audioClip = value; } }
[SerializeField]
[Range(0f, 1f)]
private float volume = 1f;
public float Volume { get { return volume; } private set { volume = value; } }
[SerializeField]
[Range(-3f, 3f)]
private float pitch = 1f;
public float Pitch { get { return pitch; } private set { pitch = value; } }
private Vector3 position = Vector3.zero;
public Vector3 Position { get { return position; } private set { position = value; } }
public SoundEffect(SoundEffect copy)
{
Clip = copy.Clip;
Volume = copy.Volume;
Pitch = copy.Pitch;
Position = copy.Position;
}
public SoundEffect(SoundEffect copy, Vector3 position)
{
Clip = copy.Clip;
Volume = copy.Volume;
Pitch = copy.Pitch;
Position = position;
}
}
[System.Serializable]
public class BackgroundMusic
{
[SerializeField]
AudioClip audioClip;
public AudioClip Clip { get { return audioClip; } }
[SerializeField]
[Range(0f, 1f)]
float volume = 1f;
public float Volume { get { return volume; } }
[SerializeField]
[Range(-3f, 3f)]
float pitch = 1f;
public float Pitch { get { return pitch; } }
}
}
|
using Photon.Pun;
using Photon.Pun.Demo.PunBasics;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Temp_PlayerController : MonoBehaviourPunCallbacks
{
private PlayerManager target;
private CameraWork playerCam;
private Text playerNameText;
private int playerID;
private float speed = 5.0f;
void Awake()
{
if (photonView.IsMine)
{
PlayerManager.LocalPlayerInstance = this.gameObject;
// setup camera on 'my' controllable character only
playerCam = gameObject.AddComponent<CameraWork>();
playerCam.OnStartFollowing();
}
DontDestroyOnLoad(this.gameObject);
}
void Start()
{
}
void Update()
{
GetInput();
}
void GetInput()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
transform.position += new Vector3(horizontal, 0, vertical) * speed * Time.deltaTime;
}
public void SetTarget(PlayerManager _target)
{
if (_target == null)
{
Debug.LogError("<Color=Red><a>Missing</a></Color> PlayMakerManager target for PlayerUI.SetTarget.", this);
return;
}
// Cache references for efficiency
target = _target;
if (playerNameText != null)
{
playerNameText.text = target.photonView.Owner.NickName;
playerID = target.photonView.Owner.ActorNumber;
}
}
}
|
using ND.FluentTaskScheduling.Core.CommandSet;
using ND.FluentTaskScheduling.Model;
using ND.FluentTaskScheduling.Model.enums;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
//**********************************************************************
//
// 文件名称(File Name):StopNodeCommand.CS
// 功能描述(Description):
// 作者(Author):Aministrator
// 日期(Create Date): 2017-04-10 15:52:16
//
// 修改记录(Revision History):
// R1:
// 修改作者:
// 修改日期:2017-04-10 15:52:16
// 修改理由:
//**********************************************************************
namespace ND.FluentTaskScheduling.Core.CommandSet
{
public class StopNodeCommand : AbstractCommand
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public override string CommandDisplayName
{
get
{
return "停止节点服务";
}
}
public override string CommandDescription
{
get
{
return "该命令用于向节点发起停止命令";
}
}
/// <summary>
/// 执行
/// </summary>
public override RunCommandResult Execute()
{
//通知节点TaskProvider任务执行
ServiceController service = new ServiceController(ConfigurationManager.AppSettings["WindowsServiceName"].ToString());
try
{
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped);
}
//添加日志
ShowCommandLog("停止节点windows服务成功");
return new RunCommandResult() { ExecuteStatus = ExecuteStatus.ExecuteSucess };
}
catch (Exception ex)
{
ShowCommandLog("停止节点windows服务失败,异常信息:" + JsonConvert.SerializeObject(ex));
return new RunCommandResult() { ExecuteStatus = ExecuteStatus.ExecuteException, Message = ex.Message, Ex = ex };
}
}
/// <summary>
/// 初始化命令所需参数
/// </summary>
public override void InitAppConfig()
{
//if (!this.AppConfig.ContainsKey("taskid"))
//{
// this.AppConfig.Add("taskid", "");
//}
}
}
}
|
using System;
namespace Task_06
{
class Program
{
static void DeleteElement(ref int[] array, int index)
{
int[] newArray = new int[array.Length - 1];
for (int i = 0, j = 0; i < newArray.Length; j++)
{
if (j == index)
{
continue;
}
newArray[i] = array[j];
i++;
}
array = newArray;
}
static void Compress(ref int[] array, ref int iterator)
{
for (int i = 0; i < array.Length - 1; i++)
{
if ((array[i] + array[i + 1]) % 3 == 0)
{
array[i] *= array[i + 1];
DeleteElement(ref array, i + 1);
iterator++;
}
}
}
static int CompressIterartions(ref int[] array)
{
int lastLength; int iterator = 0;
do
{
lastLength = array.Length;
Compress(ref array, ref iterator);
} while (lastLength != array.Length);
return iterator;
}
static void Main(string[] args)
{
if (!uint.TryParse(Console.ReadLine(), out uint N))
{
Console.WriteLine("Incorrect input");
return;
}
int[] myArray = new int[N];
for (int i = 0; i < N; i++)
{
Random random = new Random();
myArray[i] = random.Next(-10, 11);
}
foreach (var item in myArray)
{
Console.Write($"{item} ");
}
Console.WriteLine();
int iterator = CompressIterartions(ref myArray);
foreach (var item in myArray)
{
Console.Write($"{item} ");
}
Console.WriteLine();
Console.WriteLine($"\nCount of compressions: {iterator}");
}
}
}
|
using System;
namespace OrgMan.DomainObjects.Common
{
public class PhoneDomainModel
{
public Guid UID { get; set; }
public Guid CommunicationTypeUID { get; set; }
public Guid IndividualPersonUID { get; set; }
public string Number { get; set; }
public bool IsMain { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace com.Sconit.Entity.SI.SD_ORD
{
[Serializable]
public partial class SequenceMaster
{
public string SequenceNo { get; set; }
public string Flow { get; set; }
public CodeMaster.SequenceStatus Status { get; set; }
public com.Sconit.CodeMaster.OrderType OrderType { get; set; }
public com.Sconit.CodeMaster.QualityType QualityType { get; set; }
public DateTime StartTime { get; set; }
public DateTime WindowTime { get; set; }
public string PartyFrom { get; set; }
//public string PartyFromName { get; set; }
public string PartyTo { get; set; }
//public string PartyToName { get; set; }
public string ShipFrom { get; set; }
//public string ShipFromAddress { get; set; }
//public string ShipFromTel { get; set; }
//public string ShipFromCell { get; set; }
//public string ShipFromFax { get; set; }
//public string ShipFromContact { get; set; }
public string ShipTo { get; set; }
//public string ShipToAddress { get; set; }
//public string ShipToTel { get; set; }
//public string ShipToCell { get; set; }
//public string ShipToFax { get; set; }
//public string ShipToContact { get; set; }
public string LocationFrom { get; set; }
//public string LocationFromName { get; set; }
public string LocationTo { get; set; }
//public string LocationToName { get; set; }
public string Dock { get; set; }
//public string Container { get; set; }
//public string ContainerDescription { get; set; }
public Boolean IsAutoReceive { get; set; }
public Boolean IsPrintAsn { get; set; }
public Boolean IsPrintReceipt { get; set; }
public Boolean IsCheckPartyFromAuthority { get; set; }
public Boolean IsCheckPartyToAuthority { get; set; }
//public string AsnTemplate { get; set; }
//public string ReceiptTemplate { get; set; }
//public Int32 PackUserId { get; set; }
//public string PackUserName { get; set; }
//public DateTime PackDate { get; set; }
//public Int32 ShipUserId { get; set; }
//public string ShipUserName { get; set; }
//public DateTime ShipDate { get; set; }
//public DateTime? CancelDate { get; set; }
//public Int32? CancelUserId { get; set; }
//public string CancelUserName { get; set; }
//public DateTime? CloseDate { get; set; }
//public Int32? CloseUserId { get; set; }
//public string CloseUserName { get; set; }
public List<SequenceDetail> SequenceDetails { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SQMS.Application.sqms_mobileinterfaces;
using SQMS.Application.sqms_filejoiner;
namespace SQMS.Application.Views.Demo
{
public partial class WebServiceRefTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MobileInterfaces mobile = new MobileInterfaces();
if (mobile.MobileLogin("361", "t2") == false)
{
throw new Exception("Login Failed");
}
if (mobile.RegisterEquipment("0050BF3F517301083550-26020429458", "test", "t1", "t1") == false)
{
throw new Exception("Reg Equ Failed");
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DelftTools.Functions.Generic;
using DelftTools.TestUtils;
using NUnit.Framework;
namespace DelftTools.Functions.Tests
{
[TestFixture]
public class FunctionHelperTest
{
[Test]
public void SplitEnumerable()
{
var source = new[] {1, 2.0};
//split it into IEnumerable<int> and IEnumerable<double>
IList<IEnumerable> enumerables= FunctionHelper.SplitEnumerable(source, new[] {typeof (int), typeof (double)});
Assert.AreEqual(2,enumerables.Count);
Assert.IsTrue(enumerables[0] is IEnumerable<int>);
Assert.IsTrue(enumerables[1] is IEnumerable<double>);
Assert.AreEqual(1, ((IEnumerable<int>)enumerables[0]).FirstOrDefault());
Assert.AreEqual(2, ((IEnumerable<double>)enumerables[1]).FirstOrDefault());
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void WrongNumberOfValuesGivesException()
{
var source = new[] { 1, 2.0 };
//expecting 3 values getting only 2
IList<IEnumerable> enumerables = FunctionHelper.SplitEnumerable(source, new[] { typeof(int), typeof(double),typeof(double) });
}
[Test]
public void GetFirstValueBiggerThan()
{
var array = new [] { 1.0, 2.0 };
Assert.IsNull(FunctionHelper.GetFirstValueBiggerThan(5.0, array));
Assert.AreEqual(1.0,FunctionHelper.GetFirstValueBiggerThan(0.0, array));
Assert.AreEqual(2.0, FunctionHelper.GetFirstValueBiggerThan(1.5, array));
array = new[] { 1.0};
Assert.IsNull(FunctionHelper.GetFirstValueBiggerThan(5.0, array));
Assert.AreEqual(1.0, FunctionHelper.GetFirstValueBiggerThan(0.0, array));
}
[Test]
[Category(TestCategory.Performance)]
[Category(TestCategory.WorkInProgress)] // slow
public void GetFirstValueBiggerThanShouldBeFast()
{
int amount = 1000000;
List<double> values = new List<double>(amount);
for (int i = 0; i < amount; i++)
values.Add(i);
Action action = () =>
{
for (int i = 0; i < 100000; i++)
{
FunctionHelper.GetFirstValueBiggerThan(55555.0, values);
}
};
// avoid overhead, call one time
action();
TestHelper.AssertIsFasterThan(180, action);
}
[Test]
public void GetLastValueSmallerThan()
{
var array = new MultiDimensionalArray { 1.0, 2.0 };
Assert.IsNull(FunctionHelper.GetLastValueSmallerThan(1.0, array));
Assert.AreEqual(1.0, FunctionHelper.GetLastValueSmallerThan(1.5, array));
Assert.AreEqual(2.0, FunctionHelper.GetLastValueSmallerThan(2.5, array));
array = new MultiDimensionalArray { 1.0 };
Assert.IsNull(FunctionHelper.GetLastValueSmallerThan(1.0, array));
Assert.AreEqual(1.0, FunctionHelper.GetLastValueSmallerThan(55.0, array));
}
[Test]
[Category(TestCategory.Performance)]
[Category(TestCategory.WorkInProgress)] // slow
public void GetLastValueSmallerThanShouldBeFast()
{
int amount = 1000000;
List<double> values = new List<double>(amount);
for (int i = 0; i < amount; i++)
values.Add(i);
var array = new MultiDimensionalArray();
array.AddRange(values);
TestHelper.AssertIsFasterThan(400, () =>
{
for (int i = 0; i < 100000; i++)
FunctionHelper.GetLastValueSmallerThan(55555.0, array);
});
//orig: 2100ms
}
[Test]
public void CopyValuesFrom1Component()
{
Function source = new Function();
source.Arguments.Add(new Variable<DateTime>("time"));
source.Components.Add(new Variable<double>("component"));
source[DateTime.Now] = 27.7;
Function target = new Function();
target.Arguments.Add(new Variable<DateTime>("time"));
target.Components.Add(new Variable<double>("component"));
FunctionHelper.CopyValuesFrom(source, target);
Assert.AreEqual(1, target.Arguments[0].Values.Count);
Assert.AreEqual(27.7, (double)target.Components[0].Values[0], 1.0e-6);
}
[Test]
public void CopyValuesFrom1ComponentCopyShouldClear()
{
Function source = new Function();
source.Arguments.Add(new Variable<double>("x"));
source.Components.Add(new Variable<double>("component"));
source[1.0] = 27.7;
Function target = new Function();
target.Arguments.Add(new Variable<double>("x"));
target.Components.Add(new Variable<double>("component"));
target[0.0] = 10.0;
target[1.0] = 100.7;
FunctionHelper.CopyValuesFrom(source, target);
Assert.AreEqual(1, target.Arguments[0].Values.Count);
Assert.AreEqual(1.0, (double)target.Arguments[0].Values[0], 1.0e-6);
Assert.AreEqual(27.7, (double)target.Components[0].Values[0], 1.0e-6);
}
[Test]
public void CopyValuesFrom2Components()
{
Function source = new Function();
source.Arguments.Add(new Variable<double>("x"));
source.Components.Add(new Variable<double>("component1"));
source.Components.Add(new Variable<double>("component2"));
source[5.0] = new[] { 27.7, 127.7 };
Function target = new Function();
target.Arguments.Add(new Variable<double>("x"));
target.Components.Add(new Variable<double>("component1"));
target.Components.Add(new Variable<double>("component2"));
FunctionHelper.CopyValuesFrom(source, target);
Assert.AreEqual(1, target.Arguments[0].Values.Count);
Assert.AreEqual(27.7, (double)target.Components[0].Values[0], 1.0e-6);
Assert.AreEqual(127.7, (double)target.Components[1].Values[0], 1.0e-6);
}
}
} |
namespace P01Sorting
{
using System;
public interface ISortable<in T> where T : IComparable<T>
{
/// <summary>
/// Sort generic items of element
/// </summary>
/// <param name="array">elements</param>
void Sort(params T[] array);
/// <summary>
/// return whether items is sorted or not.
/// </summary>
/// <param name="array">elements</param>
/// <returns>return true if items is sorted or false if is not sorted.</returns>
bool IsSorted(T[] array);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.AccessControl;
using System.Security;
using System.Security.Principal;
namespace DotNetNuke.MSBuild.Tasks
{
class DirectoryManager
{
public delegate void FileCopied(string Source, string Destination);
public static event FileCopied OnFileCopied;
public static void DeleteFolder(string Path)
{
System.IO.Directory.Delete(Path, true);
}
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
// Check if the target directory exists, if not, create it.
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
// Copy each file into it’s new directory.
foreach (var fi in source.GetFiles())
{
//System.Diagnostics.Trace.WriteLine(string.Format(@"Copying {0}\{1}", target.FullName, fi.Name));
var filePath = Path.Combine(target.ToString(), fi.Name);
if(File.Exists(filePath))
File.Delete(filePath);
try
{
fi.CopyTo(filePath, true);
}
catch (Exception)
{
}
if (OnFileCopied != null) OnFileCopied(fi.FullName, Path.Combine(target.ToString(), fi.Name));
}
// Copy each subdirectory using recursion.
foreach (var diSourceSubDir in source.GetDirectories())
{
var nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
public static void SetFolderPermissions(FileInfo Target, string ACLUser)
{
FileSecurity fileSec = Target.GetAccessControl();
FileSystemAccessRule fsRule = new FileSystemAccessRule(ACLUser, FileSystemRights.FullControl, AccessControlType.Allow);
fileSec.AddAccessRule(fsRule);
bool modified = false;
fileSec.ModifyAccessRule(AccessControlModification.Add, fsRule, out modified);
Target.SetAccessControl(fileSec);
}
public static void SetFolderPermissions(string ACLUser, DirectoryInfo Target)
{
//RemoveInheritablePermissons(Target);
DirectorySecurity dirSec = new DirectorySecurity(Target.FullName, AccessControlSections.All);
FileSystemAccessRule fsRuleCurrentFolder = new FileSystemAccessRule(ACLUser, FileSystemRights.Read | FileSystemRights.Write | FileSystemRights.ChangePermissions | FileSystemRights.Delete, AccessControlType.Allow);
dirSec.SetAccessRule(fsRuleCurrentFolder);
FileSystemAccessRule fsRuleSubFoldersAndFiles = new FileSystemAccessRule(ACLUser, FileSystemRights.Read | FileSystemRights.Write | FileSystemRights.ChangePermissions | FileSystemRights.Delete, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow);
dirSec.AddAccessRule(fsRuleSubFoldersAndFiles);
Target.SetAccessControl(dirSec);
}
// Removes an ACL entry on the specified directory for the specified account.
public static void RemoveInheritablePermissons(DirectoryInfo Directory)
{
// Create a new DirectoryInfo object.
// Get a DirectorySecurity object that represents the
// current security settings.
DirectorySecurity dSecurity = Directory.GetAccessControl();
// Add the FileSystemAccessRule to the security settings.
const bool IsProtected = true;
const bool PreserveInheritance = false;
dSecurity.SetAccessRuleProtection(IsProtected, PreserveInheritance);
// Set the new access settings.
Directory.SetAccessControl(dSecurity);
}
}
} |
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace Centroid.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public System.Data.Entity.DbSet<Centroid.Models.Home> Homes { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.About> Abouts { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.Job> Jobs { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.ProfileDocument> ProfileDocuments { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.Service> Services { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.ServiceDetails> ServiceDetails { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.Project> Projects { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.QHSE> QHSEs { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.JobApplication> JobApplications { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.PersonalInfo> PersonalInfoes { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.Education> Educations { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.WorkExperience> WorkExperiences { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.ContactUs> ContactUs { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.Career> Careers { get; set; }
public System.Data.Entity.DbSet<Centroid.Models.KeyRecord> KeyRecords { get; set; }
}
} |
using System;
using DelftTools.Shell.Core;
using DelftTools.Shell.Core.Workflow;
using DelftTools.Units.Generics;
namespace DelftTools.Tests.Core.Mocks
{
public class TestModel : TimeDependentModelBase
{
public TestModel() : this("new test model")
{
}
public TestModel(string name) : base(name)
{
// add some test data items
base.DataItems.Add(new DataItem(new Parameter<int>("int parameter")) {Role = DataItemRole.Output});
// time step parameter
TimeStep = new TimeSpan(0, 0, 5);
}
public override void OnCleanup()
{
throw new Exception("The method or operation is not implemented.");
}
protected override void OnInitialize()
{
}
protected override bool OnExecute()
{
Parameter<int> p = DataItems[4].Value as Parameter<int>;
if (p != null) p.Value = 2 + 2;
return true;
}
public override void LoadDataFromDirectory(string path)
{
}
public override void SaveDataToDirectory(string path)
{
throw new NotImplementedException("SaveState is not implemented");
}
public override bool IsDataItemValid(IDataItem dataItem)
{
return true;
}
public override bool IsLinkAllowed(IDataItem source, IDataItem target)
{
return true;
}
}
}
|
using UnityEngine;
namespace FancyScrollView
{
public abstract class FancyScrollViewCell<TItemData, TContext> : MonoBehaviour where TContext : class, new()
{
public int Index { get; set; } = -1;
public virtual bool IsVisible => gameObject.activeSelf;
protected TContext Context { get; private set; }
public virtual void SetupContext(TContext context) => Context = context;
public virtual void SetVisible(bool visible) => gameObject.SetActive(visible);
public abstract void UpdateContent(TItemData itemData);
public abstract void UpdatePosition(float position);
}
public abstract class FancyScrollViewCell<TItemData> : FancyScrollViewCell<TItemData, FancyScrollViewNullContext>
{
public sealed override void SetupContext(FancyScrollViewNullContext context) => base.SetupContext(context);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Facturacion.Web.Data
{
public class Owner
{
public int ID { get; set; }
[MaxLength(30, ErrorMessage = "The field {0} only can contain a maximum {1} characters")]
[Required(ErrorMessage = "The field {0} is mandatory.")]
public string Document { get; set; }
[MaxLength(50, ErrorMessage = "The field {0} only can contain a maximum {1} characters")]
[Required(ErrorMessage = "The field {0} is mandatory.")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[MaxLength(50, ErrorMessage = "The field {0} only can contain a maximum {1} characters")]
[Required(ErrorMessage = "The field {0} is mandatory.")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[MaxLength(12, ErrorMessage = "The field {0} only can contain a maximum {1} characters")]
[Display(Name = "Fixed Phone")]
public string FixedPhone { get; set; }
[MaxLenght(12, ErrorMessage: "The {0} field can not have more than {1} characters.")]
[Required(ErrorMessage = "The field {0} is mandatory.")]
[Display(Name = "Cellphone")]
public string CellPhone { get; set; }
[MaxLength(100, ErrorMessage = "The field {0} only can contain a maximum {1} characters")]
public string Address { get; set; }
[Display(Name = "Owner")]
public string FullName => $"{FirstName} {LastName}";
[Display(Name = "Owner")]
public string FullNameWithDocument => $"{FirstName} {LastName} - {Document}";
}
}
|
using Euler_Logic.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public class Problem248 : ProblemBase {
public override string ProblemName {
get { return "248: Numbers for which Euler’s totient function equals 13!"; }
}
public override string GetAnswer() {
var fact = new FactorialWithHashULong();
var x = fact.Get(13);
return Test().ToString();
}
private ulong Test() {
int count = 0;
ulong num = 6227180928;
ulong fact = new FactorialWithHashULong().Get(13);
do {
num++;
if (Totient(num, fact) == fact) {
count++;
}
} while (count < 150000);
return num;
}
private ulong Totient(ulong num, ulong fact) {
var primes = new PrimeSieve((ulong)Math.Sqrt(num));
var fraction = new Fraction(num, 1);
foreach (var prime in primes.Enumerate) {
if (num % prime == 0) {
fraction.Multiply(prime - 1, prime);
do {
num /= prime;
} while (num % prime == 0);
if (fraction.X < fact) {
return 0;
}
}
}
if (num != 1) {
fraction.Multiply(num - 1, num);
}
return fraction.X;
}
}
}
|
using System.Collections.Generic;
namespace Jira_Bulk_Issues_Helper.Models
{
public class Project
{
public string self { get; set; }
public string id { get; set; }
public string key { get; set; }
public string name { get; set; }
public AvatarUrls avatarUrls { get; set; }
public IList<IssueType> issuetypes { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Thingy.WebServerLite
{
public class KnownUserFactory : IKnownUserFactory
{
private readonly string[] defaultRoles;
private readonly IKnownUser[] defaultKnownUsers;
private readonly char[] comma = new char[] { ',' };
private readonly char[] semiColon = new char[] { ',' };
public KnownUserFactory(string[] defaultRoles, string[] users)
{
this.defaultRoles = defaultRoles;
this.defaultKnownUsers = users.Select(u => u.Split(comma)).Select(s => Create("", s[0], s[1], s[2].Split(semiColon))).ToArray();
}
public IKnownUser Create(string ipAddress, string userId, string password)
{
return Create(ipAddress, userId, password, defaultRoles);
}
public IKnownUser Create(string ipAddress, string userId, string password, string[] roles)
{
return new KnownUser(ipAddress, userId, password, roles);
}
public IEnumerable<IKnownUser> GetDefaultKnownUsers()
{
return defaultKnownUsers;
}
}
}
|
using MonoDevelop.Projects;
using System;
namespace MonoDevelop.NUnit
{
public class SystemTestProvider : ITestProvider
{
public UnitTest CreateUnitTest(IWorkspaceObject entry)
{
UnitTest test = null;
if (entry is SolutionFolder)
{
test = SolutionFolderTestGroup.CreateTest((SolutionFolder)entry);
}
if (entry is Solution)
{
test = SolutionFolderTestGroup.CreateTest(((Solution)entry).get_RootFolder());
}
if (entry is Workspace)
{
test = WorkspaceTestGroup.CreateTest((Workspace)entry);
}
if (entry is DotNetProject)
{
test = NUnitProjectTestSuite.CreateTest((DotNetProject)entry);
}
if (entry is NUnitAssemblyGroupProject)
{
test = ((NUnitAssemblyGroupProject)entry).RootTest;
}
UnitTestGroup grp = test as UnitTestGroup;
UnitTest result;
if (grp != null && !grp.HasTests)
{
result = null;
}
else
{
result = test;
}
return result;
}
public System.Type[] GetOptionTypes()
{
return new System.Type[]
{
typeof(GeneralTestOptions),
typeof(NUnitCategoryOptions)
};
}
}
}
|
using System.Data.Entity;
class ApplicationContext : DbContext
{
public ApplicationContext() : base("dbImportXML") { }
public DbSet<Client> Clients { get; set; }
}
|
using System.IO;
using System.Linq;
using UnityEditorInternal;
using UnityEngine;
namespace Needle.Demystify
{
#if !UNITY_2020_1_OR_NEWER
public class ScriptableSingleton<T> : ScriptableObject where T : ScriptableObject
{
private static T s_Instance;
public static T instance
{
get
{
if (!s_Instance) CreateAndLoad();
return s_Instance;
}
}
protected ScriptableSingleton()
{
if (s_Instance)
Debug.LogError("ScriptableSingleton already exists. Did you query the singleton in a constructor?");
else
{
object casted = this;
s_Instance = casted as T;
System.Diagnostics.Debug.Assert(s_Instance != null);
}
}
private static void CreateAndLoad()
{
System.Diagnostics.Debug.Assert(s_Instance == null);
// Load
var filePath = GetFilePath();
#if UNITY_EDITOR
if (!string.IsNullOrEmpty(filePath))
InternalEditorUtility.LoadSerializedFileAndForget(filePath);
#endif
if (s_Instance == null)
{
var t = CreateInstance<T>();
t.hideFlags = HideFlags.HideAndDontSave;
}
System.Diagnostics.Debug.Assert(s_Instance != null);
}
protected virtual void Save(bool saveAsText)
{
if (!s_Instance)
{
Debug.Log("Cannot save ScriptableSingleton: no instance!");
return;
}
var filePath = GetFilePath();
if (string.IsNullOrEmpty(filePath)) return;
var folderPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(folderPath) && !string.IsNullOrEmpty(folderPath))
Directory.CreateDirectory(folderPath);
#if UNITY_EDITOR
InternalEditorUtility.SaveToSerializedFileAndForget(new[] {s_Instance}, filePath, saveAsText);
#endif
}
private static string GetFilePath()
{
var type = typeof(T);
var attributes = type.GetCustomAttributes(true);
return attributes.OfType<FilePathAttribute>()
.Select(f => f.filepath)
.FirstOrDefault();
}
}
[System.AttributeUsage(System.AttributeTargets.Class)]
internal sealed class FilePathAttribute : System.Attribute
{
public enum Location
{
PreferencesFolder,
ProjectFolder
}
public string filepath { get; set; }
public FilePathAttribute(string relativePath, FilePathAttribute.Location location)
{
if (string.IsNullOrEmpty(relativePath))
{
Debug.LogError("Invalid relative path! (its null or empty)");
return;
}
if (relativePath[0] == '/')
relativePath = relativePath.Substring(1);
#if UNITY_EDITOR
if (location == FilePathAttribute.Location.PreferencesFolder)
this.filepath = InternalEditorUtility.unityPreferencesFolder + "/" + relativePath;
else
#endif
this.filepath = relativePath;
}
}
#endif
} |
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 Requerimiento Párrafo Variable
/// </summary>
/// <remarks>
/// Creación : GMD 20150609 <br />
/// Modificación : <br />
/// </remarks>
public class RequerimientoParrafoVariableRequest : Filtro
{
/// <summary>
/// Código de Requerimiento Párrafo Variable
/// </summary>
public string CodigoRequerimientoParrafoVariable { get; set; }
/// <summary>
/// Código de Requerimiento Párrafo
/// </summary>
public string CodigoRequerimientoParrafo { get; set; }
/// <summary>
/// Código de Variable
/// </summary>
public string CodigoVariable { get; set; }
/// <summary>
/// Valor de Variable Texto
/// </summary>
public string ValorTexto { get; set; }
/// <summary>
/// Valor de Variable Número
/// </summary>
public string ValorNumeroString { get; set; }
/// <summary>
/// Valor de Variable Fecha
/// </summary>
public string ValorFechaString { get; set; }
/// <summary>
/// Valor de Variable Imagen
/// </summary>
public byte[] ValorImagen { get; set; }
/// <summary>
/// Valor de Variable Tabla
/// </summary>
public string ValorTabla { get; set; }
/// <summary>
/// Valor de Variable Tabla Editable
/// </summary>
public string ValorTablaEditable { get; set; }
/// <summary>
/// Valor de Variable Bien
/// </summary>
public string ValorBien { get; set; }
/// <summary>
/// Valor de Variable Bien Editable
/// </summary>
public string ValorBienEditable { get; set; }
/// <summary>
/// Valor de Variable Firmante
/// </summary>
public string ValorFirmante { get; set; }
/// <summary>
/// Valor de Variable Firmante Editable
/// </summary>
public string ValorFirmanteEditable { get; set; }
/// <summary>
/// Código de Tipo de Variable
/// </summary>
public string CodigoTipoVariable { get; set; }
/// <summary>
/// Valor de Variable
/// </summary>
public string Valor { get; set; }
/// <summary>
/// Valor de Variable Editable
/// </summary>
public string ValorEditable { get; set; }
/// <summary>
/// Código de Plantilla Párrafo
/// </summary>
public string CodigoPlantillaParrafo { get; set; }
/// <summary>
/// Valor de Variable Lista
/// </summary>
public string ValorLista { get; set; }
}
}
|
using System;
namespace HTB.Database.LookupRecords
{
public class AuftraggeberDetailLookup
{
#region Property Declaration
public int AgId { get; set; }
public string AgName { get; set; }
public string AgLKZ { get; set; }
public string AgOrt { get; set; }
public string AgStrasse { get; set; }
public string AgPhoneCountry { get; set; }
public string AgPhoneCity { get; set; }
public string AgPhone { get; set; }
public int InterventionAkte { get; set; }
public int InkassoAkte { get; set; }
public double InkassoBalance { get; set; }
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
namespace LeetCodeTests
{
public abstract class Problem_0078
{
/*
Given a set of distinct integers, nums, return all possible subsets(the power set).
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1, 2, 3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
*/
public static void Test()
{
Solution sol = new Solution();
/*
var input = new int[] { 2, 7, 11, 15 };
Console.WriteLine($"Input array: {string.Join(", ", input)}");
*/
var nums = new int[] { 1, 2, 3 };
Console.WriteLine($"for input '{Utils.PrintArray(nums)}' -> '{Utils.PrintArray(sol.Subsets(nums))}'");
}
public class Solution_Binary
{
/*
have array of numbers. Need find all combinations.
If we present set as binary map 0010100 where 1 mean using number from NUMS at same position, we need just pass through all numbers
starts from 0 to 2^(NUMS.length)
We need (NUMS.length / 32)+1 int numbers to present all possibilities
*/
public IList<IList<int>> Subsets(int[] nums)
{
List<IList<int>> resList = new List<IList<int>>();
return resList;
}
}
/// <summary>
/// Recursive solution
/// </summary>
public class Solution
{
public IList<IList<int>> Subsets(int[] nums)
{
List<IList<int>> resList = new List<IList<int>>();
backtrack(resList, new List<int>(), nums, 0);
return resList;
}
public void backtrack(List<IList<int>> resList, List<int> accum, int[] nums, int startPos)
{
resList.Add(new List<int>(accum));
for (int i = startPos; i < nums.Length; i++)
{
accum.Add(nums[i]);
backtrack(resList, accum, nums, i + 1);
accum.RemoveAt(accum.Count - 1);
}
}
}
}//public abstract class Problem_
} |
using System;
using System.Collections.Generic;
namespace Dimension_Data_Collab.Models
{
public partial class Education
{
public string EducationId { get; set; }
public string EducationField { get; set; }
public string EducationYears { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightingBook.Tests.Api.Product.Dto.Flight
{
public class Detail
{
public string Codes { get; set; }
public string Rates { get; set; }
public string FlightClass { get; set; }
public string FlightBrandName { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace HospitalSystem.Models.Mapping
{
public class prescriptionMap : EntityTypeConfiguration<prescription>
{
public prescriptionMap()
{
// Primary Key
this.HasKey(t => t.PrescriptionID);
// Properties
// Table & Column Mappings
this.ToTable("prescription", "teamwork");
this.Property(t => t.PrescriptionID).HasColumnName("PrescriptionID");
this.Property(t => t.MedicalRecordID).HasColumnName("MedicalRecordID");
// Relationships
this.HasOptional(t => t.medical_record)
.WithMany(t => t.prescriptions)
.HasForeignKey(d => d.MedicalRecordID);
}
}
}
|
using jaytwo.Common.Extensions;
using jaytwo.Common.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace jaytwo.Common.Test.Http
{
[TestFixture]
public static partial class HttpProviderTests
{
private static IEnumerable<TestCaseData> HttpProvider_SubmitPost_TestCases()
{
yield return new TestCaseData(new Func<string, HttpWebResponse>(url => new HttpClient().SubmitPost(url)));
yield return new TestCaseData(new Func<string, HttpWebResponse>(url => new HttpClient().SubmitPost(new Uri(url))));
yield return new TestCaseData(new Func<string, HttpWebResponse>(url => new HttpClient().SubmitPost(WebRequest.Create(url) as HttpWebRequest)));
yield return new TestCaseData(new Func<string, HttpWebResponse>(url => HttpProvider.SubmitPost(url)));
yield return new TestCaseData(new Func<string, HttpWebResponse>(url => HttpProvider.SubmitPost(new Uri(url))));
yield return new TestCaseData(new Func<string, HttpWebResponse>(url => HttpProvider.SubmitPost(WebRequest.Create(url) as HttpWebRequest)));
yield return new TestCaseData(new Func<string, HttpWebResponse>(url => new Uri(url).SubmitPost()));
yield return new TestCaseData(new Func<string, HttpWebResponse>(url => (WebRequest.Create(url) as HttpWebRequest).SubmitPost()));
}
[Test]
[TestCaseSource("HttpProvider_SubmitPost_TestCases")]
public static void HttpProvider_SubmitPost(Func<string, HttpWebResponse> submitMethod)
{
// http://httpbin.org/
var url = "http://httpbin.org/post";
using (var response = submitMethod(url))
{
var responseString = HttpHelper.GetContentAsString(response);
Console.WriteLine(responseString);
HttpHelper.VerifyResponseStatusOK(response);
var result = JsonConvert.DeserializeObject<JObject>(responseString);
Assert.AreEqual(url, result["url"].ToString());
}
}
private static IEnumerable<TestCaseData> HttpProvider_SubmitPost_with_content_TestCases()
{
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => new HttpClient().SubmitPost(url, content)));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => new HttpClient().SubmitPost(new Uri(url), content)));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => new HttpClient().SubmitPost(WebRequest.Create(url) as HttpWebRequest, content)));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => HttpProvider.SubmitPost(url, content)));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => HttpProvider.SubmitPost(new Uri(url), content)));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => HttpProvider.SubmitPost(WebRequest.Create(url) as HttpWebRequest, content)));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => new Uri(url).SubmitPost(content)));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => (WebRequest.Create(url) as HttpWebRequest).SubmitPost(content)));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => new HttpClient().SubmitPost(url, Encoding.UTF8.GetBytes(content))));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => new HttpClient().SubmitPost(new Uri(url), Encoding.UTF8.GetBytes(content))));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => new HttpClient().SubmitPost(WebRequest.Create(url) as HttpWebRequest, Encoding.UTF8.GetBytes(content))));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => HttpProvider.SubmitPost(url, Encoding.UTF8.GetBytes(content))));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => HttpProvider.SubmitPost(new Uri(url), Encoding.UTF8.GetBytes(content))));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => HttpProvider.SubmitPost(WebRequest.Create(url) as HttpWebRequest, Encoding.UTF8.GetBytes(content))));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => new Uri(url).SubmitPost(Encoding.UTF8.GetBytes(content))));
yield return new TestCaseData(new Func<string, string, HttpWebResponse>((url, content) => (WebRequest.Create(url) as HttpWebRequest).SubmitPost(Encoding.UTF8.GetBytes(content))));
}
[Test]
[TestCaseSource("HttpProvider_SubmitPost_with_content_TestCases")]
public static void HttpProvider_SubmitPost_with_content(Func<string, string, HttpWebResponse> submitMethod)
{
// http://httpbin.org/
var url = "http://httpbin.org/post";
var content = "hello world";
//var contentType = "application/custom";
using (var response = submitMethod(url, content))
{
var responseString = HttpHelper.GetContentAsString(response);
Console.WriteLine(responseString);
HttpHelper.VerifyResponseStatusOK(response);
var result = JsonConvert.DeserializeObject<JObject>(responseString);
Assert.AreEqual(url, result["url"].ToString());
//Assert.AreEqual("application/custom; charset=utf-8", result["headers"]["Content-Type"].ToString());
Assert.AreEqual(content, result["data"].ToString());
}
}
private static IEnumerable<TestCaseData> HttpProvider_SubmitPost_with_content_contentType_TestCases()
{
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => new HttpClient().SubmitPost(url, content, contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => new HttpClient().SubmitPost(new Uri(url), content, contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => new HttpClient().SubmitPost(WebRequest.Create(url) as HttpWebRequest, content, contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => HttpProvider.SubmitPost(url, content, contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => HttpProvider.SubmitPost(new Uri(url), content, contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => HttpProvider.SubmitPost(WebRequest.Create(url) as HttpWebRequest, content, contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => new Uri(url).SubmitPost(content, contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => (WebRequest.Create(url) as HttpWebRequest).SubmitPost(content, contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => new HttpClient().SubmitPost(url, Encoding.UTF8.GetBytes(content), contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => new HttpClient().SubmitPost(new Uri(url), Encoding.UTF8.GetBytes(content), contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => new HttpClient().SubmitPost(WebRequest.Create(url) as HttpWebRequest, Encoding.UTF8.GetBytes(content), contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => HttpProvider.SubmitPost(url, Encoding.UTF8.GetBytes(content), contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => HttpProvider.SubmitPost(new Uri(url), Encoding.UTF8.GetBytes(content), contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => HttpProvider.SubmitPost(WebRequest.Create(url) as HttpWebRequest, Encoding.UTF8.GetBytes(content), contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => new Uri(url).SubmitPost(Encoding.UTF8.GetBytes(content), contentType)));
yield return new TestCaseData(new Func<string, string, string, HttpWebResponse>((url, content, contentType) => (WebRequest.Create(url) as HttpWebRequest).SubmitPost(Encoding.UTF8.GetBytes(content), contentType)));
}
[Test]
[TestCaseSource("HttpProvider_SubmitPost_with_content_contentType_TestCases")]
public static void HttpProvider_SubmitPost_with_content_contentType(Func<string, string, string, HttpWebResponse> submitMethod)
{
// http://httpbin.org/
var url = "http://httpbin.org/post";
var content = "hello world";
var contentType = "application/custom";
using (var response = submitMethod(url, content, contentType))
{
var responseString = HttpHelper.GetContentAsString(response);
Console.WriteLine(responseString);
HttpHelper.VerifyResponseStatusOK(response);
var result = JsonConvert.DeserializeObject<JObject>(responseString);
Assert.AreEqual(url, result["url"].ToString());
Assert.AreEqual("application/custom; charset=utf-8", result["headers"]["Content-Type"].ToString());
Assert.AreEqual(content, result["data"].ToString());
}
}
private static IEnumerable<TestCaseData> HttpProvider_SubmitPost_with_form_TestCases()
{
yield return new TestCaseData(new Func<string, NameValueCollection, HttpWebResponse>((url, content) => new HttpClient().SubmitPost(url, content)));
yield return new TestCaseData(new Func<string, NameValueCollection, HttpWebResponse>((url, content) => new HttpClient().SubmitPost(new Uri(url), content)));
yield return new TestCaseData(new Func<string, NameValueCollection, HttpWebResponse>((url, content) => new HttpClient().SubmitPost(WebRequest.Create(url) as HttpWebRequest, content)));
yield return new TestCaseData(new Func<string, NameValueCollection, HttpWebResponse>((url, content) => HttpProvider.SubmitPost(url, content)));
yield return new TestCaseData(new Func<string, NameValueCollection, HttpWebResponse>((url, content) => HttpProvider.SubmitPost(new Uri(url), content)));
yield return new TestCaseData(new Func<string, NameValueCollection, HttpWebResponse>((url, content) => HttpProvider.SubmitPost(WebRequest.Create(url) as HttpWebRequest, content)));
yield return new TestCaseData(new Func<string, NameValueCollection, HttpWebResponse>((url, content) => new Uri(url).SubmitPost(content)));
yield return new TestCaseData(new Func<string, NameValueCollection, HttpWebResponse>((url, content) => (WebRequest.Create(url) as HttpWebRequest).SubmitPost(content)));
}
[Test]
[TestCaseSource("HttpProvider_SubmitPost_with_form_TestCases")]
public static void HttpProvider_SubmitPost_with_form(Func<string, NameValueCollection, HttpWebResponse> submitMethod)
{
// http://httpbin.org/
var url = "http://httpbin.org/post";
var form = new NameValueCollection() { { "hello", "world" } };
using (var response = submitMethod(url, form))
{
var responseString = HttpHelper.GetContentAsString(response);
Console.WriteLine(responseString);
HttpHelper.VerifyResponseStatusOK(response);
var result = JsonConvert.DeserializeObject<JObject>(responseString);
Assert.AreEqual(url, result["url"].ToString());
//Assert.AreEqual("application/custom; charset=utf-8", result["headers"]["Content-Type"].ToString());
Assert.AreEqual("world", result["form"]["hello"].ToString());
}
}
private static IEnumerable<TestCaseData> HttpProvider_SubmitPost_with_stream_TestCases()
{
yield return new TestCaseData(new Func<string, Stream, HttpWebResponse>((url, content) => new HttpClient().SubmitPost(url, content)));
yield return new TestCaseData(new Func<string, Stream, HttpWebResponse>((url, content) => new HttpClient().SubmitPost(new Uri(url), content)));
yield return new TestCaseData(new Func<string, Stream, HttpWebResponse>((url, content) => new HttpClient().SubmitPost(WebRequest.Create(url) as HttpWebRequest, content)));
yield return new TestCaseData(new Func<string, Stream, HttpWebResponse>((url, content) => HttpProvider.SubmitPost(url, content)));
yield return new TestCaseData(new Func<string, Stream, HttpWebResponse>((url, content) => HttpProvider.SubmitPost(new Uri(url), content)));
yield return new TestCaseData(new Func<string, Stream, HttpWebResponse>((url, content) => HttpProvider.SubmitPost(WebRequest.Create(url) as HttpWebRequest, content)));
yield return new TestCaseData(new Func<string, Stream, HttpWebResponse>((url, content) => new Uri(url).SubmitPost(content)));
yield return new TestCaseData(new Func<string, Stream, HttpWebResponse>((url, content) => (WebRequest.Create(url) as HttpWebRequest).SubmitPost(content)));
}
[Test]
[TestCaseSource("HttpProvider_SubmitPost_with_stream_TestCases")]
public static void HttpProvider_SubmitPost_with_stream(Func<string, Stream, HttpWebResponse> submitMethod)
{
// http://httpbin.org/
var url = "http://httpbin.org/post";
var content = "hello world";
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
using (var response = submitMethod(url, stream))
{
var responseString = response.DownloadString();
Console.WriteLine(responseString);
response.VerifyResponseStatusOK();
var result = JsonConvert.DeserializeObject<JObject>(responseString);
Assert.AreEqual(url, result["url"].ToString());
//Assert.AreEqual("application/custom; charset=utf-8", result["headers"]["Content-Type"].ToString());
Assert.AreEqual(content, result["data"].ToString());
}
}
private static IEnumerable<TestCaseData> HttpProvider_SubmitPost_with_stream_contentType_TestCases()
{
yield return new TestCaseData(new Func<string, Stream, string, HttpWebResponse>((url, content, contentType) => new HttpClient().SubmitPost(url, content, contentType)));
yield return new TestCaseData(new Func<string, Stream, string, HttpWebResponse>((url, content, contentType) => new HttpClient().SubmitPost(new Uri(url), content, contentType)));
yield return new TestCaseData(new Func<string, Stream, string, HttpWebResponse>((url, content, contentType) => new HttpClient().SubmitPost(WebRequest.Create(url) as HttpWebRequest, content, contentType)));
yield return new TestCaseData(new Func<string, Stream, string, HttpWebResponse>((url, content, contentType) => HttpProvider.SubmitPost(url, content, contentType)));
yield return new TestCaseData(new Func<string, Stream, string, HttpWebResponse>((url, content, contentType) => HttpProvider.SubmitPost(new Uri(url), content, contentType)));
yield return new TestCaseData(new Func<string, Stream, string, HttpWebResponse>((url, content, contentType) => HttpProvider.SubmitPost(WebRequest.Create(url) as HttpWebRequest, content, contentType)));
yield return new TestCaseData(new Func<string, Stream, string, HttpWebResponse>((url, content, contentType) => new Uri(url).SubmitPost(content, contentType)));
yield return new TestCaseData(new Func<string, Stream, string, HttpWebResponse>((url, content, contentType) => (WebRequest.Create(url) as HttpWebRequest).SubmitPost(content, contentType)));
}
[Test]
[TestCaseSource("HttpProvider_SubmitPost_with_stream_contentType_TestCases")]
public static void HttpProvider_SubmitPost_with_stream_contentType(Func<string, Stream, string, HttpWebResponse> submitMethod)
{
// http://httpbin.org/
var url = "http://httpbin.org/post";
var contentType = "application/custom";
var content = "hello world";
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
using (var response = submitMethod(url, stream, contentType))
{
var responseString = response.DownloadString();
Console.WriteLine(responseString);
response.VerifyResponseStatusOK();
var result = JsonConvert.DeserializeObject<JObject>(responseString);
Assert.AreEqual(url, result["url"].ToString());
Assert.AreEqual("application/custom; charset=utf-8", result["headers"]["Content-Type"].ToString());
Assert.AreEqual(content, result["data"].ToString());
}
}
private static IEnumerable<TestCaseData> HttpProvider_SubmitPost_with_stream_contentLength_TestCases()
{
yield return new TestCaseData(new Func<string, Stream, long, HttpWebResponse>((url, content, contentLength) => new HttpClient().SubmitPost(url, content, contentLength)));
yield return new TestCaseData(new Func<string, Stream, long, HttpWebResponse>((url, content, contentLength) => new HttpClient().SubmitPost(new Uri(url), content, contentLength)));
yield return new TestCaseData(new Func<string, Stream, long, HttpWebResponse>((url, content, contentLength) => new HttpClient().SubmitPost(WebRequest.Create(url) as HttpWebRequest, content, contentLength)));
yield return new TestCaseData(new Func<string, Stream, long, HttpWebResponse>((url, content, contentLength) => HttpProvider.SubmitPost(url, content, contentLength)));
yield return new TestCaseData(new Func<string, Stream, long, HttpWebResponse>((url, content, contentLength) => HttpProvider.SubmitPost(new Uri(url), content, contentLength)));
yield return new TestCaseData(new Func<string, Stream, long, HttpWebResponse>((url, content, contentLength) => HttpProvider.SubmitPost(WebRequest.Create(url) as HttpWebRequest, content, contentLength)));
yield return new TestCaseData(new Func<string, Stream, long, HttpWebResponse>((url, content, contentLength) => new Uri(url).SubmitPost(content, contentLength)));
yield return new TestCaseData(new Func<string, Stream, long, HttpWebResponse>((url, content, contentLength) => (WebRequest.Create(url) as HttpWebRequest).SubmitPost(content, contentLength)));
}
[Test]
[TestCaseSource("HttpProvider_SubmitPost_with_stream_contentLength_TestCases")]
public static void HttpProvider_SubmitPost_with_stream_contentLength(Func<string, Stream, long, HttpWebResponse> submitMethod)
{
// http://httpbin.org/
var url = "http://httpbin.org/post";
//var contentType = "application/custom";
var content = "hello world";
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
using (var response = submitMethod(url, stream, content.Length))
{
var responseString = response.DownloadString();
Console.WriteLine(responseString);
response.VerifyResponseStatusOK();
var result = JsonConvert.DeserializeObject<JObject>(responseString);
Assert.AreEqual(url, result["url"].ToString());
//Assert.AreEqual("application/custom; charset=utf-8", result["headers"]["Content-Type"].ToString());
Assert.AreEqual(content, result["data"].ToString());
}
}
private static IEnumerable<TestCaseData> HttpProvider_SubmitPost_with_stream_contentLength_contentType_TestCases()
{
yield return new TestCaseData(new Func<string, Stream, long, string, HttpWebResponse>((url, content, contentLength, contentType) => new HttpClient().SubmitPost(url, content, contentLength, contentType)));
yield return new TestCaseData(new Func<string, Stream, long, string, HttpWebResponse>((url, content, contentLength, contentType) => new HttpClient().SubmitPost(new Uri(url), content, contentLength, contentType)));
yield return new TestCaseData(new Func<string, Stream, long, string, HttpWebResponse>((url, content, contentLength, contentType) => new HttpClient().SubmitPost(WebRequest.Create(url) as HttpWebRequest, content, contentLength, contentType)));
yield return new TestCaseData(new Func<string, Stream, long, string, HttpWebResponse>((url, content, contentLength, contentType) => HttpProvider.SubmitPost(url, content, contentLength, contentType)));
yield return new TestCaseData(new Func<string, Stream, long, string, HttpWebResponse>((url, content, contentLength, contentType) => HttpProvider.SubmitPost(new Uri(url), content, contentLength, contentType)));
yield return new TestCaseData(new Func<string, Stream, long, string, HttpWebResponse>((url, content, contentLength, contentType) => HttpProvider.SubmitPost(WebRequest.Create(url) as HttpWebRequest, content, contentLength, contentType)));
yield return new TestCaseData(new Func<string, Stream, long, string, HttpWebResponse>((url, content, contentLength, contentType) => new Uri(url).SubmitPost(content, contentLength, contentType)));
yield return new TestCaseData(new Func<string, Stream, long, string, HttpWebResponse>((url, content, contentLength, contentType) => (WebRequest.Create(url) as HttpWebRequest).SubmitPost(content, contentLength, contentType)));
}
[Test]
[TestCaseSource("HttpProvider_SubmitPost_with_stream_contentLength_contentType_TestCases")]
public static void HttpProvider_SubmitPost_with_stream_contentLength_contentType(Func<string, Stream, long, string, HttpWebResponse> submitMethod)
{
// http://httpbin.org/
var url = "http://httpbin.org/post";
var contentType = "application/custom";
var content = "hello world";
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
using (var response = submitMethod(url, stream, content.Length, contentType))
{
var responseString = response.DownloadString();
Console.WriteLine(responseString);
response.VerifyResponseStatusOK();
var result = JsonConvert.DeserializeObject<JObject>(responseString);
Assert.AreEqual(url, result["url"].ToString());
Assert.AreEqual("application/custom; charset=utf-8", result["headers"]["Content-Type"].ToString());
Assert.AreEqual(content, result["data"].ToString());
}
}
private static IEnumerable<TestCaseData> HttpProvider_SubmitPostJson_with_object_TestCases()
{
yield return new TestCaseData(new Func<string, object, HttpWebResponse>((url, content) => new HttpClient().SubmitPostJson(url, content)));
yield return new TestCaseData(new Func<string, object, HttpWebResponse>((url, content) => new HttpClient().SubmitPostJson(new Uri(url), content)));
yield return new TestCaseData(new Func<string, object, HttpWebResponse>((url, content) => new HttpClient().SubmitPostJson(WebRequest.Create(url) as HttpWebRequest, content)));
yield return new TestCaseData(new Func<string, object, HttpWebResponse>((url, content) => HttpProvider.SubmitPostJson(url, content)));
yield return new TestCaseData(new Func<string, object, HttpWebResponse>((url, content) => HttpProvider.SubmitPostJson(new Uri(url), content)));
yield return new TestCaseData(new Func<string, object, HttpWebResponse>((url, content) => HttpProvider.SubmitPostJson(WebRequest.Create(url) as HttpWebRequest, content)));
yield return new TestCaseData(new Func<string, object, HttpWebResponse>((url, content) => new Uri(url).SubmitPostJson(content)));
yield return new TestCaseData(new Func<string, object, HttpWebResponse>((url, content) => (WebRequest.Create(url) as HttpWebRequest).SubmitPostJson(content)));
}
[Test]
[TestCaseSource("HttpProvider_SubmitPostJson_with_object_TestCases")]
public static void HttpProvider_SubmitPostJson_with_object(Func<string, object, HttpWebResponse> submitMethod)
{
// http://httpbin.org/
var url = "http://httpbin.org/post";
var content = new { hello = "world" };
var contentJson = new JavaScriptSerializer().Serialize(content);
using (var response = submitMethod(url, content))
{
var responseString = response.DownloadString();
Console.WriteLine(responseString);
response.VerifyResponseStatusOK();
var result = JsonConvert.DeserializeObject<JObject>(responseString);
Assert.AreEqual(url, result["url"].ToString());
//Assert.AreEqual("application/custom; charset=utf-8", result["headers"]["Content-Type"].ToString());
Assert.AreEqual(contentJson, result["data"].ToString());
}
}
}
}
|
using System;
using System.Xml;
using JetBrains.Annotations;
// ReSharper disable once CheckNamespace
namespace Thinktecture
{
/// <summary>
/// Extensions for <see cref="XmlReader"/>.
/// </summary>
internal static class XmlReaderExtensions
{
[NotNull]
public static string GetLineInfo([NotNull] this XmlReader reader)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
return reader is IXmlLineInfo lineInfo ? $"Line {lineInfo.LineNumber}, position {lineInfo.LinePosition}." : String.Empty;
}
}
}
|
using Profiling2.Domain.Prf.Careers;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Profiling2.Domain.Prf
{
/// <summary>
/// This class used to populate inputs to PRF_SP_Search_SearchForPerson_NHibernate stored proc.
/// </summary>
public class SearchTerm
{
protected string Term { get; set; }
protected bool IsQuoted { get; set; }
protected IList<string> TermList { get; set; }
public string MilitaryId { get; set; }
public string FormattedPartialName { get; set; }
public string FormattedExactName { get; set; }
public int? RankId { get; set; }
public int? RoleId { get; set; }
public SearchTerm(string searchText, IList<Rank> ranks, IList<Role> roles)
{
this.Term = searchText;
if (!string.IsNullOrEmpty(searchText))
{
this.IsQuoted = searchText.Trim().StartsWith("\"") && searchText.Trim().EndsWith("\"");
this.TermList = (from s in searchText.Split(new char[] { ' ' })
where !string.IsNullOrEmpty(s)
select s.Trim()).ToList<string>();
if (searchText.IndexOf(' ') < 0)
this.MilitaryId = searchText.Replace("-", "").Replace("/", "").Replace(".", "");
if (!this.IsQuoted)
this.FormattedPartialName = string.Join(";", this.TermList);
this.FormattedExactName = string.Join(";", (from permutation in this.GetPermutations(new List<string>(), this.TermList, string.Empty)
select (this.IsQuoted ? permutation.Replace("\"", "") : permutation)).ToArray<string>());
if (ranks != null && roles != null)
foreach (string term in this.TermList)
{
if (ranks.Where(x => x.RankName == term).Any())
this.RankId = ranks.Where(x => string.Equals(x.RankName, term, StringComparison.OrdinalIgnoreCase)).First().Id;
if (roles.Where(x => x.RoleName == term).Any())
this.RoleId = roles.Where(x => string.Equals(x.RoleName, term, StringComparison.OrdinalIgnoreCase)).First().Id;
}
}
}
/// <summary>
/// Retrieves a list of all permutations of phrases derived from a series of words. Copied
/// </summary>
/// <param name="allPhrases">The list of phrases already derived. Should be an instantiated empty list for the initial call.</param>
/// <param name="terms">The series of words from which the phrases are derived.</param>
/// <param name="current">The current phrase that is being constructed. Should be empty string for the initial call.</param>
/// <returns>List of all permutations of phrases</returns>
private IList<string> GetPermutations(IList<string> allPhrases, IList<string> terms, string current)
{
List<string> temp;
//base step
if (terms.Count < 1)
{
allPhrases.Add(current.Trim());
}
//recursive step
else
{
for (int i = 0; i < terms.Count; i++)
{
temp = new List<string>(terms);
temp.RemoveAt(i);
allPhrases = GetPermutations(allPhrases, temp, current + terms[i] + " ");
}
}
return allPhrases;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BikeRaceApp
{
public partial class FormManageRaceDetails : Form
{
RaceManager rm;
private DataView dv;
int tempID = -1;
int raceIndex = -1;
int time = 0;
public FormManageRaceDetails(RaceManager rm)
{
this.rm = rm;
InitializeComponent();
//Setting the inital value for the finish time to the start time
dtpFinishTime.Value = DateTime.ParseExact("15:30:00", "HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture);
//Disabling the finish time DateTime picker
dtpFinishTime.Enabled = false;
//Disabling all races to be changed
rbtnRace1.Enabled = false;
rbtnRace2.Enabled = false;
rbtnRace3.Enabled = false;
rbtnRace4.Enabled = false;
//populate table
List<Rider> tempriders = rm.GetRiders();
//LISTVIEW PROPERTIES
lvSearch.View = View.Details;
lvSearch.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
//Add Columns
lvSearch.Columns.Add("Name", 150);
lvSearch.Columns.Add("Surname", 150);
lvSearch.Columns.Add("School", 150);
lvSearch.Columns.Add("ID Num", 150);
//Set datetime picker format
dtpFinishTime.Format = DateTimePickerFormat.Custom;
dtpFinishTime.CustomFormat = "HH:mm:ss";
//Fill Data Table
dv = new DataView(this.rm.FillDataTable());
PopulateListView(dv);
}
//Add riders to the list view so they will be visible to the user
private void PopulateListView(DataView dv)
{
//clearing listview
lvSearch.Items.Clear();
//Adding each rider 1 by 1
foreach (DataRow row in dv.ToTable().Rows)
{
lvSearch.Items.Add(new ListViewItem(new string[] { row[0].ToString(), row[1].ToString(), row[2].ToString(), row[3].ToString() }));
}
}
//Updating the rider that are showed based on the text in the Search Bar
private void txbSearchBar_TextChanged(object sender, EventArgs e)
{
//Making sure there are no invalid characters in the search bar
if (!Regex.IsMatch((txbSearchBar.Text), "^[a-zA-Z]*$"))
{
MessageBox.Show("You cannot enter 123!@# ect in a search bar", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Filtering the list view to only displayed searched for riders
dv.RowFilter = string.Format("Name Like '%{0}%'", txbSearchBar.Text);
PopulateListView(dv);
}
//Sending user to main menu
private void btnBack_Click(object sender, EventArgs e)
{
this.Hide();
FormMainMenu window = new FormMainMenu(rm);
window.FormClosed += (s, args) => this.Close();
window.Show();
}
//Checking to see if a specific rider has been selected and making the races theyre in avalible for time changes
private void lvSearch_SelectedIndexChanged(object sender, EventArgs e)
{
if (lvSearch.SelectedItems.Count > 0)
{
ListViewItem rowData = lvSearch.SelectedItems[0];
tempID = Convert.ToInt32(rowData.SubItems[3].Text) - 1;
}
List<bool> entryStatus = rm.GetRiderEntryStatus(tempID);
//Making each specific race avalible or not
rbtnRace1.Enabled = entryStatus[0];
rbtnRace2.Enabled = entryStatus[1];
rbtnRace3.Enabled = entryStatus[2];
rbtnRace4.Enabled = entryStatus[3];
}
//Updating the times for each race
private void rbtnRace1_CheckedChanged(object sender, EventArgs e)
{
if (!dtpFinishTime.Enabled)
{
dtpFinishTime.Enabled = true;
}
raceIndex = 0;
if (!rm.GetRaceTime(tempID,raceIndex).Equals("9999999") )
{
dtpFinishTime.Value = DateTime.ParseExact(rm.GetFinishTime(tempID, raceIndex), "HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture);
lblRaceTimeInput.Text = rm.GetRaceTime(tempID, raceIndex) + " Seconds";
}
}
//Updating the times for each race
private void rbtnRace2_CheckedChanged(object sender, EventArgs e)
{
if (!dtpFinishTime.Enabled)
{
dtpFinishTime.Enabled = true;
}
raceIndex = 1;
if (!rm.GetRaceTime(tempID, raceIndex).Equals("9999999"))
{
dtpFinishTime.Value = DateTime.ParseExact(rm.GetFinishTime(tempID, raceIndex), "HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture);
lblRaceTimeInput.Text = rm.GetRaceTime(tempID, raceIndex) + " Seconds";
}
}
//Updating the times for each race
private void rbtnRace3_CheckedChanged(object sender, EventArgs e)
{
if (!dtpFinishTime.Enabled)
{
dtpFinishTime.Enabled = true;
}
raceIndex = 2;
if (!rm.GetRaceTime(tempID, raceIndex).Equals("9999999"))
{
dtpFinishTime.Value = DateTime.ParseExact(rm.GetFinishTime(tempID, raceIndex), "HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture);
lblRaceTimeInput.Text = rm.GetRaceTime(tempID, raceIndex) + " Seconds";
}
}
//Updating the times for each race
private void rbtnRace4_CheckedChanged(object sender, EventArgs e)
{
if (!dtpFinishTime.Enabled)
{
dtpFinishTime.Enabled = true;
}
raceIndex = 3;
if (!rm.GetRaceTime(tempID, raceIndex).Equals("9999999"))
{
dtpFinishTime.Value = DateTime.ParseExact(rm.GetFinishTime(tempID, raceIndex), "HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture);
lblRaceTimeInput.Text = rm.GetRaceTime(tempID, raceIndex) + " Seconds";
}
}
//Making the updated times for each race save so that it will show up
private void btnUpdate_Click(object sender, EventArgs e)
{
//Checking race time
time = rm.GetCheckRaceTime(tempID, raceIndex);
rm.SetRiderFinishTime(tempID, raceIndex, dtpFinishTime.Text);
//Making sure the user hasent tried to make their race time less than 0
if (time > 0)
{
//Displaying error
MessageBox.Show("You cannot finnish the race before it started", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
System.Console.WriteLine(time);
}
else
{
//Saving users race time to race list
rm.SetRiderFinishTime(tempID, raceIndex, dtpFinishTime.Text);
lblRaceTimeInput.Text = rm.GetRaceTime(tempID, raceIndex) + " Seconds";
//Saving users race to .txt file
rm.SaveRiders();
}
}
//Setting custom font on the form
private void FormManageRaceDetails_Load(object sender, EventArgs e)
{
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile("Montserrat-Regular.ttf");
foreach (Control c in this.Controls)
{
c.Font = new Font(pfc.Families[0], c.Font.Size, c.Font.Style);
}
}
//Remove rider
private void btnRemoveRider_Click(object sender, EventArgs e)
{
//Changing the riders status to inactive
rm.SetRiderActive(tempID);
//Saving rider status to .txt file
rm.SaveRiders();
//Updating listview to display without the removed rider
dv = new DataView(this.rm.FillDataTable());
PopulateListView(dv);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using System;
public class Bullet : RecycleObject
{
Tween move;
float moveSpeed;
[SerializeField] Rigidbody rigid;
public Vector3 StartPosition;
public Action<Bullet> Destroyed;
float ForceValue;
Vector3[] lines;
public int direction;
public float initz;
public float rad;
[SerializeField] float inclination;
[SerializeField] Vector2 forward;
[SerializeField] Vector2 dir;
[SerializeField] Vector3 refectionPosition;
public void Initialize(float ForceValue, float moveSpeed)
{
this.ForceValue = ForceValue;
this.moveSpeed = moveSpeed;
StartPosition = transform.localPosition;
move.SetAutoKill(false);
}
public void moveBullet(Vector3[] lines)
{
this.lines = lines;
move = rigid.DOLocalPath(lines, moveSpeed).OnWaypointChange(x => StartPosition = lines[x - 1]).SetLookAt(0.01f)
.OnComplete(() =>
{
Destroy();
});
}
public void TweenKill()
{
move.Kill();
}
public void Reflection(Vector3 refectionPosition)
{
rigid.velocity = Vector3.zero;
rigid.velocity = refectionPosition * ForceValue;
this.refectionPosition = rigid.velocity;
transform.LookAt(transform.position + refectionPosition.normalized);
}
public void Destroy()
{
TweenKill();
Destroyed?.Invoke(this);
rigid.velocity = Vector3.zero;
}
public IEnumerator ButtonDestroy()
{
TweenKill();
gameObject.SetActive(false);
yield return new WaitForSeconds(0.5f);
Destroyed?.Invoke(this);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
using System.ComponentModel;
namespace KartExchangeEngine
{
class ContractPrice : Entity
{
[DBIgnoreAutoGenerateParam]
[DBIgnoreReadParam]
public override string FriendlyName
{
get { return "Импорт Smarket контрактные цены"; }
}
public string Articul
{
get;
set;
}
public long idsupplier
{
get;
set;
}
public double price
{
get;
set;
}
public long iddocument
{
get;
set;
}
public DateTime begindate
{
get;
set;
}
public DateTime modificationdate
{
get;
set;
}
}
}
|
using MediaBrowser.Model.Dlna;
using System.Collections.Generic;
namespace MediaBrowser.Model.MediaInfo
{
public class PlaybackInfoRequest
{
public string Id { get; set; }
public string UserId { get; set; }
public long? MaxStreamingBitrate { get; set; }
public long? StartTimeTicks { get; set; }
public int? AudioStreamIndex { get; set; }
public int? SubtitleStreamIndex { get; set; }
public int? MaxAudioChannels { get; set; }
public string MediaSourceId { get; set; }
public string LiveStreamId { get; set; }
public DeviceProfile DeviceProfile { get; set; }
public bool EnableDirectPlay { get; set; }
public bool EnableDirectStream { get; set; }
public bool EnableTranscoding { get; set; }
public bool AllowVideoStreamCopy { get; set; }
public bool AllowAudioStreamCopy { get; set; }
public bool IsPlayback { get; set; }
public bool AutoOpenLiveStream { get; set; }
public MediaProtocol[] DirectPlayProtocols { get; set; }
public PlaybackInfoRequest()
{
EnableDirectPlay = true;
EnableDirectStream = true;
EnableTranscoding = true;
AllowVideoStreamCopy = true;
AllowAudioStreamCopy = true;
IsPlayback = true;
DirectPlayProtocols = new MediaProtocol[] { MediaProtocol.Http };
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace SQLRichControl
{
public static class SQLRichProcess
{
private static WordList ReservedWord = new WordList();
private const string BASE_FONT = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fmodern\fprq1\fcharset0 Courier New;}{\f1\fswiss\fcharset0 Arial;}}";
private const string BASE_COLOR = @"{\colortbl ;\red0\green0\blue255;\red255\green0\blue255;\red128\green128\blue128;\red255\green0\blue0;\red0\green128\blue0;\red128\green0\blue0;}";
private const string BASE = @"\viewkind4\uc1\pard";
private static void FillReserveWordSQL()
{
ReservedWord.Clear();
//String
ReservedWord.Add("'", Word.WordClassType.StringWord);
//DDL Commands
ReservedWord.Add("ALTER", Word.WordClassType.SQLWord);
ReservedWord.Add("APPLICATION", Word.WordClassType.SQLWord);
ReservedWord.Add("ASSEMBLY", Word.WordClassType.SQLWord);
ReservedWord.Add("CALLER", Word.WordClassType.SQLWord);
ReservedWord.Add("CHECK", Word.WordClassType.SQLWord);
ReservedWord.Add("CASCADE", Word.WordClassType.SQLWord);
ReservedWord.Add("CLUSTERED", Word.WordClassType.SQLWord);
ReservedWord.Add("COLUMN", Word.WordClassType.SQLWord);
ReservedWord.Add("CONSTRAINT", Word.WordClassType.SQLWord);
ReservedWord.Add("CONTENT", Word.WordClassType.SQLWord);
ReservedWord.Add("CREATE", Word.WordClassType.SQLWord);
ReservedWord.Add("DISABLE", Word.WordClassType.SQLWord);
ReservedWord.Add("DATABASE", Word.WordClassType.SQLWord);
ReservedWord.Add("DBCC", Word.WordClassType.SQLWord);
ReservedWord.Add("DROP", Word.WordClassType.SQLWord);
ReservedWord.Add("ENABLE", Word.WordClassType.SQLWord);
ReservedWord.Add("EXTERNAL", Word.WordClassType.SQLWord);
ReservedWord.Add("FILE", Word.WordClassType.SQLWord);
ReservedWord.Add("FILEGROUP", Word.WordClassType.SQLWord);
ReservedWord.Add("FILEGROWTH", Word.WordClassType.SQLWord);
ReservedWord.Add("FILENAME", Word.WordClassType.SQLWord);
ReservedWord.Add("FOREIGN", Word.WordClassType.SQLWord);
ReservedWord.Add("FUNCTION", Word.WordClassType.SQLWord);
ReservedWord.Add("GRANT", Word.WordClassType.SQLWord);
ReservedWord.Add("IDENTITY", Word.WordClassType.SQLWord);
ReservedWord.Add("INDEX", Word.WordClassType.SQLWord);
ReservedWord.Add("MOVE", Word.WordClassType.SQLWord);
ReservedWord.Add("NAME", Word.WordClassType.SQLWord);
ReservedWord.Add("NONCLUSTERED", Word.WordClassType.SQLWord);
ReservedWord.Add("NOLOCK", Word.WordClassType.SQLWord);
ReservedWord.Add("OPEN", Word.WordClassType.SQLWord);
ReservedWord.Add("PERMISSION_SET", Word.WordClassType.SQLWord);
ReservedWord.Add("PERSISTED", Word.WordClassType.SQLWord);
ReservedWord.Add("PRIMARY", Word.WordClassType.SQLWord);
ReservedWord.Add("PROCEDURE", Word.WordClassType.SQLWord);
ReservedWord.Add("READONLY", Word.WordClassType.SQLWord);
ReservedWord.Add("REPLICATION", Word.WordClassType.SQLWord);
ReservedWord.Add("RETURNS", Word.WordClassType.SQLWord);
ReservedWord.Add("REVOKE", Word.WordClassType.SQLWord);
ReservedWord.Add("ROLE", Word.WordClassType.SQLWord);
ReservedWord.Add("SAFE", Word.WordClassType.SQLWord);
ReservedWord.Add("SCHEMABINDING", Word.WordClassType.SQLWord);
ReservedWord.Add("SIZE", Word.WordClassType.SQLWord);
ReservedWord.Add("SYNONYM", Word.WordClassType.SQLWord);
ReservedWord.Add("TABLE", Word.WordClassType.SQLWord);
ReservedWord.Add("TABLOCK", Word.WordClassType.SQLWord);
ReservedWord.Add("TEXTIMAGE_ON", Word.WordClassType.SQLWord);
ReservedWord.Add("TYPE", Word.WordClassType.SQLWord);
ReservedWord.Add("TRIGGER", Word.WordClassType.SQLWord);
ReservedWord.Add("TRUNCATE", Word.WordClassType.SQLWord);
ReservedWord.Add("UPDATETEXT", Word.WordClassType.SQLWord);
ReservedWord.Add("VIEW", Word.WordClassType.SQLWord);
ReservedWord.Add("XLOCK", Word.WordClassType.SQLWord);
ReservedWord.Add("DOCUMENT", Word.WordClassType.SQLWord);
ReservedWord.Add("NOCHECK", Word.WordClassType.SQLWord);
ReservedWord.Add("RULE", Word.WordClassType.SQLWord);
//DML Commands
ReservedWord.Add("CURSOR", Word.WordClassType.SQLWord);
ReservedWord.Add("FETCH", Word.WordClassType.SQLWord);
ReservedWord.Add("NEXT", Word.WordClassType.SQLWord);
ReservedWord.Add("CLOSE", Word.WordClassType.SQLWord);
ReservedWord.Add("DEALLOCATE", Word.WordClassType.SQLWord);
ReservedWord.Add("SCROLL", Word.WordClassType.SQLWord);
ReservedWord.Add("DECLARE", Word.WordClassType.SQLWord);
ReservedWord.Add("SELECT", Word.WordClassType.SQLWord);
ReservedWord.Add("UNION", Word.WordClassType.SQLWord);
ReservedWord.Add("FROM", Word.WordClassType.SQLWord);
ReservedWord.Add("JOIN", Word.WordClassType.SQLWord);
ReservedWord.Add("INNER", Word.WordClassType.SQLWord);
ReservedWord.Add("LEFT", Word.WordClassType.SQLWord);
ReservedWord.Add("RIGHT", Word.WordClassType.SQLWord);
ReservedWord.Add("WHERE", Word.WordClassType.SQLWord);
ReservedWord.Add("DISTINCT", Word.WordClassType.SQLWord);
ReservedWord.Add("LIKE", Word.WordClassType.SQLWord);
ReservedWord.Add("HAVING", Word.WordClassType.SQLWord);
ReservedWord.Add("GROUP", Word.WordClassType.SQLWord);
ReservedWord.Add("ORDER", Word.WordClassType.SQLWord);
ReservedWord.Add("INSERT", Word.WordClassType.SQLWord);
ReservedWord.Add("INTO", Word.WordClassType.SQLWord);
ReservedWord.Add("VALUES", Word.WordClassType.SQLWord);
ReservedWord.Add("UPDATE", Word.WordClassType.SQLWord);
ReservedWord.Add("DELETE", Word.WordClassType.SQLWord);
ReservedWord.Add("EXECUTE", Word.WordClassType.SQLWord);
ReservedWord.Add("EXEC", Word.WordClassType.SQLWord);
ReservedWord.Add("COLLECTION", Word.WordClassType.SQLWord);
ReservedWord.Add("MAXRECURSION", Word.WordClassType.SQLWord);
ReservedWord.Add("REVERT", Word.WordClassType.SQLWord);
ReservedWord.Add("AS", Word.WordClassType.SQLWord);
ReservedWord.Add("END", Word.WordClassType.SQLWord);
ReservedWord.Add("SET", Word.WordClassType.SQLWord);
ReservedWord.Add("FOR", Word.WordClassType.SQLWord);
ReservedWord.Add("ON", Word.WordClassType.SQLWord);
ReservedWord.Add("TO", Word.WordClassType.SQLWord);
ReservedWord.Add("TOP", Word.WordClassType.SQLWord);
ReservedWord.Add("ALL", Word.WordClassType.SQLWord);
ReservedWord.Add("KEY", Word.WordClassType.SQLWord);
ReservedWord.Add("OFF", Word.WordClassType.SQLWord);
ReservedWord.Add("BY", Word.WordClassType.SQLWord);
ReservedWord.Add("XML", Word.WordClassType.SQLWord);
ReservedWord.Add("ADD", Word.WordClassType.SQLWord);
ReservedWord.Add("IN", Word.WordClassType.SQLWord);
ReservedWord.Add("IF", Word.WordClassType.SQLWord);
ReservedWord.Add("ASC", Word.WordClassType.SQLWord);
ReservedWord.Add("DESC", Word.WordClassType.SQLWord);
ReservedWord.Add("WHILE", Word.WordClassType.SQLWord);
ReservedWord.Add("BEGIN", Word.WordClassType.SQLWord);
ReservedWord.Add("USE", Word.WordClassType.SQLWord);
ReservedWord.Add("GOTO", Word.WordClassType.SQLWord);
ReservedWord.Add("CASE", Word.WordClassType.SQLWord);
ReservedWord.Add("ELSE", Word.WordClassType.SQLWord);
ReservedWord.Add("WHEN", Word.WordClassType.SQLWord);
ReservedWord.Add("THEN", Word.WordClassType.SQLWord);
ReservedWord.Add("BETWEEN", Word.WordClassType.SQLWord);
ReservedWord.Add("CAST", Word.WordClassType.SQLWord);
ReservedWord.Add("RETURN", Word.WordClassType.SQLWord);
ReservedWord.Add("COMMIT", Word.WordClassType.SQLWord);
ReservedWord.Add("ROLLBACK", Word.WordClassType.SQLWord);
ReservedWord.Add("TRANSACTION", Word.WordClassType.SQLWord);
ReservedWord.Add("PRINT", Word.WordClassType.SQLWord);
ReservedWord.Add("DEFAULT", Word.WordClassType.SQLWord);
ReservedWord.Add("COLLATE", Word.WordClassType.SQLWord);
ReservedWord.Add("TRY", Word.WordClassType.SQLWord);
ReservedWord.Add("CATCH", Word.WordClassType.SQLWord);
ReservedWord.Add("WITH", Word.WordClassType.SQLWord);
ReservedWord.Add("INSTEAD", Word.WordClassType.SQLWord);
ReservedWord.Add("SCHEMA", Word.WordClassType.SQLWord);
ReservedWord.Add("AUTHORIZATION", Word.WordClassType.SQLWord);
ReservedWord.Add("AFTER", Word.WordClassType.SQLWord);
ReservedWord.Add("UNIQUE", Word.WordClassType.SQLWord);
ReservedWord.Add("ROWGUIDCOL", Word.WordClassType.SQLWord);
ReservedWord.Add("REFERENCES", Word.WordClassType.SQLWord);
ReservedWord.Add("RAISERROR", Word.WordClassType.SQLWord);
ReservedWord.Add("OPTION", Word.WordClassType.SQLWord);
ReservedWord.Add("PAD_INDEX", Word.WordClassType.SQLWord);
ReservedWord.Add("STATISTICS_NORECOMPUTE", Word.WordClassType.SQLWord);
ReservedWord.Add("ALLOW_ROW_LOCKS", Word.WordClassType.SQLWord);
ReservedWord.Add("IGNORE_DUP_KEY", Word.WordClassType.SQLWord);
ReservedWord.Add("ALLOW_PAGE_LOCKS", Word.WordClassType.SQLWord);
//SETs
ReservedWord.Add("NOCOUNT", Word.WordClassType.SQLWord);
ReservedWord.Add("XACT_ABORT", Word.WordClassType.SQLWord);
ReservedWord.Add("NUMERIC_ROUNDABORT", Word.WordClassType.SQLWord);
ReservedWord.Add("IDENTITY_INSERT", Word.WordClassType.SQLWord);
ReservedWord.Add("ANSI_PADDING", Word.WordClassType.SQLWord);
ReservedWord.Add("QUOTED_IDENTIFIER", Word.WordClassType.SQLWord);
ReservedWord.Add("ANSI_NULLS", Word.WordClassType.SQLWord);
//Funcions
ReservedWord.Add("ABS", Word.WordClassType.FunctionWord);
ReservedWord.Add("AVG", Word.WordClassType.FunctionWord);
ReservedWord.Add("CHARINDEX", Word.WordClassType.FunctionWord);
ReservedWord.Add("DATALENGTH", Word.WordClassType.FunctionWord);
ReservedWord.Add("DATEADD", Word.WordClassType.FunctionWord);
ReservedWord.Add("DATEPART", Word.WordClassType.FunctionWord);
ReservedWord.Add("GETDATE", Word.WordClassType.FunctionWord);
ReservedWord.Add("GETUTCDATE", Word.WordClassType.FunctionWord);
ReservedWord.Add("REVERSE", Word.WordClassType.FunctionWord);
ReservedWord.Add("PATINDEX", Word.WordClassType.FunctionWord);
ReservedWord.Add("LTRIM", Word.WordClassType.FunctionWord);
ReservedWord.Add("RTRIM", Word.WordClassType.FunctionWord);
ReservedWord.Add("UPPER", Word.WordClassType.FunctionWord);
ReservedWord.Add("LOWER", Word.WordClassType.FunctionWord);
ReservedWord.Add("ISNULL", Word.WordClassType.FunctionWord);
ReservedWord.Add("SPACE", Word.WordClassType.FunctionWord);
ReservedWord.Add("CONVERT", Word.WordClassType.FunctionWord);
ReservedWord.Add("SUM", Word.WordClassType.FunctionWord);
ReservedWord.Add("MIN", Word.WordClassType.FunctionWord);
ReservedWord.Add("MAX", Word.WordClassType.FunctionWord);
ReservedWord.Add("RANK", Word.WordClassType.FunctionWord);
ReservedWord.Add("COUNT", Word.WordClassType.FunctionWord);
ReservedWord.Add("COUNT_BIG", Word.WordClassType.FunctionWord);
ReservedWord.Add("OBJECT_NAME", Word.WordClassType.FunctionWord);
ReservedWord.Add("OBJECT_ID", Word.WordClassType.FunctionWord);
ReservedWord.Add("ROUND", Word.WordClassType.FunctionWord);
ReservedWord.Add("NEWID", Word.WordClassType.FunctionWord);
ReservedWord.Add("NEWSEQUENTIALID", Word.WordClassType.FunctionWord);
ReservedWord.Add("IS_MEMBER", Word.WordClassType.FunctionWord);
ReservedWord.Add("@@TRANCOUNT", Word.WordClassType.FunctionWord);
ReservedWord.Add("@@IDENTITY", Word.WordClassType.FunctionWord);
ReservedWord.Add("@@FETCH_STATUS", Word.WordClassType.FunctionWord);
ReservedWord.Add("@@ERROR", Word.WordClassType.FunctionWord);
//Operators
ReservedWord.Add("IS", Word.WordClassType.OperatorWord);
ReservedWord.Add("NOT", Word.WordClassType.OperatorWord);
ReservedWord.Add("AND", Word.WordClassType.OperatorWord);
ReservedWord.Add("OR", Word.WordClassType.OperatorWord);
ReservedWord.Add("NULL", Word.WordClassType.OperatorWord);
ReservedWord.Add("EXISTS", Word.WordClassType.OperatorWord);
ReservedWord.Add("OUTER", Word.WordClassType.OperatorWord);
//SysTables
ReservedWord.Add("SYSOBJECTS", Word.WordClassType.SysTablesWord);
ReservedWord.Add("SYSCOLUMNS", Word.WordClassType.SysTablesWord);
ReservedWord.Add("SYSCOMMENTS", Word.WordClassType.SysTablesWord);
ReservedWord.Add("SYSPROCESSES", Word.WordClassType.SysTablesWord);
ReservedWord.Add("SYSCONSTRAINTS", Word.WordClassType.SysTablesWord);
ReservedWord.Add("SYSINDEXES", Word.WordClassType.SysTablesWord);
ReservedWord.Add("SYSUSERS", Word.WordClassType.SysTablesWord);
ReservedWord.Add("SYSKEYS", Word.WordClassType.SysTablesWord);
ReservedWord.Add("SYSTYPES", Word.WordClassType.SysTablesWord);
ReservedWord.Add("SYSDEPENDS", Word.WordClassType.SysTablesWord);
//SysProce
ReservedWord.Add("SP_RENAME", Word.WordClassType.SysProcWord);
ReservedWord.Add("SP_BINDRULE", Word.WordClassType.SysProcWord);
ReservedWord.Add("SP_UNBINDRULE ", Word.WordClassType.SysProcWord);
ReservedWord.Add("SP_BINDEFAULT", Word.WordClassType.SysProcWord);
ReservedWord.Add("SP_UNBINDEFAULT", Word.WordClassType.SysProcWord);
ReservedWord.Add("SP_TABLEOPTION", Word.WordClassType.SysProcWord);
ReservedWord.Add("SP_DELETE_JOB", Word.WordClassType.SysProcWord);
ReservedWord.Sort();
}
public static void FillWords(SQLTextControl.SQLType type)
{
if (type == SQLTextControl.SQLType.SQLServer) FillReserveWordSQL();
}
private static string GetRTFColor(Word word)
{
if (word.Type == Word.WordClassType.SQLWord) return @"\cf1\fs20";
if (word.Type == Word.WordClassType.FunctionWord) return @"\cf2\fs20";
if (word.Type == Word.WordClassType.OperatorWord) return @"\cf3\fs20";
if (word.Type == Word.WordClassType.StringWord) return @"\cf4\fs20";
if (word.Type == Word.WordClassType.SysTablesWord) return @"\cf5\fs20";
if (word.Type == Word.WordClassType.SysProcWord) return @"\cf6\fs20";
return @"\cf1\fs20";
}
private static string Format(string RTF)
{
RTF = BASE_FONT + BASE_COLOR + @"\cf0\fs20 " + RTF +"}";
RTF = RTF.Replace("\r\n", @"\par ");
//RTF = RTF.Replace("\t", @"\tab ");
return RTF;
}
public static string GetTextRTF(string text)
{
Regex regex = new Regex(@"\s|\n|\r|\(|\,|\)|\*");
string rtfColor;
StringBuilder acum = new StringBuilder();
int iacum = 0;
string lastChar = "";
string line = "";
bool openString = false;
bool startWithComillas = false;
string[] values = regex.Split(text);
int count = values.Length;
for (int index = 0; index < count; index++)
{
string value = values[index];
line = "";
if (!String.IsNullOrEmpty(value))
{
string[] comillas = value.Split('\'');
startWithComillas = comillas[0].Equals("");
for (int i=0;i<comillas.Length; i++)
{
if ((((i%2==0) && startWithComillas) || ((i%2==1) && !startWithComillas)) || (comillas[i].Equals("")))
{
openString = !openString;
if (openString)
line += @"\cf4\fs20 '" + comillas[i];
else
line += @"'\cf0\fs20 " + comillas[i];
}
else
{
Word word = ReservedWord[comillas[i].ToUpper()];
if ((word != null) && (!openString))
{
rtfColor = GetRTFColor(word);
line += rtfColor + comillas[i] + @"\cf0 ";
}
else
line += comillas[i];
}
}
}
else
line = value;
iacum += value.Length + 1;
if (iacum < text.Length)
lastChar = text.Substring(iacum-1, 1);
else
lastChar = "";
acum.Append(line + lastChar);
}
return Format(acum.ToString());
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace ConfluenceEditor
{
class XmlHtmlFullIndentWriter : XmlTextWriter
{
private int _indentLevel;
private int _actIndent;
private int _state = 2;
private int _hrefLevel;
public XmlHtmlFullIndentWriter(TextWriter writer)
: base(writer)
{
_initHash();
_stack = new Stack();
}
public XmlHtmlFullIndentWriter(Stream stream, Encoding encoding)
: base(stream, encoding)
{
_initHash();
_stack = new Stack();
}
private static Hashtable _fullEndElement;
private bool _writeXmlHeader;
private Stack _stack;
private bool _forceFormat;
private bool _forceHandleAmp;
private bool _inAttribWrite;
private XmlWriterSettings _settings = new XmlWriterSettings();
public override XmlWriterSettings Settings
{
get
{
return _settings;
}
}
private static void _initHash()
{
if (_fullEndElement == null)
{
_fullEndElement = new Hashtable();
_fullEndElement["table"] = "";
_fullEndElement["td"] = "";
_fullEndElement["tr"] = "";
_fullEndElement["form"] = "";
_fullEndElement["html"] = "";
_fullEndElement["body"] = "";
_fullEndElement["head"] = "";
}
}
// ================================================================
// We don't want CDATA header in html output, just write raw data
// ================================================================
public override void WriteCData(string cdata)
{
this.WriteRaw(cdata);
}
// ================================================================
// We don't want the xml header, ignore it
// ================================================================
public bool WriteXmlHeader
{
get
{
return _writeXmlHeader;
}
set
{
_writeXmlHeader = value;
}
}
public override System.Threading.Tasks.Task WriteStartDocumentAsync()
{
return base.WriteStartDocumentAsync();
}
public override System.Threading.Tasks.Task WriteStartDocumentAsync(bool standalone)
{
return base.WriteStartDocumentAsync(standalone);
}
public override void WriteStartDocument()
{
if (_writeXmlHeader)
base.WriteStartDocument();
}
public override void WriteStartDocument(bool standalone)
{
if (_writeXmlHeader)
base.WriteStartDocument(standalone);
}
// ===============================================================================
// Override to dected improper close element
// ===============================================================================
public static bool NeedFullEnd(string localName)
{
return _fullEndElement[localName] != null;
}
public string PeekElementName()
{
return (string)_stack.Peek();
}
public bool ForceFormat
{
get
{
return _forceFormat;
}
set
{
_forceFormat = value;
}
}
public bool ForceHandleAmp
{
get
{
return _forceHandleAmp;
}
set
{
_forceHandleAmp = value;
}
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
_inAttribWrite = true;
base.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteEndAttribute()
{
base.WriteEndAttribute();
_inAttribWrite = false;
}
public override void WriteString(string text)
{
if (_inAttribWrite)
{
if (text.IndexOf("&") >= 0)
base.WriteRaw(text);
else
base.WriteString(text);
}
else
{
if (text.IndexOf("&") >= 0 && _forceHandleAmp)
base.WriteRaw(text);
else
base.WriteString(text);
//base.WriteString(text);
}
}
// ===============================================================================
// Override to force full indentation on output xml : useful for debug purpose
// ===============================================================================
// ================================================================
// We don't want the xml header, ignore it
// ================================================================
public override void WriteStartElement(string prefix, string localName, string ns)
{
if (Formatting == Formatting.Indented || ForceFormat)
{
if (_state == 0 && _hrefLevel == 0) base.WriteRaw("\n");
if (localName.Equals("a"))
{
_hrefLevel++;
}
if (_actIndent < _indentLevel && _indentLevel > 0)
{
_doIndent(_indentLevel - _actIndent);
}
_actIndent = 0;
_state = 0;
_indentLevel++;
}
base.WriteStartElement(prefix, localName, ns);
_stack.Push(localName);
}
public override void WriteEndElement()
{
string localName = PeekElementName();
if (NeedFullEnd(localName))
{
WriteFullEndElement();
return;
}
else
{
base.WriteEndElement();
_stack.Pop();
if (Formatting == Formatting.Indented || ForceFormat)
{
_indentLevel--;
if (localName.Equals("a")) _hrefLevel--;
if (_hrefLevel == 0)
{
base.WriteRaw("\n");
_doIndent(_indentLevel - 1);
}
_state = 1;
_actIndent = _indentLevel - 1;
}
}
}
public override void WriteFullEndElement()
{
string localName = PeekElementName();
base.WriteFullEndElement();
_stack.Pop();
if (Formatting == Formatting.Indented || ForceFormat)
{
_indentLevel--;
if (localName.Equals("a")) _hrefLevel--;
if (_hrefLevel == 0)
{
base.WriteRaw("\n");
_doIndent(_indentLevel - 1);
}
_state = 1;
_actIndent = _indentLevel - 1;
}
}
private void _doIndent(int indentLevel)
{
for (int i = 0; i < indentLevel * Indentation; i++)
{
base.WriteRaw("" + IndentChar);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartLib;
namespace KartSystem
{
public interface IZReportRecordsView:IAxiTradeView
{
List<ZReportRecord> Records { get; set; }
}
}
|
using System.Collections.Generic;
using Proxynet.Models;
using UsersLib.Entity;
namespace Proxynet.Service.Converters
{
public class GroupDtoConverter : IGroupDtoConverter
{
public GroupDto Convert( Group userGroup )
{
return new GroupDto
{
Id = userGroup.Id,
Name = userGroup.Name
};
}
public List<GroupDto> Convert( List<Group> groups )
{
return groups.ConvertAll( Convert );
}
public Group Convert( GroupDto userGroup )
{
return new Group
{
Id = userGroup.Id,
Name = userGroup.Name
};
}
public List<Group> Convert( List<GroupDto> userGroup )
{
return userGroup.ConvertAll( Convert );
}
}
} |
using Microsoft.EntityFrameworkCore;
using HomeBuh.Models;
namespace HomeBuh.Data
{
public class BuhContext: DbContext
{
public BuhContext(DbContextOptions<BuhContext> options) : base(options)
{
}
public DbSet<Entry> Entries { get; set; }
public DbSet<BuhAccount> BuhAccounts { get; set; }
public DbSet<Setting> Settings { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Entry>()
.Property(b => b.DateLastUpdate)
.HasDefaultValueSql("getutcdate()");
}
}
}
|
using MailSender.ViewModel;
using PasswordDll;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace MailSender
{
public class EmailSendServiceClass
{
private readonly string _login;
private readonly string _pass;
private CancellationTokenSource _tokenSource = new CancellationTokenSource();
public EmailSendServiceClass(string login, string pass)
{
_login = login;
_pass = pass;
}
public void SendEmail(string mailto)
{
try
{
using (var message = new MailMessage(_login, mailto, EmailSenderConfig.title, EmailSenderConfig.message))
using (var client = new SmtpClient(EmailSenderConfig.smtpServer, EmailSenderConfig.smtpPort) { EnableSsl = true, Credentials = new NetworkCredential(_login, Encrypter.Deencrypt(_pass)) })
{
client.Send(message);
}
}
catch (Exception e)
{
//var messView = new WindowMessage();
//var mess = new WindowMessageViewModel("Ошибка отправки сообщения", e.Message);
//mess.ReqestClose += messView.Close;
//messView.DataContext = mess;
//messView.ShowDialog();
}
}
private async Task SendEmailAsync(string mailto)
{
try
{
using (var message = new MailMessage(_login, mailto, EmailSenderConfig.title, EmailSenderConfig.message))
using (var client = new SmtpClient(EmailSenderConfig.smtpServer, EmailSenderConfig.smtpPort) { EnableSsl = true, Credentials = new NetworkCredential(_login, Encrypter.Deencrypt(_pass)) })
{
await client.SendMailAsync(message).ConfigureAwait(false);
}
}
catch (Exception e)
{
//var messView = new WindowMessage();
//var mess = new WindowMessageViewModel("Ошибка отправки сообщения", e.Message);
//mess.ReqestClose += messView.Close;
//messView.DataContext = mess;
//messView.ShowDialog();
}
}
public void SendEmails(IEnumerable<Emails> mailsto, IProgress<double> progress)
{
int i = 0;
if(_tokenSource.IsCancellationRequested)
{ _tokenSource = new CancellationTokenSource(); }
mailsto.AsParallel()
.WithCancellation(_tokenSource.Token)
.WithDegreeOfParallelism(Environment.ProcessorCount)
.ForAll(async mailto =>
{
await SendEmailAsync(mailto.Value);
if(_tokenSource.IsCancellationRequested)
{
progress?.Report(0d);
MessageBox.Show("Отправка отменена");
return;
}
i++;
progress?.Report((i*100) / mailsto.Count());
});
//progress?.Report(100d);
}
public async Task SendEmailsAsync(IEnumerable<Emails> mailsto, IProgress<double> progress)
{
int i = 0;
foreach (var mailto in mailsto)
{
if (!_tokenSource.IsCancellationRequested)
{
await SendEmailAsync(mailto.Value).ConfigureAwait(false);
i++;
progress?.Report((i * 100) / mailsto.Count());
}
else
{
progress?.Report(0d);
MessageBox.Show("Отправка отменена");
return;
}
}
}
public void Cancel()
{
_tokenSource.Cancel();
}
}
}
|
#if DEBUG
using Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.ServiceModel;
namespace Contracts.Report
{
[ServiceContract(SessionMode = SessionMode.Allowed, Namespace = "http://www.noof.com/", Name = "Report")]
public interface IReportService
{
[OperationContract]
bool AssetsFitCriteria(string pct, DateTime scheduleDate);
[OperationContract]
void CreateReportMethods(string connectionString, string userName, string department);
[OperationContract]
List<Tuple<int, string, string>> GetActors();
[OperationContract]
List<string> GetChannels(bool excludeXCubed);
[OperationContract]
Movie GetMovie(int id);
[OperationContract]
List<string> GetPCTs();
[OperationContract]
DataTable GetReportUsage();
[OperationContract]
void TrackReport(string reportName, string userName);
}
}
#endif |
/*
* CREATED BY HM
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BangazonWorkforceSapphireElephants.Models.ViewModels
{
public class ComputerDeleteViewModel
{
public int Id { get; set; }
public DateTime PurchaseDate { get; set; }
public string Make { get; set; }
public string Manufacturer { get; set; }
public bool DisplayDelete { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.ComponentModel;
using System.IO.Ports;
using System.Xml;
using System.Runtime.InteropServices;
using BootLoader.Device;
using BootLoader.Protocol.Implemantations;
namespace BootLoader
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
[GuidAttribute("E868067A-33DC-4563-AC27-566839970EF8")]
public class SerialPortSetting
{
public int Baudrate { get; set; }
public string PortName { get; set; }
}
public partial class MainWindow
{
private bool _isCryptingEnabled = true;
private string _hexFilename = "";
private string _serialPort = "";
private readonly BackgroundWorker _bgWorker = new BackgroundWorker();
readonly string _settingFile;
private static string[] FixComPortsNames(ICollection<string> comportStrings)
{
var ret = new string[comportStrings.Count];
var index = 0;
foreach (var comportString in comportStrings)
{
var regex = new Regex("\\b(\\w+\\d+)");
var match = regex.Match(comportString);
if (match.Success)
{
ret[index] = match.Groups[1].ToString();
}
else
{
ret[index] = comportString;
}
++index;
}
return ret;
}
protected override void OnClosing(CancelEventArgs e)
{
UpdateSettings();
base.OnClosing(e);
}
private void UpdateIsCryptingEnabledButtonText()
{
var text = _isCryptingEnabled ? "Включено" : "Отключено";
IsCryptEnabledButton.Content = text;
}
public MainWindow()
{
var array = new List<byte> { 12, 12, 43, 54, 34, 23, 23, 33 };
var crc = Chksm(array.ToArray());
array.Add((byte)(crc >> 8));
array.Add((byte)crc);
Debug.WriteLine(String.Format("crc: {0}, {1:x2}", _CRC(array.ToArray()), crc));
InitializeComponent();
_bgWorker.WorkerReportsProgress = true;
_bgWorker.WorkerSupportsCancellation = true;
var ports = SerialPort.GetPortNames();
ports = FixComPortsNames(ports);
int[] baudRate = { 4800, 9600, 19200, 38400, 57600, 115200, 230400 };
ComboBoxForSerialPortBaudrate.ItemsSource = baudRate;
ComboBoxForSerialPortBaudrate.SelectedItem = baudRate[0];
_bgWorker.DoWork += bgWorker_DoWork;
_bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted;
_bgWorker.ProgressChanged += bgWorker_ProgressChanged;
ComboboxForPortsNames.ItemsSource = ports;
if (ports.Length > 0)
{
ComboboxForPortsNames.SelectedItem = ports[0];
_serialPort = ports[0];
}
_settingFile = AppDomain.CurrentDomain.BaseDirectory;
if (_settingFile.Length > 0)
if (_settingFile.Substring(_settingFile.Length - 1, 1) != "\\")
_settingFile += "\\";
_settingFile += "settings.xml";
ProgressBar.Text = "Выберите файл";
var settingFileIsPresents = true;
try
{
var xd = new XmlDocument();
xd.Load(_settingFile);
var currentDeviceCode = "";
if (xd.DocumentElement != null)
foreach (XmlNode node in xd.DocumentElement.ChildNodes)
{
if (node.Name == "FileName")
_hexFilename = node.InnerText;
if (node.Name == "SerialPort")
{
var serialPortName = node.InnerText;
_serialPort = serialPortName;
}
if (node.Name == "CryptIsEnabled")
_isCryptingEnabled = node.InnerText == "true";
if (node.Name == "BaudRate")
{
ComboBoxForSerialPortBaudrate.SelectedItem = Convert.ToInt32(node.InnerText);
}
if (node.Name == "CurrentDeviceCode")
currentDeviceCode = node.InnerText;
if (node.Name == "ListOfDeveiceCodes")
{
var xmlNodeList = node.ChildNodes;
foreach (XmlNode xmlNode in xmlNodeList)
{
if (xmlNode.Name == "DeviceCode")
{
ComboBoxForDeviceCode.Items.Add(xmlNode.InnerText);
}
}
}
}
if (ComboBoxForDeviceCode.Items.Contains(currentDeviceCode))
{
ComboBoxForDeviceCode.SelectedItem = currentDeviceCode;
}
else
{
ComboBoxForDeviceCode.Text = currentDeviceCode;
}
UpdateIsCryptingEnabledButtonText();
ButtonStartFlashing.IsEnabled = true;
ComboboxForPortsNames.Text = _serialPort;
}
catch (Exception)
{
settingFileIsPresents = false;
}
LabelForFileName.Text = _hexFilename;
if (!settingFileIsPresents)
{
UpdateSettings();
}
}
// проверка крк пакета возращает 1 если верно
static byte _CRC(IList<byte> array)
{
UInt64 sum = 0;
byte i = 0;
while (i < array.Count)
sum += ((UInt64)array[i++] << 8) + array[i++];
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
return sum == 0xffff ? (byte)1 : (byte)0;
}
static UInt16 Chksm(byte[] array)
{
UInt64 sum = 0;
var i = 0;
while (i < array.Length)
{
sum += ((UInt64)array[i++] << 8) + array[i++];
}
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
var answer = (UInt16)~sum;
return answer;
}
void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ProgressBar.Value = e.ProgressPercentage;
}
void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
ProgressBar.Text = "Операция отменена";
}
else if (e.Error != null)
{
ProgressBar.Text = String.Format("Ошибка: {0}", e.Error.Message);
}
else
{
// TODO: restore
ProgressBar.Text = e.Result.ToString();
}
ButtonSelectFile.IsEnabled = true;
ButtonStartFlashing.IsEnabled = true;
ComboboxForPortsNames.IsEnabled = true;
ButtonSelectAndFlashing.IsEnabled = true;
}
private bool _inProcess;
private string _resultString;
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
SetMaxValueForProgressBar(1000);
SetValueForProgressBar(0);
Debug.WriteLine(String.Format("background: {0}", Thread.CurrentThread.ManagedThreadId));
if (worker == null)
return;
var portSetting = e.Argument as SerialPortSetting;
if (portSetting == null)
return;
SetTextForProgressBar("Открываем порт " + portSetting.PortName);
var device = new TimerDeviceImpl(new SerialProtocol(portSetting.PortName, portSetting.Baudrate));
device.ProcessHandler += device_ProcessHandler;
device.ErrorHandler += device_ErrorHandler;
device.FinishedHandler += device_FinishedHandler;
device.PacketHandler += device_PacketHandler;
try {
using (var stream = new FileStream(_hexFilename, FileMode.Open)) {
if (!device.StartFlashing(stream)) {
e.Result = "Ошибка открытия последовательного порта";
return;
}
SetTextForProgressBar("Ожидаем ответа от таймера");
_inProcess = true;
_resultString = "";
while (_inProcess) {
Thread.Sleep(20);
}
}
} catch (Exception) {
e.Result = "Не получилось открыть файл";
}
e.Result = _resultString;
}
private long _packetLength;
void device_PacketHandler(object sended, long packetCount, long packetLenght) {
SetMaxValueForProgressBar((int) packetCount - 1);
_packetLength = packetLenght;
}
void device_FinishedHandler(object sender) {
_resultString = "Устройство прошито";
_inProcess = false;
}
void device_ErrorHandler(object sender, string description) {
_resultString = "Ошибка прошивки";
_inProcess = false;
}
void device_ProcessHandler(object sender, int position)
{
SetValueForProgressBar(position);
if (position > 1) SetTextForProgressBar(String.Format("Прошито {0} байт", position * (_packetLength - 2)));
}
private void UpdateSettings()
{
AddCurrentDeviceCodeToComboboxList();
LabelForFileName.Text = _hexFilename;
try
{
var settings = new XmlWriterSettings
{
// включаем отступ для элементов XML документа
// (позволяет наглядно изобразить иерархию XML документа)
Indent = true,
IndentChars = " ",
// задаем переход на новую строку
NewLineChars = "\n",
// Нужно ли опустить строку декларации формата XML документа
// речь идет о строке вида "<?xml version="1.0" encoding="utf-8"?>"
OmitXmlDeclaration = false
};
using (var xw = XmlWriter.Create(_settingFile, settings))
{
xw.WriteStartElement("Flasher");
xw.WriteElementString("FileName", _hexFilename);
xw.WriteElementString("SerialPort", ComboboxForPortsNames.Text);
xw.WriteElementString("CryptIsEnabled", _isCryptingEnabled ? "true" : "false");
xw.WriteElementString("BaudRate", ComboBoxForSerialPortBaudrate.Text);
var itemCollection = ComboBoxForDeviceCode.Items;
if (!itemCollection.IsEmpty)
{
xw.WriteStartElement("ListOfDeveiceCodes");
foreach (var item in itemCollection)
{
xw.WriteElementString("DeviceCode", item.ToString());
}
xw.WriteEndElement();
xw.WriteElementString("CurrentDeviceCode", ComboBoxForDeviceCode.Text);
}
xw.WriteEndElement();
xw.Flush();
xw.Close();
}
}
catch (Exception)
{
ProgressBar.Text = "Ошибка при обновлени настроек";
}
}
private void SetMaxValueForProgressBar(int value)
{
ProgressBar.Dispatcher.BeginInvoke(new Action<int>(x => { ProgressBar.Maximum = x; }), value);
}
private void SetValueForProgressBar(int value)
{
ProgressBar.Dispatcher.BeginInvoke(new Action<int>(x => { ProgressBar.Value = x; }), value);
}
private void SetTextForProgressBar(string text)
{
ProgressBar.Dispatcher.BeginInvoke(new Action<string>(x => { ProgressBar.Text = x; }), text);
}
protected static ushort GetChecksum(byte[] bytes, int startAddress = 0)
{
ulong sum = 0;
// Sum all the words together, adding the final byte if size is odd
var i = startAddress;
for (; i < bytes.Length - 1; i += 2)
{
sum += BitConverter.ToUInt16(bytes, i);
}
if (i != bytes.Length)
sum += bytes[i];
// Do a little shuffling
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
return (ushort)(~sum);
}
delegate void ChangeProgressBarValue(int value);
public void ChangeProgerssBarValue(int value)
{
if (ProgressBar.Dispatcher.CheckAccess())
ProgressBar.Value = value;
else
{
ProgressBar.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new ChangeProgressBarValue(ChangeProgerssBarValue),
value);
}
}
private void comboboxForPortsNames_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
_serialPort = ComboboxForPortsNames.Text;
UpdateSettings();
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
public static Point GetMousePosition()
{
var w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
private void ButtonCloseWindow_Click(object sender, RoutedEventArgs e)
{
Close();
}
private bool _mouseIsCaptured;
private Point _lastMousePos;
private void Window_MouseMove_1(object sender, MouseEventArgs e)
{
if (_mouseIsCaptured)
{
var curMousePos = GetMousePosition();
var deltax = _lastMousePos.X - curMousePos.X;
var deltay = _lastMousePos.Y - curMousePos.Y;
_lastMousePos.X = curMousePos.X;
_lastMousePos.Y = curMousePos.Y;
Top -= deltay;
Left -= deltax;
}
}
private void TextBlock_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
{
//this.DragMove();
var el = sender as UIElement;
if (el == null)
return;
if (e.LeftButton == MouseButtonState.Pressed)
_mouseIsCaptured = el.CaptureMouse();
_lastMousePos = GetMousePosition();
}
private void TextBlock_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Released)
{
_mouseIsCaptured = false;
var el = sender as UIElement;
if (el == null)
return;
el.ReleaseMouseCapture();
}
}
private void ButtonStartFlashing_Click(object sender, RoutedEventArgs e)
{
if (!ButtonStartFlashing.IsEnabled)
{
ButtonStartFlashing.IsEnabled = true;
return;
}
ButtonSelectFile.IsEnabled = false;
ButtonStartFlashing.IsEnabled = false;
ComboboxForPortsNames.IsEnabled = false;
ButtonSelectAndFlashing.IsEnabled = false;
ProgressBar.Text = "Идет прошивка, подождите...";
_bgWorker.RunWorkerAsync(new SerialPortSetting {Baudrate = Convert.ToInt32(ComboBoxForSerialPortBaudrate.SelectedItem.ToString()), PortName = ComboboxForPortsNames.Text});
}
private void ButtonSelectFile_Click(object sender, RoutedEventArgs e)
{
var dlg = new Microsoft.Win32.OpenFileDialog {DefaultExt = ".tmr", Filter = "Файлы прошивки (*.tmr)|*.tmr"};
var result = dlg.ShowDialog();
if (result != true) return;
_hexFilename = dlg.FileName;
var x = new TimerDeviceImpl(new SerialProtocol("2323", 32));
try {
using (var s = new FileStream(_hexFilename, FileMode.Open)) {
var b = x.GetBaudrateFromStream(s);
if (b < 0) ProgressBar.Text = "Херню вы какую то выбрали, батенька";
ComboBoxForSerialPortBaudrate.SelectedItem = b;
}
} finally {
UpdateSettings();
}
}
private void ButtonSelectAndFlashing_Click(object sender, RoutedEventArgs e)
{
ButtonSelectFile_Click(this, new RoutedEventArgs());
if (ButtonStartFlashing.IsEnabled)
ButtonStartFlashing_Click(this, new RoutedEventArgs());
else
ProgressBar.Text = "Херню вы какую то выбрали, батенька";
}
private void Button_Click(object sender, RoutedEventArgs e)
{
_isCryptingEnabled ^= true;
UpdateIsCryptingEnabledButtonText();
}
private void ComboBoxForDeviceCode_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
AddCurrentDeviceCodeToComboboxList();
}
}
private void AddCurrentDeviceCodeToComboboxList()
{
ItemCollection itemCollection = ComboBoxForDeviceCode.Items;
string addedItem = ComboBoxForDeviceCode.Text;
addedItem = addedItem.Trim(' ');
if (addedItem.Length > 0)
{
if (!itemCollection.Contains(addedItem))
{
itemCollection.Add(ComboBoxForDeviceCode.Text);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Bucket_Opdracht_Version2.ModelStructures
{
public abstract class FillingUnitsAbstractStructure
{
#region
[Key]
public abstract string id { get; set; }
public abstract int MaxCapacity {get;set;}
public abstract int CurrentContentValue { get; set; }
#endregion
#region
public FillingUnitsAbstractStructure()
{
id = Guid.NewGuid().ToString();
}
#endregion
}
}
|
using PhobiaX.Assets;
using PhobiaX.Game.GameObjects;
using PhobiaX.Game.UserInterface;
using PhobiaX.SDL2;
using PhobiaX.SDL2.Options;
using System;
using System.Collections.Generic;
using System.Text;
namespace PhobiaX.Game.UserInteface
{
public class UserIntefaceFactory
{
private readonly GameObjectFactory gameObjectFactory;
private readonly WindowOptions windowOptions;
public UserIntefaceFactory(GameObjectFactory gameObjectFactory, WindowOptions windowOptions)
{
this.gameObjectFactory = gameObjectFactory ?? throw new ArgumentNullException(nameof(gameObjectFactory));
this.windowOptions = windowOptions ?? throw new ArgumentNullException(nameof(windowOptions));
}
public ScoreUI CreateScoreUI(int initialScore, int initialLife)
{
var maxWidth = windowOptions.Width / 22;
var energyBarX = windowOptions.Width - 5 - windowOptions.Width / 6;
gameObjectFactory.CreateMap();
gameObjectFactory.CreateScoreBar(-2, -8);
gameObjectFactory.CreateLifeBar(energyBarX, -8);
var scorePlayer1 = gameObjectFactory.CreateLabel(windowOptions.Width / 6 - 55, 18, maxWidth);
var scorePlayer2 = gameObjectFactory.CreateLabel(windowOptions.Width / 6 - 55, 38, maxWidth);
var energyPlayer1 = gameObjectFactory.CreateLabel(energyBarX, 20, maxWidth + 15);
var energyPlayer2 = gameObjectFactory.CreateLabel(energyBarX, 40, maxWidth + 15);
var scoreUI = new ScoreUI(new List<TextGameObject> { scorePlayer1, scorePlayer2 }, new List<TextGameObject> { energyPlayer1, energyPlayer2 });
scoreUI.SetPlayerLife(0, initialLife);
scoreUI.SetPlayerScore(0, initialScore);
scoreUI.SetPlayerLife(1, initialLife);
scoreUI.SetPlayerScore(1, initialScore);
return scoreUI;
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using ServiceQuotes.Api.Helpers;
using ServiceQuotes.Application.DTOs.Quote;
using ServiceQuotes.Application.Filters;
using ServiceQuotes.Application.Interfaces;
using ServiceQuotes.Domain.Entities.Enums;
using ServiceQuotes.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ServiceQuotes.Api.Controllers
{
public class QuotesController : BaseController<QuotesController>
{
private readonly IQuoteService _quoteService;
private readonly ICustomerRepository _customerRepository;
public QuotesController(IQuoteService quoteService, ICustomerRepository customerRepository)
{
_quoteService = quoteService;
_customerRepository = customerRepository;
}
[Authorize(Role.Manager, Role.Customer)]
[HttpGet]
public async Task<ActionResult<List<GetQuoteResponse>>> GetQuotes([FromQuery] GetQuotesFilter filter)
{
if (Account.Role == Role.Customer)
{
var customer = await _customerRepository.GetByAccountId(Account.Id);
filter.CustomerId = customer.Id;
}
return Ok(await _quoteService.GetAllQuotes(filter));
}
[Authorize(Role.Manager, Role.Customer)]
[HttpGet("unpaid")]
public async Task<ActionResult<List<GetQuoteResponse>>> GetTopUnpaidQuotes([FromQuery] GetQuotesFilter filter)
{
if (Account.Role == Role.Customer)
{
var customer = await _customerRepository.GetByAccountId(Account.Id);
filter.CustomerId = customer.Id;
}
return Ok(await _quoteService.GetTopUnpaidQuotes(filter));
}
[Authorize(Role.Manager, Role.Customer)]
[HttpGet("{id:guid}")]
[ProducesResponseType(401)]
[ProducesResponseType(404)]
[ProducesResponseType(typeof(GetQuoteWithServiceDetailsResponse), 200)]
public async Task<ActionResult<GetQuoteWithServiceDetailsResponse>> GetQuoteById(Guid id)
{
var quote = await _quoteService.GetQuoteById(id);
if (quote is null) return NotFound();
// customer can get only his own quotes
if (Account.Role == Role.Customer)
{
if (quote.ServiceRequest.Customer.AccountId != Account.Id)
return Unauthorized(new { message = "Unauthorized" });
}
return Ok(quote);
}
[Authorize(Role.Manager)]
[HttpPut("{id:guid}/status")]
[ProducesResponseType(401)]
[ProducesResponseType(404)]
[ProducesResponseType(204)]
public async Task<ActionResult<GetQuoteResponse>> UpdateQuoteStatus(Guid id, [FromBody] UpdateQuoteStatusRequest dto)
{
var quote = await _quoteService.GetQuoteById(id);
if (quote is null) return NotFound();
await _quoteService.UpdateQuoteStatus(id, dto.Status);
return NoContent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
namespace DFC.ServiceTaxonomy.ContentApproval.Extensions
{
public static class EnumExtensions
{
public static Dictionary<string, string> GetEnumNameAndDisplayNameDictionary(Type enumType)
{
if (!enumType.IsEnum)
{
throw new ArgumentException($"{enumType.Name} is not an enum.");
}
FieldInfo[] enumFields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
return enumFields.ToDictionary(k => k.Name, v => v.GetCustomAttribute<DisplayAttribute>()?.Name ?? v.Name);
}
public static string GetDisplayName(this Enum enumValue)
{
MemberInfo? enumValueMemberInfo = enumValue.GetType().GetMember(enumValue.ToString()).First();
return enumValueMemberInfo.GetCustomAttribute<DisplayAttribute>()?.GetName() ?? enumValueMemberInfo.Name;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using AKCore.DataModel;
namespace AKCore.Models
{
public class AdminEventModel
{
public IEnumerable<EventViewModel> Events { get; set; }
public int Id { get; set; }
public bool Secret { get; set; }
[Display(Name = "Namn")]
public string Name { get; set; }
[Display(Name = "Plats")]
public string Place { get; set; }
[Display(Name = "Typ")]
public string Type { get; set; }
[Display(Name = "Fika")]
public string Fika { get; set; }
[Display(Name = "Beskrivning")]
public string Description { get; set; }
[Display(Name = "Intern beskrivning")]
public string InternalDescription { get; set; }
[Display(Name = "Dag")]
public DateTime Day { get; set; }
[Display(Name = "Vid hålan")]
public TimeSpan Halan { get; set; }
[Display(Name = "På plats")]
public TimeSpan There { get; set; }
[Display(Name = "Spelning")]
public TimeSpan Starts { get; set; }
[Display(Name = "Stå- eller gåspelning")]
public string Stand { get; set; }
public bool Old { get; set; }
public int TotalPages { get; set; }
public int CurrentPage { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.IO;
using System.Text;
using System.Data.Entity;
using System.Net;
using System.Web.Mvc;
using SistemaFacturacionWeb.Models;
namespace SistemaFacturacionWeb
{
public partial class BusquedaDetallesFactura : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Ini FacN
string codigo = "";
string s = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection conexion = new SqlConnection(s);
conexion.Open();
SqlCommand comando = new SqlCommand("select * FROM Ventas where Id = '" + this.TextBox1.Text + "'", conexion);
SqlDataReader registro = comando.ExecuteReader();
if (registro.Read())
{
codigo = registro["CustomerId"].ToString();
SqlConnection cn = new SqlConnection("Data Source=DESKTOP-KH2KFO1;initial catalog=facturacion;integrated security=True");
SqlCommand cmd = new SqlCommand("select OrderId,Articulo,ArticuloCodigo,Cantidad,Precio,Total,CustomerId from VentasDetalles WHERE CustomerId = '" + codigo +"'", cn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataSourceID = null;
GridView1.DataBind();
cn.Close();
}
else
{
this.Label1.Text = "No existe Factura";
}
conexion.Close();
//Fin Nfac
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum CellState {
NONE,
IDLE,
SELECTED,
MOVE,
CAPTURE
}
public class CellAppearanceController : MonoBehaviour {
static Dictionary <string, Material> whiteMaterials = new Dictionary <string, Material> ();
static Dictionary <string, Material> blackMaterials = new Dictionary <string, Material> ();
public bool IsWhite { get; set; }
CellState _state;
public CellState State {
get { return _state; }
set {
_state = value;
ApplyState ();
}
}
void Awake () {
var folder = "Materials/Cell/";
if (whiteMaterials.Count == 0) {
whiteMaterials.Add ("Idle", Resources.Load (folder + "WhiteCellIdleMaterial") as Material);
whiteMaterials.Add ("Select", Resources.Load (folder + "WhiteCellSelectMaterial") as Material);
whiteMaterials.Add ("Move", Resources.Load (folder + "WhiteCellMoveMaterial") as Material);
whiteMaterials.Add ("Capture", Resources.Load (folder + "WhiteCellCaptureMaterial") as Material);
}
if (blackMaterials.Count == 0) {
blackMaterials.Add ("Idle", Resources.Load (folder + "BlackCellIdleMaterial") as Material);
blackMaterials.Add ("Select", Resources.Load (folder + "BlackCellSelectMaterial") as Material);
blackMaterials.Add ("Move", Resources.Load (folder + "BlackCellMoveMaterial") as Material);
blackMaterials.Add ("Capture", Resources.Load (folder + "BlackCellCaptureMaterial") as Material);
}
}
CellAppearanceController() {
_state = CellState.NONE;
}
public void Init (bool isWhite) {
IsWhite = isWhite;
State = CellState.IDLE;
}
void ApplyState () {
var dic = IsWhite ? whiteMaterials : blackMaterials;
var mr = GetComponent<MeshRenderer> ();
switch (State) {
case CellState.IDLE:
mr.material = dic ["Idle"];
break;
case CellState.SELECTED:
mr.material = dic ["Select"];
break;
case CellState.MOVE:
mr.material = dic ["Move"];
break;
case CellState.CAPTURE:
mr.material = dic ["Capture"];
break;
}
}
}
|
using UnityAtoms.BaseAtoms;
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Adds Variable Instancer's Variable of type Collider2D to a Collection or List on OnEnable and removes it on OnDestroy.
/// </summary>
[AddComponentMenu("Unity Atoms/Sync Variable Instancer to Collection/Sync Collider2D Variable Instancer to Collection")]
[EditorIcon("atom-icon-delicate")]
public class SyncCollider2DVariableInstancerToCollection : SyncVariableInstancerToCollection<Collider2D, Collider2DVariable, Collider2DVariableInstancer> { }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Agencia_Datos_Entidades;
using Agencia_Dominio;
namespace Agencia.Controllers
{
public class UbigeoController : Controller
{
private readonly D_Ubigeo ubigeo;
public UbigeoController(D_Ubigeo ubigeo)
{
this.ubigeo = ubigeo;
}
//
// GET: /Ubigeo/
public ActionResult Index()
{
var items = ubigeo.TraerTodo();
return View(items);
}
//
// GET: /Ubigeo/Details/5
public ActionResult Details(string id)
{
var item = ubigeo.TraerUno(id);
return View(item);
}
//
// GET: /Ubigeo/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Ubigeo/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Ubigeo/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /Ubigeo/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Ubigeo/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /Ubigeo/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
|
using System;
namespace Compiler.Exceptions
{
public class InvalidReturnTypeException : Exception
{
public InvalidReturnTypeException()
{
}
public InvalidReturnTypeException(string message) : base(message)
{
Message = message;
}
public override string Message { get; }
}
} |
using System;
namespace CC.Mobile.Services
{
public interface IShareService
{
void Share(string subject, string text);
void Email (string email, string subject, string text);
void Email (string email, string cc, string subject, string text);
void Sms (string phone, string message);
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace Beeffective.Migrations
{
public partial class Add_Goal_Tags : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Goal",
table: "Cells",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Tags",
table: "Cells",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Goal",
table: "Cells");
migrationBuilder.DropColumn(
name: "Tags",
table: "Cells");
}
}
}
|
using Alabo.Industry.Offline.Order.Domain.Enums;
namespace Alabo.Industry.Offline.Order.Domain.Dtos
{
public class MerchantOrderListInput
{
/// <summary>
/// 订单状态
/// </summary>
public MerchantOrderStatus OrderStatus { get; set; }
/// <summary>
/// 获取会员Id
/// </summary>
public long UserId { get; set; }
/// <summary>
/// 店铺Id
/// </summary>
public string MerchantStoreId { get; set; }
/// <summary>
/// 当前页 private
/// </summary>
public long PageIndex { get; set; }
/// <summary>
/// 每页记录数 private
/// </summary>
public long PageSize { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
AbstractFactory factoryProducer;
IShape shape;
/*Pinta Objetos simples.*/
factoryProducer = FactoryProducer.getFactory(false);
shape = factoryProducer.getShape("Rectangle");
shape.draw();
shape = factoryProducer.getShape("Square");
shape.draw();
/*Pinta Objetos avanzados.*/
factoryProducer = FactoryProducer.getFactory(true);
shape = factoryProducer.getShape("Rectangle");
shape.draw();
shape = factoryProducer.getShape("Square");
shape.draw();
}
}
}
|
using System;
using Raylib_cs;
namespace RaylibStarterCS
{
class Program
{
static void Main(string[] args)
{
Game game = new Game();
Raylib.InitWindow(640, 480, "Hello World");
game.Init();
while (!Raylib.WindowShouldClose())
{
game.Update();
game.Draw();
}
game.Shutdown();
Raylib.CloseWindow();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using com.Sconit.Utility;
using Telerik.Web.Mvc;
using com.Sconit.Entity.MRP.ORD;
using com.Sconit.Web.Models.SearchModels.MRP;
using com.Sconit.Web.Models;
using com.Sconit.Entity.Exception;
using com.Sconit.Entity;
using com.Sconit.Service.MRP;
using com.Sconit.Service;
using com.Sconit.Entity.MRP.VIEW;
using Telerik.Web.Mvc.UI;
using System.Text;
using com.Sconit.Entity.MD;
using com.Sconit.Entity.MRP.TRANS;
using com.Sconit.Entity.MRP.MD;
namespace com.Sconit.Web.Controllers.MRP
{
public class RccpPlanFiController : WebAppBaseController
{
public IPlanMgr planMgr { get; set; }
public IRccpMgr rccpMgr { get; set; }
//public IGenericMgr genericMgr { get; set; }
[SconitAuthorize(Permissions = "Url_Mrp_RccpPlanFi_IslandMonth")]
public ActionResult IslandMonth()
{
ViewBag.DateIndex = DateTime.Now.ToString("yyyy-MM");
ViewBag.DateIndexTo = DateTime.Now.AddMonths(12).ToString("yyyy-MM");
return View();
}
[SconitAuthorize(Permissions = "Url_Mrp_RccpPlanFi_IslandWeek")]
public ActionResult IslandWeek()
{
ViewBag.DateIndex = com.Sconit.Utility.DateTimeHelper.GetWeekOfYear(DateTime.Now);
ViewBag.DateIndexTo = com.Sconit.Utility.DateTimeHelper.GetWeekOfYear(DateTime.Now.AddDays(7 * 16));
return View();
}
[SconitAuthorize(Permissions = "Url_Mrp_RccpPlanFi_MachineWeek")]
public ActionResult MachineWeek()
{
ViewBag.DateIndex = com.Sconit.Utility.DateTimeHelper.GetWeekOfYear(DateTime.Now);
ViewBag.DateIndexTo = com.Sconit.Utility.DateTimeHelper.GetWeekOfYear(DateTime.Now.AddDays(7 * 16));
return View();
}
[SconitAuthorize(Permissions = "Url_Mrp_RccpPlanFi_MachineMonth")]
public ActionResult MachineMonth()
{
ViewBag.DateIndex = DateTime.Now.ToString("yyyy-MM");
ViewBag.DateIndexTo = DateTime.Now.AddMonths(12).ToString("yyyy-MM");
return View();
}
#region IslandMonth
[SconitAuthorize(Permissions = "Url_Mrp_RccpPlanFi_IslandMonth")]
public string _GetRccpFiPlanView(string dateIndexTo, string dateIndex, DateTime planVersion, string island, string productLine)
{
IList<object> param = new List<object>();
string hql = " from RccpFiPlan as r where r.PlanVersion=? and r.DateType=?";
//param.Add(Convert.ToDateTime("2013-01-25 15:51:07.000"));
param.Add(planVersion);
param.Add(com.Sconit.CodeMaster.TimeUnit.Month);
if (!string.IsNullOrEmpty(dateIndex))
{
hql += " and r.DateIndex>=?";
param.Add(dateIndex);
}
if (!string.IsNullOrEmpty(dateIndexTo))
{
hql += " and r.DateIndex<=?";
param.Add(dateIndexTo);
}
if (!string.IsNullOrEmpty(island))
{
string str = string.Empty;
IList<Machine> machineList = genericMgr.FindAll<Machine>(" from Machine m where m.Island=?", island);
foreach (var machine in machineList)
{
if (str == string.Empty)
{
str += " and r.Machine in (?";
}
else
{
str += ",?";
}
param.Add(machine.Code);
}
str += " )";
hql += str;
}
if (!string.IsNullOrEmpty(productLine))
{
hql += " and r.ProductLine=?";
param.Add(productLine);
}
IList<RccpFiPlan> rccpFiPlanList = genericMgr.FindAll<RccpFiPlan>(hql, param.ToArray());
if (rccpFiPlanList.Count == 0)
{
return Resources.EXT.ControllerLan.Con_NoRecord;
}
IList<RccpFiView> rccpFiViewList = planMgr.GetIslandRccpView(rccpFiPlanList);
return GetStringIsland(rccpFiViewList);
}
private string GetStringIsland(IList<RccpFiView> rccpFiViewList)
{
if (rccpFiViewList.Count == 0)
{
return Resources.EXT.ControllerLan.Con_NoRecord;
}
var dateIndexList = (from r in rccpFiViewList
group r by
new
{
DateIndex = r.DateIndex,
} into g
select new
{
DateIndex = g.Key.DateIndex,
List = g
}).OrderBy(r => r.DateIndex).ToList();
StringBuilder str = new StringBuilder("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" id=\"datatable\" width=\"100%\"><thead><tr>");
str.Append("<th style=\"text-align:center;min-width:70px;width:70px \" >");
str.Append(Resources.MRP.RccpFiPlan.RccpFiPlan_Island);
str.Append("</th>");
str.Append("<th style=\"text-align:center;min-width:70px;width:70px \" >");
str.Append(Resources.MRP.RccpFiPlan.RccpFiPlan_Machine);
str.Append("</th>");
str.Append("<th style=\"text-align:center;min-width:60px;width:60px \" >");
str.Append(Resources.MRP.RccpFiPlan.RccpFiPlan_Type);
str.Append("</th>");
foreach (var rccpFiView in dateIndexList)
{
str.Append("<th style=\"text-align:center;\" >");
str.Append(rccpFiView.DateIndex);
str.Append("</th>");
}
str.Append("</tr></thead><tbody>");
var rccpBodys = (from r in rccpFiViewList
group r by
new
{
Island = r.Island,
} into g
select new
{
Island = g.Key.Island,
IslandDescription = g.First().IslandDescription,
List = g.ToList()
}).ToList();
int l = 0;
foreach (var rccpBody in rccpBodys)
{
l++;
var machineList = rccpBody.List.SelectMany(p => p.RccpFiViewList)
.GroupBy(p => new { p.Machine, p.Description }, (k, g) => new { Machine = k.Machine, Description = k.Description })
.OrderBy(p => p.Machine).ToList();
if (l % 2 == 0)
{
str.Append("<tr class=\"t-alt\">");
}
else
{
str.Append("<tr>");
}
str.Append(string.Format("<td rowspan=\"{0}\">", machineList.Count() * 2 + 3));
str.Append(rccpBody.Island + "<br>[" + rccpBody.IslandDescription + "]");
str.Append("</td>");
foreach (var machine in machineList)
{
if (machineList.IndexOf(machine) > 0)
{
if (l % 2 == 0)
{
str.Append("<tr class=\"t-alt\">");
}
else
{
str.Append("<tr>");
}
}
str.Append("<td rowspan='2'>");
str.Append(machine.Machine + "<br>[" + machine.Description + "]");
str.Append("</td>");
for (int i = 0; i < 2; i++)
{
if (i == 0)
{
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_Demand);
str.Append("</td>");
}
else if (i == 1)
{
if (l % 2 == 0)
{
str.Append("<tr class=\"t-alt\">");
}
else
{
str.Append("<tr>");
}
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_RequiredFactQty);
str.Append("</td>");
}
foreach (var dateIndex in dateIndexList)
{
var rccpMachine = rccpBody.List.SelectMany(p => p.RccpFiViewList)
.Where(p => p.DateIndex == dateIndex.DateIndex && p.Machine == machine.Machine).FirstOrDefault() ?? new RccpFiView();
if (i == 0)
{
str.Append("<td >");
str.Append(rccpMachine.KitQty.ToString("0.##"));
str.Append("</td>");
}
else if (i == 1)
{
str.Append("<td >");
if (rccpMachine.DateType == CodeMaster.TimeUnit.Week)
{
str.Append(rccpMachine.CurrentRequiredFactQty.ToString("0.##"));
}
else
{
str.Append(rccpMachine.RequiredFactQty.ToString("0.##"));
}
str.Append("</td>");
}
}
str.Append("</tr>");
}
}
for (int i = 0; i < 3; i++)
{
if (l % 2 == 0)
{
str.Append("<tr class=\"t-alt\">");
}
else
{
str.Append("<tr>");
}
if (i == 0)
{
str.Append("<td rowspan='3'>");
str.Append(Resources.EXT.ControllerLan.Con_Summary);
str.Append("</td>");
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_Demand);
str.Append("</td>");
}
else if (i == 1)
{
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_IslandQty);
str.Append("</td>");
}
else
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_RequiredFactQty);
str.Append("</td>");
}
#region
foreach (var rccpFiView in dateIndexList)
{
var rccpFiViewFirst = rccpFiView.List.FirstOrDefault(m => m.Island == rccpBody.Island);
if (rccpFiViewFirst != null)
{
if (i == 0)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.KitQty.ToString("0.##"));
str.Append("</td>");
}
else if (i == 1)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.IslandQty.ToString("0.##"));
str.Append("</td>");
}
else
{
if (rccpFiViewFirst.DateType == CodeMaster.TimeUnit.Week)
{
if (rccpFiViewFirst.CurrentRequiredFactQty > rccpFiViewFirst.IslandQty)
{
str.Append("<td class=\"mrp-warning\">");
str.Append(rccpFiViewFirst.CurrentRequiredFactQty.ToString("0.##"));
str.Append("</td>");
}
else
{
str.Append("<td>");
str.Append(rccpFiViewFirst.CurrentRequiredFactQty.ToString("0.##"));
str.Append("</td>");
}
}
else
{
if (rccpFiViewFirst.RequiredFactQty > rccpFiViewFirst.IslandQty)
{
str.Append("<td class=\"mrp-warning\">");
str.Append(rccpFiViewFirst.RequiredFactQty.ToString("0.##"));
str.Append("</td>");
}
else
{
str.Append("<td>");
str.Append(rccpFiViewFirst.RequiredFactQty.ToString("0.##"));
str.Append("</td>");
}
}
}
}
else
{
str.Append("<td>");
str.Append("0");
str.Append("</td>");
}
}
#endregion
str.Append("</tr>");
}
}
//表尾
str.Append("</tbody>");
str.Append("</table>");
return str.ToString();
}
#endregion
#region IslandWeek
[SconitAuthorize(Permissions = "Url_Mrp_RccpPlanFi_IslandWeek")]
public string _GetRccpFiPlanWeekView(string dateIndexTo, string dateIndex, DateTime planVersion, string island, string productLine)
{
IList<object> param = new List<object>();
string hql = " from RccpFiPlan as r where r.PlanVersion=? and r.DateType=?";
//param.Add(Convert.ToDateTime("2013-01-25 15:51:07.000"));
param.Add(planVersion);
param.Add(com.Sconit.CodeMaster.TimeUnit.Week);
if (!string.IsNullOrEmpty(dateIndex))
{
hql += " and r.DateIndex>=?";
param.Add(dateIndex);
}
if (!string.IsNullOrEmpty(dateIndexTo))
{
hql += " and r.DateIndex<=?";
param.Add(dateIndexTo);
}
if (!string.IsNullOrEmpty(island))
{
string str = string.Empty;
IList<Machine> machineList = genericMgr.FindAll<Machine>(" from Machine m where m.Island=?", island);
foreach (var machine in machineList)
{
if (str == string.Empty)
{
str += " and r.Machine in (?";
}
else
{
str += ",?";
}
param.Add(machine.Code);
}
str += " )";
hql += str;
}
if (!string.IsNullOrEmpty(productLine))
{
hql += " and r.ProductLine=?";
param.Add(productLine);
}
IList<RccpFiPlan> rccpFiPlanList = genericMgr.FindAll<RccpFiPlan>(hql, param.ToArray());
if (rccpFiPlanList.Count == 0)
{
return Resources.EXT.ControllerLan.Con_NoRecord;
}
IList<RccpFiView> rccpFiViewList = planMgr.GetIslandRccpView(rccpFiPlanList);
return GetStringIsland(rccpFiViewList);
}
private string GetStringRccpFiPlanWeekView(IList<RccpFiView> rccpFiViewList)
{
if (rccpFiViewList.Count == 0)
{
return Resources.EXT.ControllerLan.Con_NoRecord;
}
var rccpFiViewListGruopby = (from r in rccpFiViewList
group r by
new
{
DateIndex = r.DateIndex,
} into g
select new
{
DateIndex = g.Key.DateIndex,
List = g
}).OrderBy(r => r.DateIndex);
StringBuilder str = new StringBuilder("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" id=\"datatable\" width=\"100%\"><thead><tr>");
str.Append("<th style=\"text-align:center;width:100px\" >");
str.Append(Resources.MRP.RccpFiPlan.RccpFiPlan_Island);
str.Append("</th>");
str.Append("<th style=\"text-align:center;width:80px\" >");
str.Append(Resources.MRP.RccpFiPlan.RccpFiPlan_Type);
str.Append("</th>");
foreach (var rccpFiView in rccpFiViewListGruopby)
{
str.Append("<th style=\"text-align:center\" >");
str.Append(rccpFiView.DateIndex);
str.Append("</th>");
}
str.Append("</tr></thead><tbody>");
var rccpFiViewIslandWeekGruopby = from r in rccpFiViewList
group r by
new
{
Island = r.Island,
} into g
select new RccpFiView
{
Island = g.Key.Island,
IslandDescription = g.First().IslandDescription,
};
int l = 0;
foreach (var rccpPurchasePlanIsland in rccpFiViewIslandWeekGruopby)
{
l++;
for (int i = 0; i < 8; i++)
{
if (l % 2 == 0)
{
str.Append("<tr class=\"t-alt\">");
}
else
{
str.Append("<tr>");
}
if (i == 0)
{
str.Append("<td rowspan=\"8\">");
str.Append(rccpPurchasePlanIsland.Island + "<br>[" + rccpPurchasePlanIsland.IslandDescription + "]");
str.Append("</td>");
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_Demand);
str.Append("</td>");
}
else if (i == 1)
{
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_IslandQty);
str.Append("</td>");
}
else if (i == 2)
{
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_NormalQty);
str.Append("</td>");
}
else if (i == 3)
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_WeekMaxQty);
str.Append("</td>");
}
else if (i == 4)
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_MaxShiftQty);
str.Append("</td>");
}
else if (i == 5)
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_NormalShiftQty);
str.Append("</td>");
}
else if (i == 6)
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_RequiredShiftPerWeek);
str.Append("</td>");
}
else if (i == 7)
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_AlarmLamp);
str.Append("</td>");
}
#region
foreach (var rccpFiView in rccpFiViewListGruopby)
{
var rccpFiViewFirst = rccpFiView.List.FirstOrDefault(m => m.Island == rccpPurchasePlanIsland.Island);
if (rccpFiViewFirst != null)
{
if (i == 0)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.KitQty.ToString("0.##"));
str.Append("</td>");
}
else if (i == 1)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.IslandQty.ToString("0.##"));
str.Append("</td>");
}
else if (i == 2)
{
str.Append("<td>");
str.Append((rccpFiViewFirst.NormalQty / rccpFiViewFirst.ModelRate).ToString("0.##"));
str.Append("</td>");
}
else if (i == 3)
{
str.Append("<td>");
str.Append((rccpFiViewFirst.MaxQty / rccpFiViewFirst.ModelRate).ToString("0.##"));
str.Append("</td>");
}
else if (i == 4)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.MaxShiftQty.ToString("0.##"));
str.Append("</td>");
}
else if (i == 5)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.NormalShiftQty.ToString("0.##"));
str.Append("</td>");
}
else if (i == 6)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.RequiredShiftQty.ToString("0.##"));
str.Append("</td>");
}
else if (i == 7)
{
if (rccpFiViewFirst.Qty > rccpFiViewFirst.MaxQty)
{
str.Append("<td>");
str.Append("<img src='/Content/Images/Icon/Error.png'/>");
str.Append("</td>");
}
else if (rccpFiViewFirst.Qty < rccpFiViewFirst.MaxQty && rccpFiViewFirst.Qty > rccpFiViewFirst.NormalQty)
{
str.Append("<td>");
str.Append("<img src='/Content/Images/Icon/Warning.png'/>");
str.Append("</td>");
}
else
{
str.Append("<td>");
str.Append("<img src='/Content/Images/Icon/Success.png'/>");
str.Append("</td>");
}
}
}
else
{
if (i == 7)
{
str.Append("<td>");
str.Append("<img src='/Content/Images/Icon/Success.png'>");
str.Append("</td>");
}
else
{
str.Append("<td>");
str.Append("0");
str.Append("</td>");
}
}
}
}
#endregion
str.Append("</tr>");
}
//表尾
str.Append("</tbody>");
str.Append("</table>");
return str.ToString();
}
#endregion
#region MachineMonth
[SconitAuthorize(Permissions = "Url_Mrp_RccpPlanFi_MachineMonth")]
public string _GetMachineMonthView(string dateIndexTo, string dateIndex, DateTime planVersion, string machine, string productLine, string island)
{
IList<object> param = new List<object>();
string hql = " from RccpFiPlan as r where r.PlanVersion=? and r.DateType=?";
//param.Add(Convert.ToDateTime("2013-01-25 15:51:07.000"));
param.Add(planVersion);
param.Add(com.Sconit.CodeMaster.TimeUnit.Month);
if (!string.IsNullOrEmpty(machine))
{
hql += " and r.Machine=?";
param.Add(machine);
}
if (!string.IsNullOrEmpty(productLine))
{
hql += " and r.ProductLine=?";
param.Add(productLine);
}
if (!string.IsNullOrEmpty(dateIndex))
{
hql += " and r.DateIndex>=?";
param.Add(dateIndex);
}
if (!string.IsNullOrEmpty(dateIndexTo))
{
hql += " and r.DateIndex<=?";
param.Add(dateIndexTo);
}
if (!string.IsNullOrEmpty(island))
{
string hql1 = string.Empty;
IList<Machine> machineList = genericMgr.FindAll<Machine>(" from Machine m where m.Island=?", island);
foreach (var mdMachine in machineList)
{
if (hql1 == string.Empty)
{
hql1 += " and r.Machine in (?";
}
else
{
hql1 += ",?";
}
param.Add(mdMachine.Code);
}
hql1 += " )";
hql += hql1;
}
IList<RccpFiPlan> rccpFiPlanList = genericMgr.FindAll<RccpFiPlan>(hql, param.ToArray());
if (rccpFiPlanList.Count == 0)
{
return Resources.EXT.ControllerLan.Con_NoRecord;
}
var rccpFiViewList = planMgr.GetMachineRccpView(rccpFiPlanList).ToList();
//var rccpFiViewIslandTotal = from r in rccpFiViewList
// group r by
// new
// {
// Machine = r.Machine,
// } into g
// select new RccpFiView
// {
// DateIndex = "Total",
// Machine = g.Key.Machine,
// KitQty = g.Sum(p => p.KitQty),
// MachineQty = g.Average(p => p.MachineQty),
// RequiredFactQty = g.Average(p => p.RequiredFactQty),
// MaxQty = g.Sum(p => p.MaxQty / p.ModelRate),
// ShiftQuota = g.Average(p => p.ShiftQuota),
// MaxShiftQty = g.Sum(p => p.MaxShiftQty),
// MaxWorkDay = g.Sum(p => p.MaxWorkDay),
// NormalWorkDay = g.Sum(p => p.NormalWorkDay),
// TrialProduceTime = g.Sum(p => p.TrialProduceTime),
// HaltTime = g.Sum(p => p.HaltTime),
// Holiday = g.Sum(p => p.Holiday)
// };
//rccpFiViewList.AddRange(rccpFiViewIslandTotal);
var rccpFiViewListGruopby = (from r in rccpFiViewList
group r by
new
{
DateIndex = r.DateIndex,
} into g
select new
{
DateIndex = g.Key.DateIndex,
List = g
}).OrderBy(r => r.DateIndex);
StringBuilder str = new StringBuilder("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" id=\"datatable\" width=\"100%\"><thead><tr>");
str.Append("<th style=\"text-align:center;min-width:70px;width:70px;\" >");
str.Append(Resources.MRP.RccpFiPlan.RccpFiPlan_Machine);
str.Append("</th>");
str.Append("<th style=\"text-align:center;min-width:60px;width:60px;\" >");
str.Append(Resources.MRP.RccpFiPlan.RccpFiPlan_Type);
str.Append("</th>");
foreach (var rccpFiView in rccpFiViewListGruopby)
{
str.Append("<th style=\"text-align:center\" >");
str.Append(rccpFiView.DateIndex);
str.Append("</th>");
}
str.Append("</tr></thead><tbody>");
var rccpFiViewMachineGruopby = from r in rccpFiViewList
group r by
new
{
Machine = r.Machine,
} into g
select new RccpFiView
{
Machine = g.Key.Machine,
Description = g.First().Description,
};
int l = 0;
foreach (var rccpPurchasePlanMachine in rccpFiViewMachineGruopby)
{
l++;
for (int i = 0; i < 11; i++)
{
if (l % 2 == 0)
{
str.Append("<tr class=\"t-alt\">");
}
else
{
str.Append("<tr>");
}
if (i == 0)
{
str.Append("<td rowspan=\"11\">");
str.Append(rccpPurchasePlanMachine.Machine + "<br>[" + rccpPurchasePlanMachine.Description + "]");
str.Append("</td>");
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_Demand);
str.Append("</td>");
}
else if (i == 1)
{
str.Append("<td>");
str.Append(Resources.EXT.ControllerLan.Con_MaxCapacity);
str.Append("</td>");
}
else if (i == 2)
{
str.Append("<td >");
str.Append(Resources.EXT.ControllerLan.Con_CurrentMaxCapacity);
str.Append("</td>");
}
else if (i == 3)
{
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_ShiftQuota);
str.Append("</td>");
}
else if (i == 4)
{
str.Append("<td>");
str.Append(Resources.EXT.ControllerLan.Con_WorkDays);
str.Append("</td>");
}
else if (i == 5)
{
str.Append("<td>");
str.Append(Resources.EXT.ControllerLan.Con_CalendarDays);
str.Append("</td>");
}
else if (i == 6)
{
str.Append("<td>");
str.Append(Resources.EXT.ControllerLan.Con_Holidays);
str.Append("</td>");
}
else if (i == 7)
{
str.Append("<td>");
str.Append(Resources.EXT.ControllerLan.Con_HaltDays);
str.Append("</td>");
}
else if (i == 8)
{
str.Append("<td>");
str.Append(Resources.EXT.ControllerLan.Con_TrailDays);
str.Append("</td>");
}
else if (i == 9)
{
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_MachineQty);
str.Append("</td>");
}
else
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_RequiredFactQtyMachine);
str.Append("</td>");
}
#region
foreach (var rccpFiView in rccpFiViewListGruopby)
{
var rccpFiViewFirst = rccpFiView.List.FirstOrDefault(m => m.Machine == rccpPurchasePlanMachine.Machine);
if (rccpFiViewFirst != null)
{
if (i == 0)
{
str.Append("<td>");
str.Append((rccpFiViewFirst.Qty / rccpFiViewFirst.ModelRate).ToString("0.##"));
str.Append("</td>");
}
else if (i == 1)
{
str.Append("<td>");
str.Append((rccpFiViewFirst.MaxQty / rccpFiViewFirst.ModelRate).ToString("0.##"));
str.Append("</td>");
}
else if (i == 2)
{
str.Append("<td>");
str.Append((rccpFiViewFirst.CurrentMaxQty / rccpFiViewFirst.ModelRate).ToString("0.##"));
str.Append("</td>");
}
else if (i == 3)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.KitShiftQuota.ToString("0.##"));
str.Append("</td>");
}
else if (i == 4)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.NormalWorkDay.ToString("0.##"));
str.Append("</td>");
}
else if (i == 5)
{
str.Append("<td>");
str.Append((rccpFiViewFirst.MaxWorkDay + rccpFiViewFirst.Holiday + rccpFiViewFirst.HaltTime + rccpFiViewFirst.TrialProduceTime).ToString("0.##"));
str.Append("</td>");
}
else if (i == 6)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.Holiday.ToString("0.##"));
str.Append("</td>");
}
else if (i == 7)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.HaltTime.ToString("0.##"));
str.Append("</td>");
}
else if (i == 8)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.TrialProduceTime.ToString("0.##"));
str.Append("</td>");
}
else if (i == 9)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.MachineQty.ToString("0.##"));
str.Append("</td>");
}
else
{
if (rccpFiViewFirst.RequiredFactQty > rccpFiViewFirst.MachineQty)
{
str.Append("<td class=\"mrp-warning\">");
str.Append(rccpFiViewFirst.RequiredFactQty.ToString("0.##"));
str.Append("</td>");
}
else
{
str.Append("<td>");
str.Append(rccpFiViewFirst.RequiredFactQty.ToString("0.##"));
str.Append("</td>");
}
}
}
else
{
str.Append("<td>");
str.Append("0");
str.Append("</td>");
}
}
#endregion
}
str.Append("</tr>");
}
//表尾
str.Append("</tbody>");
str.Append("</table>");
return str.ToString();
}
#endregion
#region MachineWeek
[SconitAuthorize(Permissions = "Url_Mrp_RccpPlanFi_MachineWeek")]
public string _GetRccpFiPlanMachineWeekView(string dateIndexTo, string dateIndex, DateTime planVersion, string machine, string productLine, string island)
{
IList<object> param = new List<object>();
string hql = " from RccpFiPlan as r where r.PlanVersion=? and r.DateType=?";
param.Add(planVersion);
param.Add(com.Sconit.CodeMaster.TimeUnit.Week);
if (!string.IsNullOrEmpty(machine))
{
hql += " and r.Machine=?";
param.Add(machine);
}
if (!string.IsNullOrEmpty(productLine))
{
hql += " and r.ProductLine=?";
param.Add(productLine);
}
if (!string.IsNullOrEmpty(dateIndex))
{
hql += " and r.DateIndex>=?";
param.Add(dateIndex);
}
if (!string.IsNullOrEmpty(dateIndexTo))
{
hql += " and r.DateIndex<=?";
param.Add(dateIndexTo);
}
if (!string.IsNullOrEmpty(island))
{
string str = string.Empty;
IList<Machine> machineList = genericMgr.FindAll<Machine>(" from Machine m where m.Island=?", island);
foreach (var mdMachine in machineList)
{
if (str == string.Empty)
{
str += " and r.Machine in (?";
}
else
{
str += ",?";
}
param.Add(mdMachine.Code);
}
str += " )";
hql += str;
}
IList<RccpFiPlan> rccpFiPlanList = genericMgr.FindAll<RccpFiPlan>(hql, param.ToArray());
if (rccpFiPlanList.Count == 0)
{
return Resources.EXT.ControllerLan.Con_NoRecord;
}
IList<RccpFiView> rccpFiViewList = planMgr.GetMachineRccpView(rccpFiPlanList);
return GetStringRccpFiPlanMachineWeekView(rccpFiViewList);
}
private string GetStringRccpFiPlanMachineWeekView(IList<RccpFiView> rccpFiViewList)
{
if (rccpFiViewList.Count == 0)
{
return Resources.EXT.ControllerLan.Con_NoRecord;
}
var rccpFiViewListGruopby = (from r in rccpFiViewList
group r by
new
{
DateIndex = r.DateIndex,
} into g
select new
{
DateIndex = g.Key.DateIndex,
List = g
}).OrderBy(r => r.DateIndex);
StringBuilder str = new StringBuilder("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" id=\"datatable\" width=\"100%\"><thead><tr>");
str.Append("<th style=\"text-align:center;min-width:70px;width:70px;\" >");
str.Append(Resources.MRP.RccpFiPlan.RccpFiPlan_Machine);
str.Append("</th>");
str.Append("<th style=\"text-align:center;min-width:60px;width:60px;\" >");
str.Append(Resources.MRP.RccpFiPlan.RccpFiPlan_Type);
str.Append("</th>");
foreach (var rccpFiView in rccpFiViewListGruopby)
{
str.Append("<th style=\"text-align:center\" >");
str.Append(rccpFiView.DateIndex);
str.Append("</th>");
}
str.Append("</tr></thead><tbody>");
var rccpFiViewMachineWeekGruopby = from r in rccpFiViewList
group r by
new
{
Machine = r.Machine,
} into g
select new RccpFiView
{
Machine = g.Key.Machine,
Description = g.First().Description,
};
int l = 0;
foreach (var rccpPurchasePlanMachine in rccpFiViewMachineWeekGruopby)
{
l++;
for (int i = 0; i < 12; i++)
{
if (l % 2 == 0)
{
str.Append("<tr class=\"t-alt\">");
}
else
{
str.Append("<tr>");
}
if (i == 0)
{
str.Append("<td rowspan=\"12\">");
str.Append(rccpPurchasePlanMachine.Machine + "<br>[" + rccpPurchasePlanMachine.Description + "]");
str.Append("</td>");
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_Demand);
str.Append("</td>");
}
else if (i == 1)
{
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_WeekShiftQuota);
str.Append("</td>");
}
else if (i == 2)
{
str.Append("<td >");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_ShiftType);
str.Append("</td>");
}
else if (i == 3)
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_NormalWorkDay);
str.Append("</td>");
}
else if (i == 4)
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_MaxWorkDay);
str.Append("</td>");
}
else if (i == 5)
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_MachineQty);
str.Append("</td>");
}
else if (i == 6)
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_NormalQty);
str.Append("</td>");
}
else if (i == 7)
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_WeekMaxQty);
str.Append("</td>");
}
else if (i == 8)
{
str.Append("<td>");
str.Append(Resources.EXT.ControllerLan.Con_RequirementMachine);
str.Append("</td>");
}
else if (i == 9)
{
str.Append("<td>");
str.Append(Resources.EXT.ControllerLan.Con_Gap);
str.Append("</td>");
}
else if (i == 10)
{
str.Append("<td>");
str.Append(Resources.EXT.ControllerLan.Con_RequirementShift);
str.Append("</td>");
}
else if (i == 11)
{
str.Append("<td>");
str.Append(@Resources.MRP.RccpFiPlan.RccpFiPlan_AlarmLamp);
str.Append("</td>");
}
#region
foreach (var rccpFiView in rccpFiViewListGruopby)
{
var rccpFiViewFirst = rccpFiView.List.FirstOrDefault(m => m.Machine == rccpPurchasePlanMachine.Machine);
if (rccpFiViewFirst != null)
{
if (i == 0)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.KitQty.ToString("0.##"));
str.Append("</td>");
}
else if (i == 1)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.KitShiftQuota.ToString("0.##"));
str.Append("</td>");
}
else if (i == 2)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.ShiftPerDay);
str.Append("</td>");
}
else if (i == 3)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.NormalWorkDay.ToString("0.##"));
str.Append("</td>");
}
else if (i == 4)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.MaxWorkDay.ToString("0.##"));
str.Append("</td>");
}
else if (i == 5)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.MachineQty.ToString("0.##"));
str.Append("</td>");
}
else if (i == 6)
{
str.Append("<td>");
str.Append((rccpFiViewFirst.CurrentNormalQty / rccpFiViewFirst.ModelRate).ToString("0.##"));
str.Append("</td>");
}
else if (i == 7)
{
str.Append("<td>");
str.Append((rccpFiViewFirst.CurrentMaxQty / rccpFiViewFirst.ModelRate).ToString("0.##"));
str.Append("</td>");
}
else if (i == 8)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.RequiredFactQty.ToString("0.##"));
str.Append("</td>");
}
else if (i == 9)
{
str.Append("<td>");
str.Append((rccpFiViewFirst.CurrentDiffQty / rccpFiViewFirst.ModelRate).ToString("0.##"));
str.Append("</td>");
}
else if (i == 10)
{
str.Append("<td>");
str.Append(rccpFiViewFirst.RequiredShiftPerDay.ToString("0.##"));
str.Append("</td>");
}
else if (i == 11)
{
if (rccpFiViewFirst.Qty > rccpFiViewFirst.CurrentMaxQty)
{
str.Append("<td>");
str.Append("<img src='/Content/Images/Icon/Error.png'/>");
str.Append("</td>");
}
else if (rccpFiViewFirst.Qty < rccpFiViewFirst.CurrentMaxQty && rccpFiViewFirst.Qty > rccpFiViewFirst.CurrentNormalQty)
{
str.Append("<td>");
str.Append("<img src='/Content/Images/Icon/Warning.png'/>");
str.Append("</td>");
}
else
{
str.Append("<td>");
str.Append("<img src='/Content/Images/Icon/Success.png'/>");
str.Append("</td>");
}
}
}
else
{
if (i == 11)
{
str.Append("<td>");
str.Append("<img src='/Content/Images/Icon/Success.png'>");
str.Append("</td>");
}
else
{
str.Append("<td>");
str.Append("0");
str.Append("</td>");
}
}
}
}
#endregion
str.Append("</tr>");
}
//表尾
str.Append("</tbody>");
str.Append("</table>");
return str.ToString();
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
public class MovementUtilities
{
public static IEnumerator EaseIn (GameObject obj, Vector3 target, float maxSpeed, bool destroyOnArrival, bool invokeClearToContinue)
{
Vector3 startPos = obj.transform.position;
float speed = maxSpeed;
while (Vector3.Distance(obj.transform.position, target) > 0.01f)
{
speed = Vector3.Distance(obj.transform.position, target) * 2.5f;
if (speed > maxSpeed)
{
speed = maxSpeed;
}
if (speed < 0.2f)
{
speed = 0.2f;
}
obj.transform.position = Vector3.MoveTowards (obj.transform.position, target, Time.deltaTime * speed);
yield return new WaitForFixedUpdate ();
}
obj.transform.position = target;
if (destroyOnArrival == true)
{
GameObject.Destroy (obj);
}
if (invokeClearToContinue == true)
{
EventsHandler.Invoke_Callback (EventsHandler.cb_isClearToContinue);
}
}
public static IEnumerator MoveConstantSpeed (GameObject obj, Vector3 target, float maxSpeed, bool destroyOnArrival, bool invokeClearToContinue)
{
Vector3 startPos = obj.transform.position;
float speed = maxSpeed;
while (Vector3.Distance(obj.transform.position, target) > 0.01f)
{
obj.transform.position = Vector3.MoveTowards (obj.transform.position, target, Time.deltaTime * speed);
yield return new WaitForFixedUpdate ();
}
obj.transform.position = target;
if (destroyOnArrival == true)
{
GameObject.Destroy (obj);
}
if (invokeClearToContinue == true)
{
EventsHandler.Invoke_Callback (EventsHandler.cb_isClearToContinue);
}
}
public static IEnumerator EaseOut (GameObject obj, Vector3 target, float maxSpeed, bool destroyOnArrival, bool invokeClearToContinue)
{
Vector3 startPos = obj.transform.position;
float speed = 0;
while (Vector3.Distance(obj.transform.position, target) > 0.01f)
{
speed += Time.deltaTime * maxSpeed;
if (speed > maxSpeed)
{
speed = maxSpeed;
}
obj.transform.position = Vector3.MoveTowards (obj.transform.position, target, Time.deltaTime * speed);
yield return new WaitForFixedUpdate ();
}
obj.transform.position = target;
if (destroyOnArrival == true)
{
GameObject.Destroy (obj);
}
if (invokeClearToContinue == true)
{
EventsHandler.Invoke_Callback (EventsHandler.cb_isClearToContinue);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
public class Product
{
[ScaffoldColumn(false)]
public int ProductID
{
get;
set;
}
[DisplayName("Product name")]
public string ProductName
{
get;
set;
}
[DisplayName("Units in stock")]
[DataType("Integer")]
public int UnitsInStock
{
get;
set;
}
public bool? Available { get; set; }
}
}
|
using System;
using System.Linq;
using System.Web.Http;
using Uintra.Core.Member.Abstractions;
using Uintra.Features.Permissions.Interfaces;
using Umbraco.Core.Services;
using Umbraco.Web.WebApi;
namespace Uintra.Core.Member.Controllers
{
public class MemberApiController : UmbracoAuthorizedApiController
{
private readonly ICacheableIntranetMemberService _cacheableIntranetMemberService;
private readonly IIntranetMemberGroupService _memberGroupService;
private readonly IMemberService _memberService;
public MemberApiController(
ICacheableIntranetMemberService cacheableIntranetMemberService,
IIntranetMemberGroupService memberGroupService,
IMemberService memberService)
{
_cacheableIntranetMemberService = cacheableIntranetMemberService;
_memberGroupService = memberGroupService;
_memberService = memberService;
}
[HttpPost]
public virtual bool MemberChanged(Guid memberId)
{
var member = _memberService.GetByKey(memberId);
var groups = _memberService.GetAllRoles(member.Id).ToList();
if (!groups.Any())
{
_memberGroupService.AssignDefaultMemberGroup(member.Id);
}
if (groups.Count > 1)
{
_memberGroupService.RemoveFromAll(member.Id);
_memberGroupService.AssignDefaultMemberGroup(member.Id);
}
_cacheableIntranetMemberService.UpdateMemberCache(memberId);
return true;
}
}
} |
using System.Collections.Generic;
using System.Drawing;
namespace MageTwinstick
{
/// <summary>
/// Superclass for anything that exsist in the GameWorld
/// </summary>
abstract class GameObject
{
//fields
protected Image sprite; //!< Image sprite for the GameObject
protected Rectangle display; //!< Rectangle for the display
protected List<Image> animationFrames; //!< List of images for animated objects
protected float currentFrameIndex;//!< the current Frame in the animation
protected float animationSpeed;//!< the speed of the animation
private RectangleF collisionBox;//!< the collider rectangle
//Properteis
//Auto properties for the values
/// <summary>
/// 2D Vector for the GameObject position
/// </summary>
public Vector2D Position { get; set; }
/// <summary>
/// Rectanglge for the GameObjects collider
/// </summary>
public RectangleF CollisionBox
{
get
{
collisionBox = new RectangleF(Position.X, Position.Y, sprite.Width, sprite.Height);
return collisionBox;
}
}
/// <summary>
/// GameObject Constructor
/// </summary>
/// <param name="imagePath">Image path for the sprite</param>
/// <param name="startPos">The starting position of the GameObject</param>
/// <param name="display">Rectangle for the diplay</param>
/// <param name="animationSpeed">Animation speed for animated objects</param>
public GameObject(string imagePath, Vector2D startPos, Rectangle display, float animationSpeed)
{
//Assigning the values to the fields
this.Position = startPos;
this.display = display;
this.animationSpeed = animationSpeed;
//Spit the inputted imagepaths to we can have animations
string[] imagePaths = imagePath.Split(';');
//Initate the list ´to we can use it
animationFrames = new List<Image>();
//Add each image to the list from the paths in the paths array
foreach (string path in imagePaths)
{
animationFrames.Add(Image.FromFile(path));
}
//Set the sprite to the first fram in the animation
sprite = animationFrames[0];
}
//Methods
/// <summary>
/// draws the graphics in the GameWorld
/// </summary>
/// <param name="dc">GDI+ class for drawing the sprite</param>
public virtual void Draw(Graphics dc)
{
//Draws the sprite
dc.DrawImage(sprite, Position.X, Position.Y, sprite.Width, sprite.Height);
}
/// <summary>
/// updates the information in the GameObject
/// </summary>
/// <param name="fps">Fps used to update based on time</param>
public virtual void Update(float fps)
{
CheckCollision();
}
/// <summary>
/// Animates the sprite on the GameObject
/// </summary>
/// <param name="fps">Fps used to update based on time</param>
public virtual void UpdateAnimation(float fps)
{
//make a factor based on the fps
float factor = 1 / fps;
//set the current fram of the animation depending on the speed an the factor
currentFrameIndex += factor * animationSpeed;
//Reset the animation if it is done
if (currentFrameIndex >= animationFrames.Count)
{
currentFrameIndex = 0;
}
//Apply the current frame to the sprite
sprite = animationFrames[(int)currentFrameIndex];
}
/// <summary>
/// Checks for collision with other GameObjects
/// </summary>
public void CheckCollision()
{
//Check if the current object is colliding with any one of the object currently in the list
foreach (GameObject go in GameWorld.Objects)
{
//Dont check it self
if (go != this)
{
// if it is colliding with some thing
if (IsCollidingWith(go))
{
OnCollision(go);
}
}
}
}
/// <summary>
/// Checks for collision with a specific GameObject
/// </summary>
/// <param name="other">The other GameObject</param>
/// <returns></returns>
public bool IsCollidingWith(GameObject other)
{
//Return wether two collisionboxes are collising
return collisionBox.IntersectsWith(other.CollisionBox);
}
/// <summary>
/// Abstract method for functionality when colliding with a specific GameObject
/// </summary>
/// <param name="other">The other GameObject</param>
public abstract void OnCollision(GameObject other);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameControl : MonoBehaviour {
public Text timerLabel;
public Text restartLabel;
public float maxTimer = 60f;
private float timer = 60f;
public bool stopTimer;
public bool ended;
// Use this for initialization
void Awake () {
ended = false;
stopTimer = false;
timer = maxTimer;
restartLabel.gameObject.SetActive(false);
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Submit")) {
Scene loadedLevel = SceneManager.GetActiveScene();
SceneManager.LoadScene(loadedLevel.buildIndex);
}
if (Input.GetKeyDown(KeyCode.Escape) || Input.GetButtonDown("Cancel")) {
Application.Quit();
}
if (!ended) {
if (!stopTimer) {
timer -= Time.deltaTime;
if ( timer <= 0 )
{
restartLabel.gameObject.SetActive(true);
ended = true;
}
else
{
//ended = true;
timerLabel.text = string.Format ("{0:00}", timer);
}
}
}
else
{
if (Input.GetKeyDown(KeyCode.Space)) {
Scene loadedLevel = SceneManager.GetActiveScene();
SceneManager.LoadScene(loadedLevel.buildIndex);
}
}
}
public void StopTimer() {
stopTimer = true;
}
}
|
using momo.Entity.Premission;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace momo.Domain.SystemManager.UseManager
{
public interface IUserDomain
{
#region APIs
/// <summary>
/// 获取所有用户
/// </summary>
/// <returns></returns>
Task<IList<IdentityUser>> GetAllUserAsync();
Task<int> AddUser(IdentityUser user);
Task<int> ModifyUser(IdentityUser user);
Task<int> DeleteUser(Guid guid);
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Forms;
using System.Globalization;
namespace MakePayroll {
public class MainWindowViewModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
public List<PayrollView> payrolls { get; set; }
public PayrollView rowPayroll { get; set; }
public ICollectionView payrollView { get; set; }
public MainWindowViewModel() {
Queries queries = new Queries();
payrolls = queries.getPayrollView();
payrollView = CollectionViewSource.GetDefaultView(payrolls);
}
public void add() {
Queries queries = new Queries();
PayrollView rowPayroll = new PayrollView();
rowPayroll.number = queries.getTabelNumber().ToString("00000000");
rowPayroll.date = DateTime.Now;
queries.addPayroll(rowPayroll);
PayrollWindow win = new PayrollWindow(rowPayroll);
win.ShowDialog();
if (win.DialogResult == true) {
payrolls.Add(rowPayroll);
payrollView.Refresh();
this.rowPayroll = rowPayroll;
} else {
queries.removePayroll(rowPayroll);
}
}
public void remove() {
if (rowPayroll == null)
return;
payrolls.Remove(rowPayroll);
Queries queries = new Queries();
queries.removePayroll(rowPayroll);
payrollView.Refresh();
}
public void edit() {
if (rowPayroll == null)
return;
PayrollWindow win = new PayrollWindow(rowPayroll);
win.ShowDialog();
if (win.DialogResult == true) {
Queries queries = new Queries();
queries.editPayroll(rowPayroll);
payrollView.Refresh();
}
}
}
}
|
using UnityEngine;
using GFW;
using CodeX;
public class AppMain : MonoBehaviour {
public bool DebugMode = true;
public bool EnableLog = true;
// Use this for initialization
void Start () {
AppConst.DebugMode = DebugMode;
if (AppConst.DebugMode)
{
AppConst.LuaBundleMode = false;
AppConst.UpdateMode = false;
}
else
{
AppConst.LuaBundleMode = true;
AppConst.UpdateMode = true;
}
if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
{
LogMgr.EnableLog = EnableLog;
gameObject.AddComponent<LogViewer>();
}
ModuleStarter.Instance.StartUp();
}
private void Update()
{
}
private void OnDestroy()
{
ModuleStarter.Instance.ReleaseAll();
}
private void OnApplicationQuit()
{
ModuleStarter.Instance.Dispose();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FuelRadar.UI.Toast
{
public interface IToastNotifier
{
void ShowToast(String message);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeadZone : MonoBehaviour {
public Transform spawnBallPosition;
public LauncherDoor launcherDoor;
public ScoreManager manager;
void OnTriggerEnter(Collider ballCollider){
Debug.Log ("Ha entrado");
manager.ResetScore ();
Debug.Log ("Abriendo puerta lanzador");
launcherDoor.SetState(true);
GameObject ball = ballCollider.gameObject;
//Mover bola al punto de spawn
ball.transform.position = spawnBallPosition.position;
ball.transform.rotation = spawnBallPosition.rotation;
Debug.Log ("Bola movida al spawn");
//Poner a cero las velocidades del rigidbody
Rigidbody rb = ball.GetComponent<Rigidbody>();
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
Debug.Log ("Velocidades y direccion reseteadas");
//Acceder al componente Ball Launcher de la bola y la variable fired ponerla a false
BallLauncher launcher = ball.GetComponent<BallLauncher>();
launcher.fired = false;
}
}
|
using System.Linq;
using aairvid.Utils;
namespace libairvidproto.model
{
public class Video : AirVidResource
{
public static readonly int ContentType = (int)EmContentType.Video;
public Video(AirVidServer server, string name, string id, NodeInfo parent)
: base(server, name, id, parent)
{
}
public MediaInfo GetMediaInfo(IWebClient webClient)
{
return Server.GetMediaInfo(webClient, this);
}
public string GetPlaybackUrl(IWebClient webClient,
MediaInfo mediaInfo,
SubtitleStream sub,
AudioStream audio,
ICodecProfile profile)
{
bool noSub = true;
if (sub != null)
{
if (sub.Language == null)
{
noSub = false;
}
else if (string.IsNullOrWhiteSpace(sub.Language.Value))
{
noSub = false;
}
else if (sub.Language.Value.ToUpperInvariant() != "DISABLED")
{
noSub = false;
}
}
if (!noSub)
{
return Server.GetPlayWithConvUrl(webClient, this, mediaInfo, sub, audio, profile);
}
if(audio != null && audio.index != 1)
{
return Server.GetPlayWithConvUrl(webClient, this, mediaInfo, sub, audio, profile);
}
return Server.GetPlaybackUrl(webClient, this);
}
public string GetPlayWithConvUrl(IWebClient webClient, MediaInfo mediaInfo,
SubtitleStream sub, AudioStream audio, ICodecProfile profile)
{
return Server.GetPlayWithConvUrl(webClient, this, mediaInfo, sub, audio, profile);
}
public string GetDispName()
{
return Id.Split('\\').LastOrDefault();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using UniversityCourseAndResultMangementSystem.Models;
namespace UniversityCourseAndResultMangementSystem.Gateway
{
public class RegisterStudentGateway
{
string connectingString = WebConfigurationManager.ConnectionStrings["ConnectionDB"].ConnectionString;
public int InsertRegisterStudent(RegisterStudentModel registerStudentModel)
{
SqlConnection connection = new SqlConnection(connectingString);
string query = "INSERT INTO RegisterStudent VALUES ('" + registerStudentModel.StudentId + "','" + registerStudentModel.Name + "','" + registerStudentModel.Email + "','" + registerStudentModel.ContactNo + "', '" + registerStudentModel.Date + "''" + registerStudentModel.Address + "','" + registerStudentModel.DepartmentId + "');";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
int rowAffected = command.ExecuteNonQuery();
connection.Close();
return rowAffected;
}
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UnreliablePerformanceBenchmark.cs">
// Copyright (c) 2020 Johannes Deml. All rights reserved.
// </copyright>
// <author>
// Johannes Deml
// public@deml.io
// </author>
// --------------------------------------------------------------------------------------------------------------------
using BenchmarkDotNet.Attributes;
namespace NetworkBenchmark
{
[Config(typeof(PerformanceBenchmarkConfig))]
public class UnreliablePerformanceBenchmark : APredefinedBenchmark
{
[Params(NetworkLibrary.ENet, NetworkLibrary.LiteNetLib, NetworkLibrary.NetCoreServer)]
public NetworkLibrary Library { get; set; }
[Params(TransmissionType.Unreliable)]
public TransmissionType Transmission { get; set; }
[Params(500, Priority = 100)]
public override int Clients { get; set; }
public override int MessageTarget { get; set; } = 500_000;
protected override BenchmarkMode Mode => BenchmarkMode.Performance;
protected override NetworkLibrary LibraryTarget => Library;
[GlobalSetup(Target = nameof(PingPongUnreliable))]
public void PreparePingPongUnreliable()
{
BenchmarkCoordinator.ApplyPredefinedConfiguration();
var config = BenchmarkCoordinator.Config;
config.ParallelMessages = 1;
config.MessageByteSize = 32;
config.Transmission = Transmission;
PrepareBenchmark();
}
[GlobalSetup(Target = nameof(PingPongBatchedUnreliable))]
public void PreparePingPongBatchedUnreliable()
{
BenchmarkCoordinator.ApplyPredefinedConfiguration();
var config = BenchmarkCoordinator.Config;
config.ParallelMessages = 10;
config.MessageByteSize = 32;
config.Transmission = Transmission;
PrepareBenchmark();
}
[Benchmark]
public long PingPongUnreliable()
{
return RunBenchmark();
}
[Benchmark]
public long PingPongBatchedUnreliable()
{
return RunBenchmark();
}
public override string ToString()
{
return "UnreliablePerformanceBenchmark";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentNHibernate.Mapping;
namespace Nhibernate
{
class BookMap:ClassMap<Book>
{
public BookMap()
{
Id(x => x.Id);
Map(x => x.Title);
References(x => x.Author).Cascade.All();
}
}
}
|
using System.Collections.Generic;
using System.Security.Principal;
namespace Tests.Utils.WebFakers
{
public class FakePrincipal : IPrincipal
{
private readonly string _username;
private List<string> _roles = new List<string>();
public List<string> Roles
{
get { return _roles; }
}
public FakePrincipal() : this("TestUser")
{
}
public FakePrincipal(string username)
{
_username = username;
}
public IIdentity Identity
{
get { return new GenericIdentity(_username); }
}
public bool IsInRole(string role)
{
return _roles.Contains(role);
}
public void AddRoles(params string[] roles)
{
foreach (var role in roles)
{
_roles.Add(role);
}
}
public void ClearRoles()
{
_roles = new List<string>();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.