text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Text;
using Models;
namespace BLL.Interface
{
public interface IQuanTriBusiness
{
public List<GIANGVIEN> DangNhapGiangVien(int role, string un, string pas);
public List<SINHVIEN> LayDSSVTheoMaLopChuyenNganh(int ki, string malop);
public List<SINHVIEN> XemDSTheoMaLopMonHoc(string malopmonhoc);
public List<LOPMONHOC> LayDSLopMonHocTheoKi(int ki);
public List<RowAffected> SuaLopMonHoc(LOPMONHOC l);
public List<RowAffected> XoaLopMonHoc(string malopmonhoc);
public List<LOPMONHOC> TraGVLopMonHoc(string mgv, int ki);
public List<LOPMONHOC> TraSVLopMonHoc(int ki, string msv);
public List<CHUONGTRINHDAOTAO> LayDanhSachCTDT();
public List<RowAffected> ThemCTDT(CHUONGTRINHDAOTAO c);
public List<RowAffected> SuaCTDT(CHUONGTRINHDAOTAO c);
public List<RowAffected> XoaCTDT(string ma);
public List<CHUONGTRINHDAOTAO> TimCTDTTheoTen(string ten);
public List<LOPMONHOC> XemDSLopMonHocTheoKi(int ki);
public List<SINHVIEN> DiemMonLopChuyenNganh(string mamon, string mlcn);
public List<MONHOC> LayDSMHTienQuyet(string mamon);
public List<LOPMONHOC> DSLopMonHocDaDong();
public List<LOPMONHOC> DSLopMonHocDaHuy();
public ServiceResult HuyLop(string[] arr_ma);
public ServiceResult DongLop(string[] arr);
public List<RowAffected> DongAll();
public List<RowAffected> MoAll();
public List<LOPMONHOC> PhanTrangLopDaDong(int currPage, int recodperpage, int pagesize);
public List<GIANGVIEN> DSGV();
public List<RowAffected> ThemMoiLopMonHoc(LOPMONHOC l);
public ServiceResult MoLop(string[] arr);
public List<LOP> LayTTLop(string ml);
public List<LOPMONHOC> LayDSLHP_SV(string masv);
public List<TRANGTHAIACC> TrangThaiAcc();
public List<TRANGTHAIACC> DongMoTruyCap(string lenh);
}
}
|
using System.Threading.Tasks;
using Archimedes.Library.Message.Dto;
using Microsoft.AspNetCore.SignalR;
namespace Archimedes.Service.Ui.Hubs
{
public class PriceHub : Hub<IPriceHub>
{
public async Task Add(PriceDto value)
{
await Clients.All.Add(value);
}
public async Task Delete(PriceDto value)
{
await Clients.All.Delete(value);
}
public async Task Update(PriceDto value)
{
await Clients.All.Update(value);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DB_Test.Domain
{
public class Person
{
private string firstName;
private string lastName;
private string iD;
private string nID;
private DateTime birthDate;
private string phoneNumber;
private string address;
public Person(string firstName, string lastName, string iD, string nID, DateTime birthDate)
{
FirstName = firstName;
LastName = lastName;
ID = iD;
NID = nID;
BirthDate = birthDate;
}
public string FirstName { get => firstName; set => firstName = value; }
public string LastName { get => lastName; set => lastName = value; }
public string ID { get => iD; set => iD = value; }
public string NID { get => nID; set => nID = value; }
public DateTime BirthDate { get => birthDate; set => birthDate = value; }
public string PhoneNumber { get => phoneNumber; set => phoneNumber = value; }
public string Address { get => address; set => address = value; }
}
}
|
namespace Epsagon.Dotnet.Core.Configuration {
public interface IEpsagonConfiguration {
string Token { get; }
string AppName { get; }
bool MetadataOnly { get; }
bool UseSSL { get; }
string TraceCollectorURL { get; }
string OpenTracingCollectorURL { get; }
bool IsEpsagonDisabled { get; }
bool UseLogsTransport { get; }
int SendTimeout { get; }
string LogFile { get; }
string IgnoredKeys { get; }
}
}
|
namespace BankClassLib
{
class CheckingAccount : Account
{
public CheckingAccount(int accountNumber, string name)
{
this.AccountNumber = accountNumber;
this.Name = name;
this.AccountType = AccountType.CheckingAccount;
}
public override void CalculateInterest()
{
if (Balance > 0)
{
Balance *= 1.005;
}
}
}
}
|
using System.Data.Common;
using FastSQL.Sync.Core.Enums;
using FastSQL.Sync.Core.Models;
namespace FastSQL.Sync.Core.Repositories
{
public class ConnectionRepository : BaseGenericRepository<ConnectionModel>
{
public ConnectionRepository(DbConnection connection) : base(connection)
{
}
protected override EntityType EntityType => EntityType.Connection;
}
}
|
/*
* Copyright (c) 2022 Samsung Electronics Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Tizen.Applications;
using Alarms.Models;
namespace Alarms.Services
{
public static class AppListService
{
public static List<AppInfo> GetAppList()
{
List<AppInfo> appList = new List<AppInfo>();
IEnumerable<Package> packageList = PackageManager.GetPackages();
foreach (Package pkg in packageList)
{
var list = pkg.GetApplications();
foreach (var app in list)
{
if (!app.IsNoDisplay)
{
appList.Add(new AppInfo(app.Label, app.ApplicationId));
}
}
}
return appList;
}
}
} |
using System.Collections.Generic;
namespace Enrollment.Parameters.Expressions
{
abstract public class FilterMethodOperatorParametersBase : IExpressionParameter
{
public FilterMethodOperatorParametersBase()
{
}
public FilterMethodOperatorParametersBase(IExpressionParameter sourceOperand, IExpressionParameter filterBody = null, string filterParameterName = null)
{
SourceOperand = sourceOperand;
FilterBody = filterBody;
FilterParameterName = filterParameterName;
}
public IExpressionParameter SourceOperand { get; set; }
public IExpressionParameter FilterBody { get; set; }
public string FilterParameterName { get; set; }
}
} |
using System;
using System.ComponentModel.DataAnnotations;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Extensions;
using MyCompanyName.AbpZeroTemplate.Card;
#region 代码生成器相关信息_ABP Code Generator Info
//你好,我是ABP代码生成器的作者,欢迎您使用该工具,目前接受付费定制该工具,有需要的可以联系我
//我的邮箱:werltm@hotmail.com
// 官方网站:"http://www.yoyocms.com"
// 交流QQ群:104390185
//微信公众号:角落的白板报
// 演示地址:"vue版本:http://vue.yoyocms.com angularJs版本:ng1.yoyocms.com"
//博客地址:http://www.cnblogs.com/wer-ltm/
//代码生成器帮助文档:http://www.cnblogs.com/wer-ltm/p/5777190.html
// <Author-作者>梁桐铭 ,微软MVP</Author-作者>
// Copyright © YoYoCms@China.2019-07-30T19:53:10. All Rights Reserved.
//<生成时间>2019-07-30T19:53:10</生成时间>
#endregion
namespace MyCompanyName.AbpZeroTemplate.Card.Dtos
{
/// <summary>
/// 用于添加或编辑 订单明细表时使用的DTO
/// </summary>
public class GetOrderDetailForEditOutput
{
/// <summary>
/// OrderDetail编辑状态的DTO
/// </summary>
public OrderDetailEditDto OrderDetail{get;set;}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Project_Workflow_Engine
{
public class CallWebServide : IWorkFlow
{
public void Execute()
{
Console.WriteLine("Calling web service...");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Atendimento_V2
{
class Guiche
{
//atributos
private int id;
private Queue<Senha> atendimentos;
//Propriedades getter e setters
public void setId(int value)
{
this.id = value;
}
public void setSenha(Senha senha)
{
this.atendimentos.Enqueue(senha);
}
public int getId()
{
return this.id;
}
public Senha getSenha()
{
return this.atendimentos.Dequeue();
}
//Construtores
public Guiche(int id)
{
this.atendimentos = new Queue<Senha>();
setId(id);
}
public Guiche()
{
this.atendimentos = new Queue<Senha>();
setId(0);
}
//métodos funcionais
public void chamarSenha(Senha senha) //-- Adiciona uma nova senha aos atendimentos desse guiche
{
senha.setDtAtend();
senha.setHrAtend();
this.atendimentos.Enqueue(senha);
}
public List<String> dadosResumido()
{
List<String> senhas = new List<string>();
foreach (Senha s in this.atendimentos)
{
senhas.Add(s.dadosCompletos());
}
return senhas;
}
}
}
|
using Android.Content;
using Android.Widget;
using Android.Util;
using Ts.Core.Containers;
using Microsoft.Practices.ServiceLocation;
namespace Ts.Core.Popups
{
public class DialogContent : TextView, IDialogContent
{
private Context _context;
//private TextView _textContent;
private static BaseActivity _activity;
private static BaseActivity Activity
{
get
{
return _activity ?? (_activity = ServiceLocator.Current.GetInstance<BaseActivity>());
}
}
public string Content
{
get
{
return this.Text;
}
set
{
this.Text = value;
this.Visibility = string.IsNullOrEmpty(value) ? Android.Views.ViewStates.Gone : Android.Views.ViewStates.Visible;
}
}
public DialogIcon Icon { get; set; }
public DialogContent() :
base(Activity)
{
_context = Activity;
Initialize();
}
public DialogContent(Context context, IAttributeSet attrs) :
base(context, attrs)
{
_context = context;
Initialize();
}
public DialogContent(Context context, IAttributeSet attrs, int defStyle) :
base(context, attrs, defStyle)
{
_context = context;
Initialize();
}
private void Initialize()
{
//TextView _textContent = new TextView(_context);
//FrameLayout.LayoutParams contentParameter = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent);
//contentParameter.Gravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical;
//_textContent.LayoutParameters = contentParameter;
//this.AddView(_textContent);
this.SetTextSize(Resource.Dimension.dialog_text_size);
SetTextColor(new Android.Graphics.Color(190, 190, 190));
}
}
} |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
/// <summary>
/// A class that creates the end game screen and exits it.
/// </summary>
public class GameOver : MonoBehaviour {
/// <summary>
/// The text object in the Game Over scene.
/// </summary>
public GameObject textPanel;
/// <summary>
/// The AudioSource component in the Game Over scene.
/// </summary>
public AudioSource audioSource;
/// <summary>
/// The scene controller.
/// </summary>
public SceneTransitions sceneController;
/// <summary>
/// The story used in the game.
/// </summary>
private Story story;
/// <summary>
/// Provides an easy to use handler to fade the text.
/// </summary>
/// <param name="textObject">The text object to be faded.</param>
/// <param name="alpha">The target alpha value for the object.</param>
/// <param name="time">The amount of time over which the crossfade should elapse.</param>
private void fadeText(GameObject textObject, float alpha, float time){
textObject.GetComponent<Text>().CrossFadeAlpha(alpha,time,false);
}
/// <summary>
/// Runs the end game cutscene.
/// </summary>
/// <returns>While the Enumerator may return a value, I would not trust it to be usable.</returns>
/// <param name="story">The story of the game that just ended.</param>
IEnumerator endGameCutscene(Story story){
audioSource.Play (); //play scream
yield return new WaitForSeconds(1f); //wait 1 second after scream begins
textPanel.transform.GetChild(0).GetComponent<Text>().text = "On this day, "+ story.murderer.GetComponent<Character>().longName +" was arrested for the murder of "+ story.victim.GetComponent<Character>().longName +" at the Ron Cooke Hub.";
fadeText (textPanel.transform.GetChild (0).gameObject,1f, 2f);
yield return new WaitForSeconds(3f); //wait 1 second after last fade ends
textPanel.transform.GetChild(1).GetComponent<Text>().text = "The murder was carried out using a " + story.murderWeapon +".";
fadeText (textPanel.transform.GetChild (1).gameObject,1f, 2f);
yield return new WaitForSeconds(3f); //wait 1 second after last fade ends
textPanel.transform.GetChild(2).GetComponent<Text>().text = "During the interrogation, it was revealed that the murder had something to do with a " + story.motiveClue+".";
fadeText (textPanel.transform.GetChild (2).gameObject,1f, 2f);
yield return new WaitForSeconds(3f); //wait 1 second after last fade ends
textPanel.transform.GetChild(3).GetComponent<Text>().text = "Your work being done, you headed home to your force.";
fadeText (textPanel.transform.GetChild (3).gameObject,1f, 2f);
yield return new WaitForSeconds(3f); //wait 1 second after last fade ends
textPanel.transform.GetChild(4).GetComponent<Text>().text = "It needs you.";
fadeText (textPanel.transform.GetChild (4).gameObject,1f, 2f);
yield return new WaitForSeconds(3f); // wait three secs for fade, and one second after the fade ends
fadeOutAllText (0f,2f);
yield return new WaitForSeconds(3f); // wait three secs for fade, and one second after the fade ends
SceneManager.LoadScene (12); //load credits
}
/// <summary>
/// Simultaneously fades out all text boxes.
/// </summary>
private void fadeOutAllText(float alpha, float time){
fadeText (textPanel.transform.GetChild (0).gameObject, alpha, time);
fadeText (textPanel.transform.GetChild (1).gameObject, alpha, time);
fadeText (textPanel.transform.GetChild (2).gameObject, alpha, time);
fadeText (textPanel.transform.GetChild (3).gameObject, alpha, time);
fadeText (textPanel.transform.GetChild (4).gameObject, alpha, time);
}
// Use this for initialization
void Start () {
Story story = FindObjectOfType<Story> ();
fadeOutAllText (0f, 0f); //instantaneously fades out all text boxes
StartCoroutine (endGameCutscene(story));
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
public class RegularPolygon : Poligon
{
private int count;
public RegularPolygon(int count)
{
this.count = count;
}
public override void dragOnCreate(Point startPoint, Point secondPoint)
{
base.move(startPoint);
this.getVertexes().Clear();
this.getVertexes().Add(secondPoint);
}
public override void draw(Graphics formGraphics)
{
Point topPoint = this.getVertexes().ToArray()[0];
this.getVertexes().Clear();
float radius = (float)Math.Sqrt((this.getCenter().X - topPoint.X) * (this.getCenter().X - topPoint.X)
+ (this.getCenter().Y - topPoint.Y) * (this.getCenter().Y - topPoint.Y));
float startAngle = XYToDegrees(topPoint, this.getCenter());
float step = 360.0f / count;
float angle = startAngle; //starting angle
for (double i = startAngle; i < startAngle + 360.0; i += step) //go in a full circle
{
this.getVertexes().Add(DegreesToXY(angle, radius, this.getCenter())); //code snippet from above
angle += step;
}
base.draw(formGraphics);
}
private Point DegreesToXY(float degrees, float radius, Point origin)
{
Point xy = new Point();
double radians = degrees * Math.PI / 180.0;
xy.X = (int)(Math.Cos(radians) * radius + origin.X);
xy.Y = (int)(Math.Sin(-radians) * radius + origin.Y);
return xy;
}
private float XYToDegrees(Point xy, Point origin)
{
int deltaX = origin.X - xy.X;
int deltaY = origin.Y - xy.Y;
double radAngle = Math.Atan2(deltaY, deltaX);
double degreeAngle = radAngle * 180.0 / Math.PI;
return (float)(180.0 - degreeAngle);
}
public int getCount()
{
return 0;
}
public override List<Point> Location()
{
return base.Location();
}
///
/// <param name="newVal"></param>
public void setCount(int newVal)
{
}
}//end RegularPolygon |
namespace Contoso.Parameters.Expressions
{
public class OrBinaryOperatorParameters : BinaryOperatorParameters
{
public OrBinaryOperatorParameters()
{
}
public OrBinaryOperatorParameters(IExpressionParameter left, IExpressionParameter right) : base(left, right)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Quartz.Spi;
using Quartz;
using Ninject.Activation;
namespace MvcApplicationWithNinjectAndQuartz.App_Quartz
{
public class QuartzSchedulerProvider : Provider<IScheduler>
{
private readonly IJobFactory jobFactory;
private readonly IEnumerable<ISchedulerListener> listeners;
private readonly ISchedulerFactory schedulerFactory;
public QuartzSchedulerProvider(
ISchedulerFactory schedulerFactory,
IJobFactory jobFactory,
IEnumerable<ISchedulerListener> listeners)
{
this.jobFactory = jobFactory;
this.listeners = listeners;
this.schedulerFactory = schedulerFactory;
}
protected override IScheduler CreateInstance(IContext context)
{
var scheduler = this.schedulerFactory.GetScheduler();
scheduler.JobFactory = this.jobFactory;
foreach (var listener in this.listeners)
{
scheduler.AddSchedulerListener(listener);
}
return scheduler;
}
}
} |
using DG.Tweening;
using PurificationPioneer.Global;
using PurificationPioneer.Network.Proxy;
using UnityEngine;
using UnityEngine.UI;
namespace PurificationPioneer.Script
{
public class HeroChooseTimerUi : MonoBehaviour
{
public RectTransform timerObj;
public Text timerText;
public Button submitBtn;
private void Start()
{
SetTime(GlobalVar.SelectHeroTime);
}
public void SubmitHeroReq()
{
if (GlobalVar.IsLocalSubmit)
{
Debug.LogError("重复锁定");
return;
}
LogicProxy.Instance.SubmitHero(GlobalVar.Uname);
}
public void SetTime(int time)
{
timerText.text = time.ToString();
}
public void OnSubmit(float time, Ease easeType)
{
this.submitBtn.gameObject.SetActive(false);
this.timerObj.DOMove(this.submitBtn.transform.position, time).SetEase(easeType);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace OCP.BackgroundJob
{
public interface IJob : Quartz.IJob
{
/**
* Run the background job with the registered argument
*
* @param \OCP\BackgroundJob\IJobList jobList The job list that manages the state of this job
* @param ILogger|null logger
* @since 7.0.0
*/
void execute(IJobList jobList, ILogger logger = null);
/**
* @param int id
* @since 7.0.0
*/
void setId(int id);
/**
* @param int lastRun
* @since 7.0.0
*/
void setLastRun(int lastRun);
/**
* @param mixed argument
* @since 7.0.0
*/
void setArgument(object argument);
/**
* Get the id of the background job
* This id is determined by the job list when a job is added to the list
*
* @return int
* @since 7.0.0
*/
int getId();
/**
* Get the last time this job was run as unix timestamp
*
* @return int
* @since 7.0.0
*/
int getLastRun();
/**
* Get the argument associated with the background job
* This is the argument that will be passed to the background job
*
* @return mixed
* @since 7.0.0
*/
object getArgument();
}
}
|
using System;
using System.Windows.Forms;
using Ego.PDF.Data;
using Ego.PDF.Samples;
namespace Ego.PDF.WindowsFormsTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void DoSample1()
{
var pdf = Sample1.GetSample( );
pdf.Output("sample1.pdf", OutputDevice.SaveToFile);
}
public void DoSample2()
{
{
var pdf = Sample2.GetSample("logo.png");
pdf.Output("sample2.a.pdf", OutputDevice.SaveToFile);
}
{
// var pdf = Sample2.GetSample("gift.jpg");
// pdf.Output("sample2.b.pdf", OutputDevice.SaveToFile);
}
}
public void DoSample3()
{
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var pdf = Sample3.GetSample(path);
pdf.Output("sample3.pdf", OutputDevice.SaveToFile);
}
public void DoSample4()
{
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var pdf = Sample4.GetSample(path);
pdf.Output("sample4.pdf", OutputDevice.SaveToFile);
}
public void DoSample5()
{
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var pdf = Sample5.GetSample(path);
pdf.Output("sample5.pdf", OutputDevice.SaveToFile);
}
public void DoSample6()
{
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var pdf = Sample6.GetSample(path);
pdf.Output("sample6.pdf", OutputDevice.SaveToFile);
}
private void BtnRunSamples_Click(object sender, EventArgs e)
{
DoSample1();
DoSample2();
DoSample3();
DoSample4();
DoSample5();
DoSample6();
}
}
}
|
using System;
using System.Data;
using System.Text;
using System.Data.OracleClient;
using Maticsoft.DBUtility;//Please add references
namespace PDTech.OA.DAL
{
/// <summary>
/// 数据访问类:ARCHIVE_PROJECT_MAP
/// </summary>
public partial class ARCHIVE_PROJECT_MAP
{
public ARCHIVE_PROJECT_MAP()
{}
#region BasicMethod
/// <summary>
/// 获取Anchive和Project关联
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public Model.ARCHIVE_PROJECT_MAP get_mapInfo(Model.ARCHIVE_PROJECT_MAP where)
{
string condition = DAL_Helper.GetWhereCondition(where);
string selSQL = string.Format(@"SELECT * FROM ARCHIVE_PROJECT_MAP WHERE 1=1 {0}",condition);
DataTable dt = DbHelperSQL.Query(selSQL).Tables[0];
if (dt.Rows.Count > 0)
{
return DAL_Helper.CommonFillList<Model.ARCHIVE_PROJECT_MAP>(dt)[0];
}
else
{
return null;
}
}
#endregion BasicMethod
#region ExtensionMethod
#endregion ExtensionMethod
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EatDrinkApplication.Models
{
public class Foods
{
public int FoodsId { get; set; }
public Recipe[] Property1 { get; set; }
}
public class Recipe
{
public int RecipeId { get; set; }
public int id { get; set; }
public string title { get; set; }
public string image { get; set; }
public string imageType { get; set; }
public int usedIngredientCount { get; set; }
public int missedIngredientCount { get; set; }
public Missedingredient[] missedIngredients { get; set; }
public Usedingredient[] usedIngredients { get; set; }
public Unusedingredient[] unusedIngredients { get; set; }
public int likes { get; set; }
}
public class Missedingredient
{
public int MissedingredientId { get; set; }
public int id { get; set; }
public float amount { get; set; }
public string unit { get; set; }
public string unitLong { get; set; }
public string unitShort { get; set; }
public string aisle { get; set; }
public string name { get; set; }
public string original { get; set; }
public string originalString { get; set; }
public string originalName { get; set; }
public string image { get; set; }
}
public class Usedingredient
{
public int UsedingredientId { get; set; }
public int id { get; set; }
public float amount { get; set; }
public string unit { get; set; }
public string unitLong { get; set; }
public string unitShort { get; set; }
public string aisle { get; set; }
public string name { get; set; }
public string original { get; set; }
public string originalString { get; set; }
public string originalName { get; set; }
public string image { get; set; }
}
public class Unusedingredient
{
public int UnusedingredientId { get; set; }
public int id { get; set; }
public float amount { get; set; }
public string unit { get; set; }
public string unitLong { get; set; }
public string unitShort { get; set; }
public string aisle { get; set; }
public string name { get; set; }
public string original { get; set; }
public string originalString { get; set; }
public string originalName { get; set; }
public string image { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.UI.Popups;
using Stock_Management.Model;
using Stock_Management.Viewmodel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Stock_Management.View;
namespace Stock_Management.Handler
{
class ProductHandler : IProductHandler
{
public ProductViewModel ProductViewModel { get; set; }
public ProductHandler(ProductViewModel productViewModel)
{
ProductViewModel = productViewModel;
}
public void CreateProduct()
{
ProductViewModel.Product.Price = Convert.ToDecimal(ProductViewModel.StringPrice);
ProductViewModel.Product.RestockPeriod = ProductViewModel.Date.Date;
if (ProductViewModel.SelectedSupplier != null)
{
// IF a selected supplier exists, that means the supplier was selected from the dropdown
// pass the selectedSupplier to the Product obj
ProductViewModel.Product.Supplier = ProductViewModel.SelectedSupplier;
}
else
{
// ELSE the selected supplier was typed in, meaning it might be a new supplier to be created
// or the supplier should be searched if it already exists, and then should be updated
// this supplier is missing an ID
ProductViewModel.Product.Supplier = ProductViewModel.Supplier;
}
try
{
ProductViewModel.ProductCatalogSingleton.CreateProduct(ProductViewModel.Product);
var frame = (Frame)Window.Current.Content;
frame.Navigate(typeof(MainPage));
}
catch (Exception e)
{
new MessageDialog(e.Message).ShowAsync();
}
}
public void UpdateProduct()
{
// Convert the SelectedProductStringPrice to a real decimal, and set the product.price
ProductViewModel.SelectedProduct.Price = Convert.ToDecimal(ProductViewModel.SelectedProductStringPrice);
// Set the Product.RestockPeriod (DateTime) to SelectedProductDate (DateTimeOffset) for put'ing to DB
ProductViewModel.SelectedProduct.RestockPeriod = ProductViewModel.SelectedProductDate.Date;
try
{
ProductViewModel.ProductCatalogSingleton.UpdateProduct(ProductViewModel.SelectedProduct);
var frame = (Frame)Window.Current.Content;
frame.Navigate(typeof(ProductView));
}
catch (Exception e)
{
new MessageDialog(e.Message).ShowAsync();
}
}
public void DeleteProduct()
{
try
{
ProductViewModel.ProductCatalogSingleton.DeleteProduct(ProductViewModel.SelectedProduct);
var frame = (Frame)Window.Current.Content;
frame.Navigate(typeof(MainPage));
}
catch (Exception e)
{
new MessageDialog(e.Message).ShowAsync();
}
}
public void ManualOrder()
{
// TEST
// TODO Make Product to order dynamic. Currently creates an order for the latest product in the list
//ObservableCollection<Product> productList = ProductViewModel.ProductCatalogSingleton.ProductList;
Product p = ProductViewModel.SelectedProduct;
int amount = ProductViewModel.OrderAmount;
try
{
ProductViewModel.ProductCatalogSingleton.OrderProduct(p, amount);
var frame = (Frame)Window.Current.Content;
frame.Navigate(typeof(ProductOrderView));
}
catch (Exception e)
{
new MessageDialog(e.Message).ShowAsync();
}
}
public void ReturnProduct()
{
try
{
ProductViewModel.ProductReturn.ProductId = ProductViewModel.SelectedProduct.Id;
ProductViewModel.ProductReturn.Date = DateTime.Now;
ProductViewModel.ProductCatalogSingleton.CreateProductReturn(ProductViewModel.SelectedProduct, ProductViewModel.ProductReturn);
}
catch (ArgumentException e)
{
new MessageDialog(e.Message).ShowAsync();
}
}
public void ApproveOrder()
{
try
{
ProductViewModel.ProductCatalogSingleton.ApproveOrder(ProductViewModel.SelectedProduct);
var frame = (Frame)Window.Current.Content;
frame.Navigate(typeof(ProductOrderView));
}
catch (Exception e)
{
new MessageDialog("Kunne ikke godkende ordre. Mangler muligvis ordre at godkende.").ShowAsync();
}
}
public void SetSelectedProduct(Product p)
{
ProductViewModel.SelectedProduct = p;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
[System.Serializable]
public class EndCutscene {
[TextArea(3, 10)]
public string sentence;
}
public class End : MonoBehaviour {
//cutscenes
public EndCutscene[] cutscenes;
public TextMeshProUGUI text;
private Queue<string> sentences;
public float waitTime;
public GameObject canvas;
public GameObject endCanvas;
public GameObject codebreakerCanvasGroup;
public GameObject endCanvasGroup;
private Fading fade;
private bool playEnd = true;
public string menu;
void Start()
{
sentences = new Queue<string>();
StartCoroutine(Begin());
fade = FindObjectOfType<Fading>();
}
void Update()
{
if((endCanvas.activeSelf) && (playEnd))
{
StartCoroutine(PlayEnd());
}
}
IEnumerator PlayEnd()
{
playEnd = false;
while(codebreakerCanvasGroup.GetComponent<CanvasGroup>().alpha != 1)
{
codebreakerCanvasGroup.GetComponent<CanvasGroup>().alpha += 1 * Time.deltaTime;
yield return new WaitForSeconds(0.001f);
}
while(endCanvasGroup.GetComponent<CanvasGroup>().alpha != 1)
{
endCanvasGroup.GetComponent<CanvasGroup>().alpha += 1 * Time.deltaTime;
yield return new WaitForSeconds(0.001f);
}
yield return new WaitForSeconds(1);
fade.BeginFade(1);
yield return new WaitForSeconds(1);
PlayerPrefs.SetInt("scene07", 1);
SceneManager.LoadScene(menu);
}
IEnumerator Begin()
{
yield return new WaitForSeconds(waitTime);
canvas.SetActive(true);
StartDialogue();
}
public void StartDialogue() //(Dialogue dialogue)
{
sentences.Clear();
for (int i = 0; i < cutscenes.Length; i++)
{
sentences.Enqueue(cutscenes[i].sentence);
}
DisplayNextSentence();
}
public void DisplayNextSentence()
{
if(sentences.Count == 0)
{
EndDialogue();
return;
}
string sentence = sentences.Dequeue();
StopAllCoroutines();
StartCoroutine(TypeSentence(sentence));
}
IEnumerator TypeSentence (string sentence)
{
text.text = "";
foreach(char letter in sentence.ToCharArray())
{
text.text += letter;
yield return null;
}
}
void EndDialogue()
{
canvas.SetActive(false);
endCanvas.SetActive(true);
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using CRVCManager.DataModels;
using CRVCManager.Utilities;
namespace CRVCManager
{
/// <summary>
/// Interaction logic for SaleWindow.xaml
/// </summary>
public partial class SaleWindow : Window
{
private readonly User _currentUser;
private Client _currentClient;
private Consult _currentConsult;
private Sale _currentSale;
private bool _isCounterSale;
private bool _isEdit;
private SaleItem _selectedItem;
public List<SaleItem> SaleItems = new List<SaleItem>();
// Main
public SaleWindow(User currentUser, Sale currentSale = null, Client currentClient = null, Consult currentConsult = null)
{
_currentUser = currentUser;
InitializeComponent();
SetupUi(currentSale, currentClient, currentConsult);
}
// Counter Sale
public SaleWindow(User currentUser, Client currentClient) : this(currentUser, null, currentClient)
{
}
// Consult Sale
public SaleWindow(User currentUser, Consult currentConsult) : this(currentUser, null, null, currentConsult)
{
}
private void SetupUi(Sale currentSale, Client currentClient, Consult currentConsult)
{
if (currentSale == null)
{
_isEdit = false;
GenerateInvoiceButton.IsEnabled = false;
DeleteButton.Content = "Cancel";
DeleteButton.Click += DeleteButton_Cancel_Click;
CloseButton.Visibility = Visibility.Collapsed;
if (currentClient != null && currentConsult == null)
{
_isCounterSale = true;
_currentClient = currentClient;
Title = "New Counter Sale";
WindowTitleLabel.Content = "New Counter Sale";
}
else if (currentClient == null && currentConsult != null)
{
_isCounterSale = false;
_currentClient = currentConsult.Client;
_currentConsult = currentConsult;
Title = "New Consult Sale";
WindowTitleLabel.Content = "New Sale";
}
else
{
throw new ArgumentException($"{nameof(currentClient)} or {nameof(currentConsult)} were in the wrong format");
}
}
else
{
_isEdit = true;
GenerateInvoiceButton.IsEnabled = true;
Title = "Edit Sale";
WindowTitleLabel.Content = "Edit Sale";
DeleteButton.Content = "Delete";
DeleteButton.Click += DeleteButton_Click;
CloseButton.Visibility = Visibility.Visible;
_currentSale = currentSale;
}
PopulateData();
}
private void PopulateData()
{
PaymentMethodComboBox.PopEnumComboBoxItems<PaymentMethod>();
PaymentStatusComboBox.PopEnumComboBoxItems<PaymentStatus>();
if (_isEdit)
{
if (_currentSale.IsCounterSale)
{
ClientTextBox.Text = _currentSale.Client.GetFullName();
ClientFlagIcon.Fill = (SolidColorBrush)new BrushConverter().ConvertFrom(_currentSale.Consult.Client.Flag.Color.ConvertColorToString());
}
else
{
ClientTextBox.Text = _currentSale.Consult.Client.GetFullName();
ClientFlagIcon.Fill = (SolidColorBrush)new BrushConverter().ConvertFrom(_currentSale.Consult.Client.Flag.Color.ConvertColorToString());
}
CreationDateTextBox.Text = _currentSale.CreationDate.GetString("D");
PaymentDatePicker.SelectedDate = _currentSale.PaymentDate;
PaymentMethodComboBox.SelectEnumComboBoxMember<PaymentMethod>(_currentSale.PaymentMethod);
PaymentStatusComboBox.SelectEnumComboBoxMember<PaymentStatus>(_currentSale.PaymentStatus);
SaleItems = _currentSale.Items;
}
else
{
PaymentMethodComboBox.SelectedIndex = 1;
PaymentStatusComboBox.SelectedIndex = 1;
CreationDateTextBox.Text = DateTime.Today.ToString("D");
if (_isCounterSale)
{
ClientTextBox.Text = _currentClient.GetFullName();
ClientFlagIcon.Fill = (SolidColorBrush) new BrushConverter().ConvertFrom(_currentClient.Flag.Color.ConvertColorToString());
}
else
{
ClientTextBox.Text = _currentConsult.Client.GetFullName();
ClientFlagIcon.Fill = (SolidColorBrush) new BrushConverter().ConvertFrom(_currentConsult.Client.Flag.Color.ConvertColorToString());
}
}
ValidateFields();
}
private void ValidateFields()
{
if (PaymentMethodComboBox.SelectedIndex == -1 || SaleItems.Count == 0)
{
SaveButton.IsEnabled = false;
RecieveButton.IsEnabled = false;
GenerateInvoiceButton.IsEnabled = false;
}
else
{
SaveButton.IsEnabled = true;
RecieveButton.IsEnabled = true;
GenerateInvoiceButton.IsEnabled = true;
}
if (SaleItems.Count == 0)
{
SaleItemsLabel.HighlightInvalid();
RemoveItemButton.IsEnabled = false;
}
else
{
SaleItemsLabel.HighlightNormal();
RemoveItemButton.IsEnabled = true;
}
}
private void RefreshItemsDataGrid()
{
var d = new DataTable();
d.Columns.Add("ID");
d.Columns.Add("Item");
d.Columns.Add("Tot. Unit Price");
d.Columns.Add("Quantity");
d.Columns.Add("Sub Total");
foreach (var i in SaleItems)
{
var t = i.Item.TotalPrice.DoubleToCurrency();
d.Rows.Add(i.Id, i.Item.Name, t, i.Quantity, i.ItemTotal.DoubleToCurrency());
}
ItemsDataGrid.DataContext = d;
ItemsDataGrid.SelectedIndex = -1;
// ItemsDataGrid.HideColumn();
ValidateFields();
}
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
if (_currentSale != null && _currentSale.Exists)
{
_currentSale.Delete();
if (_currentSale.Exists == false)
{
Logging.Info($"Sale was successfully deleted");
Logging.Debug($"Sale with ID {_currentSale.Id} was deleted by user with ID {_currentUser.Id}");
Close();
}
else
{
Logging.Error(new Exception("An error occured while trying to delete the sale."));
Close();
}
}
}
private void DeleteButton_Cancel_Click(object sender, RoutedEventArgs routedEventArgs)
{
this.ConfirmClose($"Are you sure you want to cancel? You will lose any unsved changes.");
}
private void SaveButton_OnClick(object sender, RoutedEventArgs e)
{
SaveData();
}
private void SaveData()
{
if (_isEdit)
{
_currentSale.Items = SaleItems;
_currentSale.Discount = DiscountTextBox.Text.ToInt();
_currentSale.PaymentMethod = PaymentMethodComboBox.SelectedItem.ToString().ParseEnum<PaymentMethod>();
_currentSale.PaymentStatus = PaymentStatusComboBox.SelectedItem.ToString().ParseEnum<PaymentStatus>();
_currentSale.PaymentDate = PaymentDatePicker.SelectedDate;
_currentSale.Notes = NotesTextBox.Text;
Logging.Info("Sale was successfully updated");
Logging.Debug($"Sale with ID {_currentSale.Id} was updated by user with ID {_currentUser.Id}");
SetupUi(_currentSale, null, null);
}
else
{
var sale = new Sale();
if (sale.Exists)
{
if (_isCounterSale)
{
sale.Client = _currentClient;
}
else
{
sale.Consult = _currentConsult;
}
sale.CreationDate = DateTime.Now;
sale.CreatingUser = _currentUser;
sale.Items = SaleItems;
sale.Discount = DiscountTextBox.Text.ToInt();
sale.PaymentMethod = PaymentMethodComboBox.SelectedItem.ToString().ParseEnum<PaymentMethod>();
sale.PaymentStatus = PaymentStatusComboBox.SelectedItem.ToString().ParseEnum<PaymentStatus>();
sale.PaymentDate = PaymentDatePicker.SelectedDate;
sale.Notes = NotesTextBox.Text;
Logging.Info("Sale created successfully");
Logging.Debug($"Sale with ID {sale.Id} was created by user with ID {_currentUser.Id}");
SetupUi(sale, null, null);
}
else
{
Logging.Error(new Exception("An error occured while creating a sale. Your changes may not have been saved"));
Close();
}
}
}
private void CloseButton_OnClick(object sender, RoutedEventArgs e)
{
Close();
}
private void PaymentDatePicker_OnSelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
ValidateFields();
}
private void AddItemButton_OnClick(object sender, RoutedEventArgs e)
{
var a = new AddItemWindow(_currentUser)
{
SaleWindowRef = this
};
var d = a.ShowDarkenedDialog(this);
RefreshItemsDataGrid();
}
private void RemoveItemButton_OnClick(object sender, RoutedEventArgs e)
{
SaleItems.RemoveAt(ItemsDataGrid.SelectedIndex);
RefreshItemsDataGrid();
}
private void ClearAllItemsButton_OnClick(object sender, RoutedEventArgs e)
{
SaleItems.Clear();
RefreshItemsDataGrid();
}
private void GenerateInvoiceButton_OnClick(object sender, RoutedEventArgs e)
{
if (this.ConfirmAction("Are you sure you want to generate an invoice? Changes must be saved before they appear on an invoice.") && _isEdit)
{
SaveData();
var w = new InvoiceStatusWindow(ref _currentSale);
var result = w.ShowDarkenedDialog(this);
if (result != null && (bool) result && _currentSale.InvoiceDocument != null)
{
Logging.Info("Invoice successfully generated");
Logging.Debug($"Invoice with ID {_currentSale.InvoiceDocument.Id} was created by user with ID {_currentUser.Id}");
// TODO implement document viewer w/printing
}
else
{
Logging.Error(new Exception("An error occured while generating an invoice."));
}
}
}
private void RecieveButton_OnClick(object sender, RoutedEventArgs e)
{
var w = new RecievePaymentWindow(ref _currentSale);
var result = w.ShowDialog();
if (result == null || result == true)
{
_currentSale.PaymentDate = DateTime.Now;
_currentSale.PaymentStatus = PaymentStatus.Paid;
SetupUi(_currentSale, null, null);
}
}
private void ItemsDataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
e.HideIdColumn();
}
private void ItemsDataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
SaleItem selectedItem = null;
if (ItemsDataGrid.SelectedIndex != -1)
{
if (ItemsDataGrid.SelectedItem is DataRowView saleItemRowView)
{
var saleItemFromDataGrid = new SaleItem(saleItemRowView.Row.ItemArray[0].ToString().ParseGuid());
if (saleItemFromDataGrid.Exists)
{
selectedItem = saleItemFromDataGrid;
RemoveItemButton.IsEnabled = true;
}
}
RemoveItemButton.IsEnabled = true;
}
_selectedItem = selectedItem;
ValidateFields();
}
private void PaymentMethodComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ValidateFields();
}
private void PaymentStatusComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ValidateFields();
}
private void DiscountTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ValidateFields();
}
}
} |
using JIoffe.PizzaBot.Model;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.AI.Luis;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using PizzaBot.Accessors;
using PizzaBot.States;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace PizzaBot.Dialogs
{
//The methods in this class might seem a little repetetive; this is
//to really make clear the basic flows available in Bot.Builder.Dialogs
/// <summary>
/// Handles all the steps related to taking a pizza order as WaterfallSteps
/// </summary>
public class PizzaOrderDialogFactory : IDialogFactory
{
private readonly PizzaOrderAccessors _accessors;
private readonly LuisRecognizer _luisRecognizer;
public PizzaOrderDialogFactory(PizzaOrderAccessors accessors, LuisRecognizer luisRecognizer)
{
_accessors = accessors;
_luisRecognizer = luisRecognizer;
}
public Dialog Build()
{
//Step 12) Create a new waterfall dialog covering the full range of
//steps to order a pizza: GetAddress, ConfirmAddress, BeginOrder, GetSize, GetToppings,
//ConfirmOrder and finally CompleteOrder
var steps = new WaterfallStep[]
{
GetAddressAsync,
ConfirmAddressAsync,
BeginOrderAsync,
GetSizeAsync,
GetToppingsAsync,
ConfirmOrderAsync,
CompleteOrderAsync
};
var dialog = new WaterfallDialog(DialogNames.PIZZA_ORDER, steps);
return dialog;
}
private async Task<DialogTurnResult> GetAddressAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
//Step 13) Pull the PizzaOrderState from our accessors.
var turnContext = stepContext.Context;
var state = await _accessors.PizzaOrderState.GetAsync(turnContext, () => new States.PizzaOrderState());
//Step 14) If we already have a preferred address, then skip to the next step!
if (!string.IsNullOrWhiteSpace(state.PreferredAddress))
{
return await stepContext.NextAsync(state.PreferredAddress, cancellationToken);
}
//Step 15) Otherwise, prompt the user to enter an address. This will be passed to the next step of the waterfall.
var promptOptions = new PromptOptions
{
Prompt = MessageFactory.Text(Responses.Orders.AddressPrompt)
};
return await stepContext.PromptAsync(DialogNames.ADDRESS_PROMPT, promptOptions, cancellationToken);
}
private async Task<DialogTurnResult> ConfirmAddressAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
//Step 16) Retrieve the address from the current step context result
var address = stepContext.Result as string;
address = address.Trim();
var turnContext = stepContext.Context;
var state = await _accessors.PizzaOrderState.GetAsync(turnContext, () => new States.PizzaOrderState());
state.PreferredAddress = address;
await _accessors.ConversationState.SaveChangesAsync(turnContext);
//Step 17) Prompt the user to confirm that this is the correct address to use
var promptOptions = new PromptOptions
{
Prompt = MessageFactory.Text(string.Format(Responses.Orders.AddressConfirm, address))
};
return await stepContext.PromptAsync(DialogNames.ADDRESS_CONFIRM, promptOptions, cancellationToken);
}
private async Task<DialogTurnResult> BeginOrderAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
//The choice prompt will provide us with a boolean.
var correctAddress = (bool)stepContext.Result;
var turnContext = stepContext.Context;
//Step 18) If this is not the correct address, we will start over!
// Get the order state from the accessors again, and this time set the address to empty.
// Save all changes and use ReplaceDialog to restart this dialog.
if (!correctAddress)
{
//Clear the address
var state = await _accessors.PizzaOrderState.GetAsync(turnContext, () => new States.PizzaOrderState());
state.PreferredAddress = string.Empty;
await _accessors.ConversationState.SaveChangesAsync(turnContext);
//ReplaceDialogAsync can be used to restart a dialog
return await stepContext.ReplaceDialogAsync(DialogNames.PIZZA_ORDER, null, cancellationToken);
}
return await stepContext.NextAsync();
}
private async Task<DialogTurnResult> GetSizeAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
//Step 19) Check if the current order already has a size (it is not set to 0).
//If so, move to the next step with the size. Otherwise, prompt for the size.
var turnContext = stepContext.Context;
var state = await _accessors.PizzaOrderState.GetAsync(turnContext, () => new States.PizzaOrderState());
if (state.CurrentOrder.Size != 0)
{
return await stepContext.NextAsync(state.CurrentOrder.Size);
}
var promptOptions = new PromptOptions
{
Prompt = MessageFactory.Text(Responses.Orders.SizePrompt)
};
return await stepContext.PromptAsync(DialogNames.SIZE_PROMPT, promptOptions, cancellationToken);
}
private async Task<DialogTurnResult> GetToppingsAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
//Step 20) Check if the current order already has a toppings (it is not set to 0).
// If so, move to the next step with topping selection. Otherwise, prompt for the toppings.
var turnContext = stepContext.Context;
var state = await _accessors.PizzaOrderState.GetAsync(turnContext, () => new States.PizzaOrderState());
state.CurrentOrder.Size = (PizzaSize)stepContext.Result;
await _accessors.ConversationState.SaveChangesAsync(turnContext);
if(state.CurrentOrder.Toppings?.Count > 0)
{
return await stepContext.NextAsync(state.CurrentOrder.Toppings);
}
var promptOptions = new PromptOptions
{
Prompt = MessageFactory.Text(Responses.Orders.ToppingsPrompt)
};
return await stepContext.PromptAsync(DialogNames.TOPPINGS_PROMPT, promptOptions, cancellationToken);
}
private async Task<DialogTurnResult> ConfirmOrderAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
//This is similar to the earlier entries, so it will be provided for you.
var turnContext = stepContext.Context;
var state = await _accessors.PizzaOrderState.GetAsync(turnContext, () => new States.PizzaOrderState());
state.CurrentOrder.Toppings = (ISet<PizzaTopping>)stepContext.Result;
await _accessors.ConversationState.SaveChangesAsync(turnContext);
//Bot Framework gives us a number of pre-built cards that can be interpreted
//by several platforms. In this method, let us implement a basic ReceiptCard.
await SendReceiptAsync(turnContext, state);
var promptOptions = new PromptOptions
{
Prompt = MessageFactory.Text(Responses.Orders.ConfirmOrder)
};
return await stepContext.PromptAsync(DialogNames.CONFIRM_ORDER, promptOptions, cancellationToken);
}
private async Task<DialogTurnResult> CompleteOrderAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
var turnContext = stepContext.Context;
var state = await _accessors.PizzaOrderState.GetAsync(turnContext, () => new States.PizzaOrderState());
//Step 22 - Cast the result to (bool) to see if the user clicked yes or no. Respond accordingly.
var orderConfirmed = (bool)stepContext.Result;
if (orderConfirmed)
{
var response = string.Format(Responses.Orders.CompletedOrder, state.CurrentOrder.Toppings.First());
await turnContext.SendActivityAsync(response);
}
else
{
await turnContext.SendActivityAsync(Responses.Orders.CancelledOrder);
}
//Step 23 - End the dialog. This will bring us back to the previous point on the stack.
return await stepContext.EndDialogAsync();
}
private async Task SendReceiptAsync(ITurnContext context, PizzaOrderState state)
{
var items = GetReceiptItems(state.CurrentOrder);
var total = items.Sum(item => double.Parse(item.Price));
//Step 21 - Create and send a new ReceiptCard detailing the customer's order.
var msg = context.Activity.CreateReply();
msg.Attachments = new[]
{
new ReceiptCard()
{
Title = $"Pizza Order - {state.PreferredAddress}",
Facts = new[]
{
new Fact(){Key = "Address", Value = state.PreferredAddress}
},
Total = $"${total.ToString("N2")}",
Items = items
}.ToAttachment()
};
await context.SendActivityAsync(msg);
}
private IList<ReceiptItem> GetReceiptItems(PizzaOrder order)
{
//Extremely simple for the sake of this example
var sizePrices = new[] { 10D, 15D, 20D };
var toppingPrices = new[] { 2D, 1.5D, 2.5D, 3D, 1D, 1.5D, 2D, 3D };
var items = new List<ReceiptItem>();
items.Add(new ReceiptItem(title: $"{order.Size} pie", price: sizePrices[(int)order.Size - 1].ToString("N2")));
items.AddRange(order.Toppings.Select(t => new ReceiptItem(title: $"+{t}", price: toppingPrices[(int)t- 1].ToString("N2"))));
return items;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Assets.Scripts.Managers;
using Assets.Scripts.Interfaces;
using UnityEngine.UI;
namespace Assets.Scripts
{
public class Bootstrapper : MonoBehaviour
{
IUpdateManager _updateManager;
IControlManager _controlManager;
IPlatformManager _platformManager;
IObjectStorage _objectStorage;
UIManager _UIManager;
void Start()
{
var updateManagerObject = new GameObject("UpdateManager");
_updateManager = updateManagerObject.AddComponent<UpdateManager>();
_objectStorage = new ObjectStorage(Constants.platformCount);
_objectStorage.Initialization(Constants.playerPrefabName, Constants.platformPrefabName);
_controlManager = new ControlManager(_updateManager, _objectStorage);
_platformManager = new PlatformManager(_updateManager, _objectStorage);
_UIManager = new UIManager(_updateManager, _controlManager, _platformManager, _objectStorage);
_UIManager.ShowMainMenu();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CheckMySymptoms.Forms.Parameters.Common
{
public enum DetailItemEnum
{
Field,
Group,
List
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace DependencyInjectionContainer.Container
{
public class DiContainer
{
private readonly Dictionary<Type, Type> _types = new Dictionary<Type, Type>();
public void Register<TInterface, TClass>()
{
if (_types.ContainsKey(typeof(TInterface)))
{
throw new Exception("Interface type already registered");
}
_types.Add(typeof(TInterface), typeof(TClass));
}
public TInterface Resolve<TInterface>()
{
// Resolve returns the implementation
// Someone else deals with the embedded dependencies
// It receives and object which it casts into the type ie. interface and returns it
return (TInterface)GetImplementation(typeof(TInterface));
}
// Take the actual type as the input to help with recursive function calls
private object GetImplementation(Type interfaceType)
{
// Check if the key exists in the dictionary
if (!_types.ContainsKey(interfaceType))
{
throw new Exception("Interface type does not exist");
}
// Get the value from the dictionary
_types.TryGetValue(interfaceType, out Type implementation);
// Identify the dependencies of this class by getting the constructor information
ConstructorInfo constructorInfo = implementation.GetConstructors()[0];
var constructorParams = constructorInfo.GetParameters();
// List of implementations needed to call the constructor
List<object> constructorParamImplementations = new List<object>();
// For the constructor
// Get the list of all classes it depends on
foreach (var param in constructorParams)
{
// Get the dependent implementations recursively
constructorParamImplementations.Add(GetImplementation(param.ParameterType));
}
// Call or invoke the constructor with its parameters
// This is the 0th constructor that we picked
// The parameters are the dependent class implementations that we retrieved
return constructorInfo.Invoke(constructorParamImplementations.ToArray());
}
}
} |
namespace Aqueduct.SitecoreLib.Search.Parameters
{
public class FieldSearchParam : SearchParam
{
public string FieldName { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScoreManager : MonoBehaviour {
/*
* So what's a Score Manager do?
* Well, keeps track of the score, of course!
* It has to be able to respond to the following messages:
* -AddRuns() by a boundary or housefront collider
* -MultiplierWallCount() by a housefront collider
* -And it should have functions fulfilling the following duties:
* -getRuns()
* -setRuns()
* -addToRuns()
*
* -getMultiplier()
* -setMultiplier()
* -addToMultiplier()
*
* -getPainted()
* -setPainted()
* -addToPainted()
*
* -GetMultedScore()
*/
int runs;
float multiplier;
int painted;
public int fullyPaintedLimit;
void Start () {
setRuns (0);
setMultiplier (1);
setPainted (0);
}
void Update(){
// Debug.Log ("Score is " + runs);
// Debug.Log ("Multiplier is " + multiplier);
}
public int getRuns(){
return runs;
}
void setRuns(int newruns){
runs = newruns;
}
public void addToRuns(int adding_runs){
runs += adding_runs;
}
public float getMultiplier(){
return multiplier;
}
void setMultiplier(float new_mult){
multiplier = new_mult;
}
public void addToMultiplier(float adding_mult){
multiplier += adding_mult;
}
int getPainted(){
return painted;
}
void setPainted(int new_painted){
painted = new_painted;
}
public void addToPainted(int adding_painted){
painted += adding_painted;
}
public float getMultedScore(){
return (getMultiplier () * getRuns ());
}
}
|
// Phạm Mạnh Hùng - 20194293
using System;
using System.Collections.Generic;
using DTO;
namespace DAL
{
/// <summary>
/// Class khởi tạo và lưu trữ dữ liệu về khách hàng
/// </summary>
public class KhachHangDAL
{
private List<KhachHangDTO> _dsKhachHang;
/// <summary>
/// Danh sách các khách hàng
/// </summary>
public List<KhachHangDTO> DsKhachHang
{
get
{
if (_dsKhachHang == null)
{
_Load();
}
return _dsKhachHang;
}
}
/// <summary>
/// Khởi tạo dữ liệu ban đầu cho chương trình, tránh việc khi chạy chương trình thì phải nhập lại dữ liệu từ đầu
/// </summary>
private void _Load()
{
_dsKhachHang = new List<KhachHangDTO>()
{
new KhachHangDTO("TC10120211503", "Pham Hung", "Lang Son", "TC101", new DateTime(2021, 3, 15), new DateTime(2021, 6, 15), 10000000),
new KhachHangDTO("TC20520210120 ", "Nguyen Van A", "Ha Noi", "TC205", new DateTime(2021, 1, 20), new DateTime(2021, 7, 23), 7000000),
new KhachHangDTO("TC10420210113 ", "Nguyen Van B", "Ha Noi", "TC104", new DateTime(2021, 1, 13), new DateTime(2021, 5, 12), 10000000),
new KhachHangDTO("TC30420210201 ", "Nguyen Van C", "Ha Noi", "TC304", new DateTime(2021, 2, 1), new DateTime(2021, 5, 30), 11000000),
new KhachHangDTO("TC30520210202 ", "Nguyen Van D", "Ha Noi", "TC305", new DateTime(2021, 2, 2), new DateTime(2021, 5, 16), 7000000),
};
}
}
}
|
// (C) 2012 Christian Schladetsch. See http://www.schladetsch.net/flow/license.txt for Licensing information.
using System;
using System.Diagnostics;
namespace Flow
{
/// <summary>
/// TODO: delta-capping, pausing, introduction of zulu/sim time differences
/// </summary>
internal class TimeFrame : ITimeFrame
{
private Stopwatch _stopwatch;
public TimeFrame()
{
_stopwatch = new Stopwatch();
Now = TimeSpan.Zero;
Last = TimeSpan.Zero;
Delta = TimeSpan.Zero;
}
/// <inheritdoc />
public System.TimeSpan Last { get; internal set; }
/// <inheritdoc />
public System.TimeSpan Now { get; internal set; }
/// <inheritdoc />
public System.TimeSpan Delta { get; internal set; }
public void Step()
{
if (_stopwatch.IsRunning == false)
{
_stopwatch.Reset();
_stopwatch.Start();
}
Last = Now;
Delta = _stopwatch.Elapsed - Last;
Now = _stopwatch.Elapsed;
}
}
} |
using System.ComponentModel.DataAnnotations;
using CourseLibrary.API.ValidationAttributes;
namespace CourseLibrary.API.Models.Courses
{
[CourseTitleMustBeDifferentFromDescription(ErrorMessage = "Title must be different from description")]
public abstract class CourseForManipulationDto
{
[Required(ErrorMessage = "You should fill out title")]
[MaxLength(100, ErrorMessage = "You should provide title lesser than 100 characters")]
public string Title { get; set; }
[MaxLength(1500, ErrorMessage = "You should provide description lesser than 1500 characters")]
public virtual string Description { get; set; }
}
} |
using System.Collections.Generic;
using UnityEngine;
public class Sounds_Scriptable : ScriptableObject {
public List<string> vSoundsClip;
#if UNITY_EDITOR
private void Awake() {
AudioClip[] vAudioClips = Resources.LoadAll<AudioClip>( "Audio/Sounds");
vSoundsClip = new List<string>();
foreach( AudioClip p in vAudioClips ) vSoundsClip.Add( "Audio/Sounds/" + p.name );
}
#endif
}
|
using System;
using System.Text.RegularExpressions;
class SubStringInText
{
//Write a program that finds how many times a sub-string is contained in a given text (perform case insensitive search).
static void Main(string[] args)
{
Console.Write("Enter some text: ");
string text = Console.ReadLine();
Console.Write("Enter substring to search for: ");
string substring = Console.ReadLine();
Console.WriteLine(GetSubstringCount(text, substring));
}
private static int GetSubstringCount(string text, string substring)
{
return Regex
.Matches(text, substring, RegexOptions.IgnoreCase)
.Count;
}
}
|
// File initially copied from
// https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/4d9b3e3bb785a55f73b3029a843f0c0b73cc9ea7/StyleCop.Analyzers/StyleCop.Analyzers.CodeFixes/Helpers/FixAllContextHelper.cs
// Original copyright statement:
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
namespace Meziantou.Analyzer;
internal static class FixAllContextHelper
{
public static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync(FixAllContext fixAllContext)
{
var allDiagnostics = ImmutableArray<Diagnostic>.Empty;
var projectsToFix = ImmutableArray<Project>.Empty;
var document = fixAllContext.Document;
var project = fixAllContext.Project;
switch (fixAllContext.Scope)
{
case FixAllScope.Document:
if (document != null)
{
var documentDiagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false);
return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty.SetItem(document, documentDiagnostics);
}
break;
case FixAllScope.Project:
projectsToFix = ImmutableArray.Create(project);
allDiagnostics = await GetAllDiagnosticsAsync(fixAllContext, project).ConfigureAwait(false);
break;
case FixAllScope.Solution:
projectsToFix = project.Solution.Projects
.Where(p => p.Language == project.Language)
.ToImmutableArray();
var diagnostics = new ConcurrentDictionary<ProjectId, ImmutableArray<Diagnostic>>();
var tasks = new Task[projectsToFix.Length];
for (var i = 0; i < projectsToFix.Length; i++)
{
fixAllContext.CancellationToken.ThrowIfCancellationRequested();
var projectToFix = projectsToFix[i];
tasks[i] = Task.Run(
async () =>
{
var projectDiagnostics = await GetAllDiagnosticsAsync(fixAllContext, projectToFix).ConfigureAwait(false);
diagnostics.TryAdd(projectToFix.Id, projectDiagnostics);
}, fixAllContext.CancellationToken);
}
await Task.WhenAll(tasks).ConfigureAwait(false);
allDiagnostics = allDiagnostics.AddRange(diagnostics.SelectMany(i => i.Value.Where(x => fixAllContext.DiagnosticIds.Contains(x.Id))));
break;
}
if (allDiagnostics.IsEmpty)
{
return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty;
}
return await GetDocumentDiagnosticsToFixAsync(allDiagnostics, projectsToFix, fixAllContext.CancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all <see cref="Diagnostic"/> instances within a specific <see cref="Project"/> which are relevant to a
/// <see cref="FixAllContext"/>.
/// </summary>
/// <param name="fixAllContext">The context for the Fix All operation.</param>
/// <param name="project">The project.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the asynchronous operation. When the task completes
/// successfully, the <see cref="Task{TResult}.Result"/> will contain the requested diagnostics.</returns>
private static async Task<ImmutableArray<Diagnostic>> GetAllDiagnosticsAsync(FixAllContext fixAllContext, Project project)
{
return await fixAllContext.GetAllDiagnosticsAsync(project).ConfigureAwait(false);
}
private static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync(
ImmutableArray<Diagnostic> diagnostics,
ImmutableArray<Project> projects,
CancellationToken cancellationToken)
{
var treeToDocumentMap = await GetTreeToDocumentMapAsync(projects, cancellationToken).ConfigureAwait(false);
var builder = ImmutableDictionary.CreateBuilder<Document, ImmutableArray<Diagnostic>>();
foreach (var documentAndDiagnostics in diagnostics.GroupBy(d => GetReportedDocument(d, treeToDocumentMap)))
{
cancellationToken.ThrowIfCancellationRequested();
var document = documentAndDiagnostics.Key;
if (document != null)
{
var diagnosticsForDocument = documentAndDiagnostics.ToImmutableArray();
builder.Add(document, diagnosticsForDocument);
}
}
return builder.ToImmutable();
}
private static async Task<ImmutableDictionary<SyntaxTree, Document>> GetTreeToDocumentMapAsync(ImmutableArray<Project> projects, CancellationToken cancellationToken)
{
var builder = ImmutableDictionary.CreateBuilder<SyntaxTree, Document>();
foreach (var project in projects)
{
cancellationToken.ThrowIfCancellationRequested();
foreach (var document in project.Documents)
{
cancellationToken.ThrowIfCancellationRequested();
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (tree != null)
{
builder.Add(tree, document);
}
}
}
return builder.ToImmutable();
}
private static Document? GetReportedDocument(Diagnostic diagnostic, ImmutableDictionary<SyntaxTree, Document> treeToDocumentsMap)
{
var tree = diagnostic.Location.SourceTree;
if (tree != null)
{
if (treeToDocumentsMap.TryGetValue(tree, out var document))
{
return document;
}
}
return null;
}
}
|
using Paylocity.Models;
namespace Paylocity.Benefits.CostStrategies
{
public class SingleEmployeeStrategy : IBenefitsCostStrategy
{
private readonly IConfiguration _configuration;
public SingleEmployeeStrategy(IConfiguration configuration)
{
_configuration = configuration;
}
public IBenefitsPackage GetPackageCost(IEmployee employee)
{
return new BenefitsPackage()
{
EmployeeCost = _configuration.AnnualEmployeeBenefitsCost
};
}
public bool IsApplicableForEmployee(IEmployee employee)
{
return employee.Dependents.Count == 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using InfiniteMeals.Kitchens.Model;
using System.Collections.ObjectModel;
using System.Globalization;
using InfiniteMeals.Refund;
using InfiniteMeals.Information;
using InfiniteMeals.PromptAddress;
using Plugin.LatestVersion;
using InfiniteMeals.Checkout;
using Xamarin.Essentials;
using Acr.UserDialogs;
using Newtonsoft.Json;
//using Foundation;
//using UIKit;
//using Android.Content;
namespace InfiniteMeals
{
public partial class MainPage : ContentPage
{
ObservableCollection<KitchensModel> Kitchens = new ObservableCollection<KitchensModel>();
// THIS LIST WILL CONTAIN ALL WEEKS OPENED AND CLOSED HOURS
public IList<IList<string>> businessDailyHours = null;
public IList<IList<string>> businessDailyAcceptingHours = null;
public IList<IList<string>> businessDeliveryHours = null;
// THIS CLASS CONTAINTS THE LIST OF HOURS FOR EVERY BUSINESS BY DAY
public class BusinessHours
{
public IList<string> Friday { get; set; }
public IList<string> Monday { get; set; }
public IList<string> Sunday { get; set; }
public IList<string> Tuesday { get; set; }
public IList<string> Saturday { get; set; }
public IList<string> Thursday { get; set; }
public IList<string> Wednesday { get; set; }
}
public MainPage()
{
InitializeComponent();
// CheckVersion();
//try
//{
// GetKitchens();
//}
//catch (TaskCanceledException ex)
//{
// GetKitchens();
//}
//// Kitchens.Clear();
//kitchensListView.RefreshCommand = new Command(() =>
//{
// GetKitchens();
// kitchensListView.IsRefreshing = false;
//});
kitchensListView.ItemSelected += Handle_ItemTapped();
}
protected async void GetKitchens()
{
var request = new HttpRequestMessage();
// request.RequestUri = new Uri("https://phaqvwjbw6.execute-api.us-west-1.amazonaws.com/dev/api/v1/kitchens");
request.RequestUri = new Uri("https://tsx3rnuidi.execute-api.us-west-1.amazonaws.com/dev/api/v2/businesses");
request.Method = HttpMethod.Get;
var client = new HttpClient();
try
{
HttpResponseMessage response = await client.SendAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string data = response.Content.ReadAsStringAsync().Result;
ServingFreshBusiness business = new ServingFreshBusiness();
business = JsonConvert.DeserializeObject<ServingFreshBusiness>(data);
var currentDay = DateTime.Now.DayOfWeek.ToString();
var time = DateTime.Now.TimeOfDay.ToString().Substring(0, 8);
this.Kitchens.Clear();
for(int i = 0; i < business.result.result.Count;i++)
{
// SETTING LIST OF DAILY BUSINESS HOURS - RDS
businessDailyHours = new List<IList<string>>();
businessDailyAcceptingHours = new List<IList<string>>();
businessDeliveryHours = new List<IList<string>>();
SetListOfBusinessHours(business.result.result[i].business_hours);
SetListOfBusinessAcceptingHours(business.result.result[i].business_accepting_hours);
SetListOfBusinessDeliveryHours(business.result.result[i].business_delivery_hours);
try
{
Console.WriteLine("available_zip:" + GetZipCodeListByBussinessName(business.result.result[i].business_name));
}
catch
{
Console.WriteLine("no");
}
Boolean businessIsOpen;
string accepting_hours;
int dayOfWeekIndex = getDayOfWeekIndex(DateTime.Today);
// CHECKING CURRENT BUSINESS IS OPERATING
if (IsOpened() == false)
{
accepting_hours = "Not accepting orders, no meals";
businessIsOpen = false;
}
else if (IsOpened24Hrs(dayOfWeekIndex) == true)
{
accepting_hours = "24 hours";
businessIsOpen = true;
}
else
{
Boolean isAccepting = IsBusinessAccepting(dayOfWeekIndex, DateTime.Parse(time));
businessIsOpen = IsBusinessOpen(TimeSpan.Parse(businessDailyAcceptingHours[dayOfWeekIndex][0]), TimeSpan.Parse(businessDailyAcceptingHours[dayOfWeekIndex][1]), isAccepting);
accepting_hours = WhenAccepting(businessIsOpen, dayOfWeekIndex);
}
string delivery_hours = WhenDelivering(dayOfWeekIndex);
bool is_available = false;
string zipcodes = "";
try
{
string customer_zipcode = Application.Current.Properties["zip"].ToString();
zipcodes = GetZipCodeListByBussinessName(business.result.result[i].business_name);
string[] zipcodes_array = zipcodes.Split(',');
foreach (var zipcode in zipcodes_array)
{
if (zipcode == customer_zipcode)
{
is_available = true;
break;
}
}
}
catch
{
is_available = true;
zipcodes = "";
}
if (is_available)
{
this.Kitchens.Add(new KitchensModel()
{
kitchen_id = business.result.result[i].business_uid,
zipcode = business.result.result[i].business_zip,
title = business.result.result[i].business_name,
open_hours = accepting_hours,
delivery_period = delivery_hours,
description = business.result.result[i].business_desc,
isOpen = businessIsOpen,
status = (businessIsOpen == true) ? "Open now" : "Closed",
statusColor = (businessIsOpen == true) ? "Green" : "#a0050f",
opacity = (businessIsOpen == true) ? "1.0" : "0.6",
available_zipcode = zipcodes
}
);
if (business.result.result[i].business_desc != null)
{
Console.WriteLine("This is the length of the a desc" + business.result.result[i].business_desc.Length);
}
}
else
{
if (!zipcodes.Equals(""))
{
this.Kitchens.Add(new KitchensModel()
{
kitchen_id = business.result.result[i].business_uid,
zipcode = business.result.result[i].business_zip,
title = business.result.result[i].business_name,
open_hours = accepting_hours,
delivery_period = delivery_hours,
description = business.result.result[i].business_desc,
isOpen = false,
status = "Not available for your address",
statusColor = "#a0050f",
opacity = "0.6",
available_zipcode = zipcodes
});
}
}
}
kitchensListView.ItemsSource = Kitchens;
}
}
catch (TaskCanceledException ex)
{
GetKitchens();
}
}
// HELPER FUNCTION 1
// THIS FUNCTION SETS UP THE A LIST OF ZIPCODES
public string GetZipCodeListByBussinessName(string businessName)
{
if (businessName.Equals("Resendiz Family Fruit Barn"))
{
return "94024,94087,95014,95030,95032,95051,95070,95111,95112,95120,95123,95124,95125,95129,95130,95128,95122,95118,95126,95136,95113,95117,95050";
}
if (businessName.Equals("Esquivel Farm"))
{
return "94024,94087,95014,95030,95032,95051,95070,95111,95112,95120,95123,95124,95125,95129,95130,95128,95122,95118,95126,95136,95113,95117,95050";
}
if (businessName.Equals("Almaden Farmer's Market"))
{
return "94024,94087,95014,95030,95032,95051,95070,95111,95112,95120,95123,95124,95125,95129,95130,95128,95122,95118,95126,95136,95113,95117,95050";
}
if (businessName.Equals("Nitya Ayurveda"))
{
return "94024,94087,95014,95030,95032,95051,95070,95111,95112,95120,95123,95124,95125,95129,95130,95128,95122,95118,95126,95136,95113,95117,95050";
}
// WE DON'T HAVE THE LIST OF ZIPCODES FOR THE GIVEN BUSINESS
return "";
}
// HELPER FUNCTION 2
// THIS FUNCTION INSERTS THE BUSINESS HOURS IN A LIST EACH INDEX
// REPRESENT A WEEKDAY
private void SetListOfBusinessHours(string hoursStr)
{
BusinessHours hours = JsonConvert.DeserializeObject<BusinessHours>(hoursStr);
businessDailyHours.Add(hours.Sunday);
businessDailyHours.Add(hours.Monday);
businessDailyHours.Add(hours.Tuesday);
businessDailyHours.Add(hours.Wednesday);
businessDailyHours.Add(hours.Thursday);
businessDailyHours.Add(hours.Friday);
businessDailyHours.Add(hours.Saturday);
}
// HELPER FUNCTION 3
// THIS FUNCTION INSERTS THE BUSINESS HOURS IN A LIST EACH INDEX
// REPRESENT A WEEKDAY
private void SetListOfBusinessAcceptingHours(string hoursStr)
{
BusinessHours hours = JsonConvert.DeserializeObject<BusinessHours>(hoursStr);
businessDailyAcceptingHours.Add(hours.Sunday);
businessDailyAcceptingHours.Add(hours.Monday);
businessDailyAcceptingHours.Add(hours.Tuesday);
businessDailyAcceptingHours.Add(hours.Wednesday);
businessDailyAcceptingHours.Add(hours.Thursday);
businessDailyAcceptingHours.Add(hours.Friday);
businessDailyAcceptingHours.Add(hours.Saturday);
}
// HELPER FUNCTION 4
// THIS FUNCTION INSERTS THE BUSINESS HOURS IN A LIST EACH INDEX
// REPRESENT A WEEKDAY
private void SetListOfBusinessDeliveryHours(string hoursStr)
{
BusinessHours hours = JsonConvert.DeserializeObject<BusinessHours>(hoursStr);
businessDeliveryHours.Add(hours.Sunday);
businessDeliveryHours.Add(hours.Monday);
businessDeliveryHours.Add(hours.Tuesday);
businessDeliveryHours.Add(hours.Wednesday);
businessDeliveryHours.Add(hours.Thursday);
businessDeliveryHours.Add(hours.Friday);
businessDeliveryHours.Add(hours.Saturday);
}
// HELPER FUNCTION 5
// THIS FUNCTION DETERMINES IF A BUSINESS IS OPERATING ANY DAY
// IF AT LEAST ONE DAY IS OPEN, THEN SAY IT IS OPERATING. OTHERWISE IS NOT.
private bool IsOpened()
{
int openedTime = 0;
int closedTime = 1;
for(int i = 0; i < businessDailyHours.Count; i++)
{
DateTime opened = DateTime.Parse(businessDailyHours[i][openedTime]);
DateTime closed = DateTime.Parse(businessDailyHours[i][closedTime]);
if (DateTime.Compare(opened, closed) != 0)
{
return true;
}
}
return false;
}
// HELPER FUNCTION 6
// THIS FUNCTION DETERMINES IF A BUSINEES IS OPERATING 24HOURS
private bool IsOpened24Hrs(int currentDayIndex)
{
var opened = businessDailyHours[currentDayIndex][0];
var closed = businessDailyHours[currentDayIndex][1];
if(opened.Equals("00:00:00") && closed.Equals("23:59:59")){
return true;
}
return false;
}
// HELPER FUNCTION 7
// THIS FUNCTION DETERMINE IF THE CURRENT BUSINESS ARE ACCEPTING ORDERS
// BASED ON CURRENT DAY AND TIME
private bool IsBusinessAccepting(int currentDayIndex, DateTime currentTime)
{
int beforeClosedTime = -1;
int inTime = 0;
int afterOpenedTime = 1;
int openedTime = 0;
int closedTime = 1;
DateTime opened = DateTime.Parse(businessDailyAcceptingHours[currentDayIndex][openedTime]);
DateTime closed = DateTime.Parse(businessDailyAcceptingHours[currentDayIndex][closedTime]);
// BUSINESS IS NOT ACCEPTING ORDERS TODAY
if (DateTime.Compare(opened, closed) == 0)
{
return false;
}
else
{
// BUSINESS ACCEPT ORDERS IF WITH IN THE ACCEPTING HOURS RANGE
if (DateTime.Compare(currentTime, opened) == inTime
|| DateTime.Compare(currentTime, opened) == afterOpenedTime && DateTime.Compare(currentTime, closed) == beforeClosedTime
|| DateTime.Compare(currentTime, closed) == inTime)
{
return true;
}
else
{
return false;
}
}
}
// HELPER FUNCTION 8
// THIS FUNCTION DETERMINES WHEN IS THE NEXT ACCEPTING TIME AVAILABLE DAY DETERMINE BY THE INDEX OF THE LIST
// NOTE: IF OPENED == CLOSED TIME RETURN FALSE;
private bool NextAcceptingDay(int dayIndex, int orderOrDelivery)
{
// 0 = Order
DateTime opened = new DateTime();
DateTime closed = new DateTime();
if (orderOrDelivery == 0)
{
opened = DateTime.Parse(businessDailyAcceptingHours[dayIndex][0]);
closed = DateTime.Parse(businessDailyAcceptingHours[dayIndex][1]);
}
else
{
opened = DateTime.Parse(businessDeliveryHours[dayIndex][0]);
closed = DateTime.Parse(businessDeliveryHours[dayIndex][1]);
}
if (DateTime.Compare(opened, closed) == 0)
{
return false;
}
else
{
return true;
}
}
public async void CheckVersion()
{
string latestVersionNumber = await CrossLatestVersion.Current.GetLatestVersionNumber();
string installedVersionNumber = CrossLatestVersion.Current.InstalledVersionNumber;
var isLatest = await CrossLatestVersion.Current.IsUsingLatestVersion();
if (!isLatest)
{
bool update = await DisplayAlert("Serving Now\nhas gotten even better!", "Please visit the App Store to get the latest version.", "Yes", "No"); ;
if (update)
{
await CrossLatestVersion.Current.OpenAppInStore();
}
}
}
private EventHandler<SelectedItemChangedEventArgs> Handle_ItemTapped()
{
return OnItemSelected;
}
async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
// disable selected item highlighting;
if (e.SelectedItem == null) return;
((ListView)sender).SelectedItem = null;
// do something with the selection
var kitchen = e.SelectedItem as KitchensModel;
// disable selection if the kitchen is closed
if (kitchen.isOpen == false)
{
return;
}
var guid = Preferences.Get("guid", null);
if (guid == null)
{
var will_enable = await DisplayAlert("Serving Now works better with Notifications Enabled", "Please consider turning on Notifications so that we can Confirm your order was received and Notify you when your order has been delivered", "No Thanks", "Yes! Send Notifications");
if (!will_enable)
{
await DisplayAlert("Thank you!", "Make sure you restart the app after you've enabled", "Go to app setting");
//switch (Device.RuntimePlatform)
//{
// case Device.iOS:
// var url = new NSUrl($"app-settings:notifications");
// UIApplication.SharedApplication.OpenUrl(url);
// break;
// case Device.Android:
// //Android.App.Application.Context.StartActivity(new Intent(
// // Android.Provider.Settings.ActionApplicationDetailsSettings,
// // Android.Net.Uri.Parse("package:" + Android.App.Application.Context.PackageName)));
// //Intent intent = new Intent(
// //Android.Provider.Settings.ActionApplicationDetailsSettings,
// //Android.Net.Uri.Parse("package:" + Android.App.Application.Context.PackageName));
// //intent.AddFlags(ActivityFlags.NewTask);
// //Android.App.Application.Context.StartActivity(intent);
// break;
//}
DependencyService.Get<ISettingsHelper>().OpenAppSettings();
}
}
await Navigation.PushAsync(new SelectMealOptions(kitchen.kitchen_id, kitchen.title, kitchen.zipcode, kitchen.available_zipcode));
}
// Get integer index of day of the week, with 0 as Sunday
private int getDayOfWeekIndex(DateTime day)
{
if (day.DayOfWeek == DayOfWeek.Sunday)
return 0;
if (day.DayOfWeek == DayOfWeek.Monday)
return 1;
if (day.DayOfWeek == DayOfWeek.Tuesday)
return 2;
if (day.DayOfWeek == DayOfWeek.Wednesday)
return 3;
if (day.DayOfWeek == DayOfWeek.Thursday)
return 4;
if (day.DayOfWeek == DayOfWeek.Friday)
return 5;
if (day.DayOfWeek == DayOfWeek.Saturday)
return 6;
return -1;
}
// Get day of week string from intger index of the week, with 0 as Sunday
private string getDayOfWeekFromIndex(int index)
{
if (index == 0)
return "Sunday";
if (index == 1)
return "Monday";
if (index == 2)
return "Tuesday";
if (index == 3)
return "Wednesday";
if (index == 4)
return "Thursday";
if (index == 5)
return "Friday";
if (index == 6)
return "Saturday";
return "Error";
}
// Is the store already closed or is it opening later today?
private int isAlreadyClosed(DateTime endTime)
{
string currentTime = DateTime.Now.TimeOfDay.ToString().Substring(0, 8);
if (DateTime.Compare(DateTime.Parse(currentTime), endTime) < 0)
{
return 0;
}
else
{
return 1;
}
}
// When is the business accepting orders?
private string WhenAccepting(Boolean businessIsOpen, int dayOfWeekIndex)
{
//JArray converted_accepting_hours = JArray.Parse((string)k["accepting_hours"]);
//string end_time_12 = ConvertFromToTime(converted_accepting_hours[dayOfWeekIndex]["M"]["close_time"]["S"].ToString(), "HH:mm", "h:mm tt");
string end_time_24 = businessDailyAcceptingHours[dayOfWeekIndex][1];
if (businessIsOpen == true)
{
return "Until " + ConvertFromToTime(end_time_24.Substring(0, 5), "HH:mm", "h:mm tt");
}
int nextOpenDay = nextPeriodDayIndex(dayOfWeekIndex, isAlreadyClosed(DateTime.Parse(end_time_24)), 0);
if (nextOpenDay == -1)
{
return "Not currently accepting orders";
}
string next_day;
if (nextOpenDay == dayOfWeekIndex)
{
next_day = "today";
}
else if (nextOpenDay == (dayOfWeekIndex + 1) % 7)
{
next_day = "tomorrow";
}
else
{
next_day = getDayOfWeekFromIndex(nextOpenDay);
}
// INDEX 1 MEANS CLOSED TIME
return "Starting " + next_day + " " + ConvertFromToTime(businessDailyAcceptingHours[nextOpenDay][1].Substring(0, 5), "HH:mm", "h:mm tt");
}
// When is the next delivery period?
private string WhenDelivering(int dayOfWeekIndex)
{
// JArray converted_accepting_hours = JArray.Parse((string)k["accepting_hours"]);
int nextDeliveryDayIndex = nextPeriodDayIndex(dayOfWeekIndex, 1, 1);
if (nextDeliveryDayIndex != -1)
{
var deliveryOpenTime = businessDeliveryHours[nextDeliveryDayIndex][0];
var deliveryCloseTime = businessDeliveryHours[nextDeliveryDayIndex][1];
return getDayOfWeekFromIndex(nextDeliveryDayIndex) + " " + ConvertFromToTime(deliveryOpenTime.Substring(0,5), "HH:mm", "h:mm tt") + " - " + ConvertFromToTime(deliveryCloseTime.Substring(0, 5), "HH:mm", "h:mm tt");
}
else
{
return "Not currently delivering";
}
}
// Get integer index of day of the week of next time (accepting or delivering) period, with 0 as Sunday
// 3rd and 4th arguments take kitchen API list and boolean keys (e.g. delivery_hours and is_delivering)
// 5th argument takes the number of days to wait before beginning the check. For instance, if you want to find the next delivery period starting the day after today, argument should be 1.
private int nextPeriodDayIndex(int dayOfTheWeek, int dayDelay, int orderOrDelivery)
{
//JArray converted_accepting_hours = JArray.Parse((string)kitchen[list_key]);
int dayIndex;
for (int i = dayDelay; i < dayDelay + 7; i++)
{
dayIndex = (dayOfTheWeek + i) % 7;
if (NextAcceptingDay(dayIndex, orderOrDelivery) == true)
{
return dayIndex;
}
}
return -1;
}
// Function checking if business is currently open
private Boolean IsBusinessOpen(TimeSpan open_time, TimeSpan close_time, Boolean is_accepting)
{
TimeSpan now = DateTime.Now.TimeOfDay;
// Accepting orders on current day?
if (is_accepting == false)
{
return false;
}
else
{
// Opening and closing hours on same day
if (open_time <= close_time)
{
if (now >= open_time && now <= close_time)
{
return true;
}
else
{
return false;
}
}
// Opening and closing hours on different day
else
{
if (now >= open_time || now <= close_time)
{
return true;
}
else
{
return false;
}
}
}
}
private string formatZipcode(string zipcode)
{
if (zipcode == "95120")
{
return "Almaden";
}
if (zipcode == "95135")
{
return "Evergreen";
}
if (zipcode == "95060")
{
return "Santa Cruz";
}
return "Other";
}
// https://www.niceonecode.com/Question/20540/how-to-convert-24-hours-string-format-to-12-hours-format-in-csharp
public static string ConvertFromToTime(string timeHour, string inputFormat, string outputFormat)
{
var timeFromInput = DateTime.ParseExact(timeHour, inputFormat, null, DateTimeStyles.None);
string timeOutput = timeFromInput.ToString(
outputFormat,
CultureInfo.InvariantCulture);
return timeOutput;
}
void NavigateToRefund(object sender, EventArgs e)
{
Navigation.PushAsync(new ProductRefundPage());
}
void NavigateToInformation(object sender, EventArgs e)
{
Navigation.PushAsync(new InformationPage());
//Navigation.PushAsync(new SocialLoginPage());
}
void PromptForAddress(object sender, EventArgs e)
{
Navigation.PushAsync(new PromptAddressPage());
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Xaml.Controls;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
namespace kassasysteem.Classes
{
internal class CreatePrintPdf
{
public static void CreateReceipt(string name, int bonnummer)
{
var document = new PdfDocument();
var page = document.Pages.Add();
page.Graphics.DrawString("Groene Vingers\n", new PdfStandardFont(PdfFontFamily.TimesRoman, 32), PdfBrushes.YellowGreen, 20, 10);
page.Graphics.DrawString(DateTime.Now.Date.Day + "-" + DateTime.Now.Date.Month + "-" + DateTime.Now.Year + " " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + "\n" + name + " \nBonnummer: " + bonnummer, new PdfStandardFont(PdfFontFamily.TimesRoman, 16), PdfBrushes.Black, 10, 60);
page.Graphics.DrawLine(new PdfPen(Color.Black),10,125, 400, 125);
page.Graphics.DrawString("Aantal Omschrijving Bedrag", new PdfStandardFont(PdfFontFamily.TimesRoman, 16), PdfBrushes.Black, 10, 130);
page.Graphics.DrawLine(new PdfPen(Color.Black), 10, 153, 400, 153);
page.Graphics.DrawString("1 Consultancy per uur €75,00", new PdfStandardFont(PdfFontFamily.TimesRoman, 16), PdfBrushes.Black, 10, 160);
page.Graphics.DrawLine(new PdfPen(Color.Black), 10, 183, 400, 183);
page.Graphics.DrawString("1 Subtotaal: €75,00", new PdfStandardFont(PdfFontFamily.TimesRoman, 16), PdfBrushes.Black, 10, 190);
var stream = new MemoryStream();
document.Save(stream);
document.Close(true);
Save(stream, "Bon" + bonnummer + ".pdf");
}
private static async void Save(Stream stream, string filename)
{
stream.Position = 0;
StorageFile stFile;
if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent($"Windows.Phone.UI.Input.HardwareButtons"))
{
var savePicker = new FileSavePicker
{
DefaultFileExtension = ".pdf",
SuggestedFileName = filename
};
savePicker.FileTypeChoices.Add("Adobe PDF Document", new List<string>() { ".pdf" });
stFile = await savePicker.PickSaveFileAsync();
}
else
{
var local = ApplicationData.Current.LocalFolder;
stFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
}
if (stFile == null) return;
var fileStream = await stFile.OpenAsync(FileAccessMode.ReadWrite);
var st = fileStream.AsStreamForWrite();
st.Write((stream as MemoryStream)?.ToArray(), 0, (int)stream.Length);
st.Flush();
st.Dispose();
fileStream.Dispose();
}
}
}
|
using Dapper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using static HelperLibrary.Tools;
using System.Text;
using System.Threading.Tasks;
using ConnectLibrary.Logger;
using ConnectLibrary.SQLRepository.Interfaces;
using HelperLibrary.Models;
using HelperLibrary.Models.Interfaces;
using static ConnectLibrary.LibrarySettings;
namespace ConnectLibrary.SQLRepository.Prototypes
{
public abstract class GeneralRepository<T> : IRepository<T> where T: class, ITable
{
private readonly string _tableName;
public GeneralRepository(Tables tableName)
{
_tableName = tableName.ToString();
}
public void DeleteById(int id)
{
if (id <= 0)
{
Log.MakeLog(LoggerOperations.Error, "ArgumentOutOfRangeException");
throw new ArgumentOutOfRangeException(nameof(id));
}
using (IDbConnection cn = Connection)
{
cn.Open();
cn.Execute("DELETE FROM dbo." + _tableName + " WHERE Id=@ID", new { ID = id });
}
}
public T FindByID(int id)
{
if (id <= 0)
{
Log.MakeLog(LoggerOperations.Error, "ArgumentOutOfRangeException");
throw new ArgumentOutOfRangeException(nameof(id));
}
T item = default(T);
using (IDbConnection cn = Connection)
{
cn.Open();
var p = new DynamicParameters();
p.Add("@ID", id);
item = cn.Query<T>($"SELECT * FROM dbo.{_tableName} WHERE Id=@ID", p).SingleOrDefault();
}
return item;
}
public IEnumerable<T> FindAll()
{
IEnumerable<T> items = null;
using (IDbConnection cn = Connection)
{
cn.Open();
items = cn.Query<T>("SELECT * FROM dbo." + _tableName);
}
return items;
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
using System.Web;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Controllers;
using DotNetNuke.Entities.Portals;
#endregion
namespace DotNetNuke.Entities.Urls
{
/// <summary>
/// Abstract class to allow derived classes of different implementations of Url Rewriter
/// </summary>
public abstract class UrlRewriterBase
{
internal abstract void RewriteUrl(object sender, EventArgs e);
protected static void AutoAddAlias(HttpContext context)
{
var portalId = Host.Host.HostPortalID;
//the domain name was not found so try using the host portal's first alias
if (portalId > Null.NullInteger)
{
var portalAliasInfo = new PortalAliasInfo { PortalID = portalId, HTTPAlias = Globals.GetDomainName(context.Request, true) };
PortalAliasController.Instance.AddPortalAlias(portalAliasInfo);
context.Response.Redirect(context.Request.Url.ToString(), true);
}
}
protected static bool CanAutoAddPortalAlias()
{
bool autoAddPortalAlias = HostController.Instance.GetBoolean("AutoAddPortalAlias");
autoAddPortalAlias = autoAddPortalAlias && (PortalController.Instance.GetPortals().Count == 1);
return autoAddPortalAlias;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace BlackJack
{
class Game
{
private IBlackjackPlayer PlayerOne;
private IBlackjackPlayer PlayerTwo;
private Deck Deck;
public void StartNewGame()
{
PlayerOne = new Player();
PlayerTwo = new Dealer();
Deck = new Deck();
Deck.Shuffle();
PlayerOne.GiveCard(Deck.GetCard());
PlayerOne.GiveCard(Deck.GetCard());
PlayerTwo.GiveCard(Deck.GetCard());
PlayerTwo.GiveCard(Deck.GetCard());
//garākais variants:
//Card card1 = Deck.GetCard();
//PlayerOne.GiveCard(card1);
}
public void Loop()
{
//player one turn
while (!PlayerOne.IsGameCompleted() && PlayerOne.WantCard())
{
PlayerOne.GiveCard(Deck.GetCard());
}
if (PlayerOne.CountPoints() > 21)
{
Console.WriteLine("Player one lost the game!");
}
else if (PlayerOne.CountPoints() == 21)
{
Console.WriteLine("Player wins!");
}
else
{
//player two turn
Console.WriteLine("Dealers turn!");
while (!PlayerTwo.IsGameCompleted() && PlayerTwo.WantCard())
{
PlayerTwo.GiveCard(Deck.GetCard());
}
Console.WriteLine("Player one points: {0}", PlayerOne.CountPoints());
Console.WriteLine("Dealer points: {0}", PlayerTwo.CountPoints());
int playerPoints = PlayerOne.CountPoints();
int dealerPoints = PlayerTwo.CountPoints();
if (dealerPoints > 21 || playerPoints > dealerPoints)
{
Console.WriteLine("Player one wins ");
}
else
{
Console.WriteLine("Dealer wins!");
}
// īsā versija:
// Console.WriteLine(dealerPoints > 21 || playerPoints > dealerPoints ? "You win" : "Dealer wins");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KPI.Model.EF
{
public class LateOnUpLoad
{
[Key]
public int ID { get; set; }
public int UserID { get; set; }
public int NotificationID { get; set; }
public string Area { get; set; }
public string DeadLine { get; set; }
public string KPIName { get; set; }
public string Code { get; set; }
public string Year { get; set; }
}
}
|
using System;
public class Program
{
public static void Main()
{
var typeOfDay = Console.ReadLine();
var clientAge = int.Parse(Console.ReadLine());
var ticketPrice = 0;
if (clientAge < 0 || clientAge > 122)
{
Console.WriteLine("Error!");
return;
}
switch (typeOfDay)
{
case "Weekday":
ticketPrice = GetTicketPrice(clientAge, 12, 18, 12); break;
case "Weekend":
ticketPrice = GetTicketPrice(clientAge, 15, 20, 15); break;
case "Holiday":
ticketPrice = GetTicketPrice(clientAge, 5, 12, 10); break;
}
Console.WriteLine($"{ticketPrice}$");
}
public static int GetTicketPrice(int clientAge, int youngAge, int midAge, int oldAge)
{
var ticketPrice = 0;
if (clientAge >= 0 && clientAge <= 18)
{
ticketPrice = youngAge;
}
else if (clientAge > 18 && clientAge <= 64)
{
ticketPrice = midAge;
}
else
{
ticketPrice = oldAge;
}
return ticketPrice;
}
} |
/*
>>>----- Copyright (c) 2012 zformular ----->
| |
| Author: zformular |
| E-mail: zformular@163.com |
| Date: 9.27.2012 |
| |
╰==========================================╯
* POP3指令:
* USER username 认证用户名
* PASS password 认证密码 错误回送-ER ......
* STAT 回送邮箱内邮件数 总字大小
* LIST 成功回送邮件序列和字节大小
* TOP 1 接收第1封邮件, 成功返回第1封邮件头
* RETR 1 接收第1封邮件, 成功返回第1封邮件所有内容
* DELE 1 删除第1封邮件, QUIT命令后才会真正删除
* RSET 撤销所有的DELE命令
* QUIT 如果server处于处理状态,则进入'更新'状态即保存修改
* QUIT 如果server处于认可状态,则不进入'更新'状态
*/
using System;
using System.IO;
using ValueMail.Receive.Infrastructure;
namespace ValueMail.Receive.POP3.Instruction
{
public class POP3Instruction : IDisposable
{
private ProviderType providerTpye;
private StreamWriter streamWriter;
private StreamReader streamReader;
private String response;
public POP3Instruction(ProviderType providerType, StreamWriter streamWriter, StreamReader streamReader)
{
this.providerTpye = providerType;
this.streamWriter = streamWriter;
this.streamReader = streamReader;
}
/// <summary>
/// USER指令输入账户
/// </summary>
/// <param name="account"></param>
/// <returns></returns>
public String USERResponse(String account)
{
streamWriter.WriteLine("USER " + account);
streamWriter.Flush();
response = streamReader.ReadLine();
response = streamReader.ReadLine();
return response;
}
/// <summary>
/// PASS指令输入密码
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
public String PASSResponse(String password)
{
streamWriter.WriteLine("PASS " + password);
streamWriter.Flush();
response = streamReader.ReadLine();
return response;
}
/// <summary>
/// STAT指令查看邮件数量
/// </summary>
/// <returns></returns>
public String STATResponse()
{
streamWriter.WriteLine("STAT ");
streamWriter.Flush();
response = streamReader.ReadLine();
return response;
}
/// <summary>
/// UIDL指令获得邮件唯一码
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public String UIDLResponse(Int32 index)
{
streamWriter.WriteLine("UIDL " + index);
streamWriter.Flush();
response = streamReader.ReadLine();
return response;
}
/// <summary>
/// TOP指令查看邮件头部信息
/// </summary>
/// <param name="index"></param>
public String TOPResponse(Int32 index)
{
streamWriter.WriteLine("TOP " + index + " 0");
streamWriter.Flush();
response = streamReader.ReadLine();
return response;
}
/// <summary>
/// RETR指令查看完整邮件
/// </summary>
/// <param name="index"></param>
public String RETRResponse(Int32 index)
{
streamWriter.WriteLine("RETR " + index);
streamWriter.Flush();
response = streamReader.ReadLine();
return response;
}
/// <summary>
/// DELE指令删除指定邮件
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public String DELEResponse(Int32 index)
{
streamWriter.WriteLine("DELE " + index);
streamWriter.Flush();
response = streamReader.ReadLine();
return response;
}
/// <summary>
/// RSET指令撤销所有的删除指令
/// </summary>
/// <returns></returns>
public String RSETResponse()
{
streamWriter.WriteLine("RSET ");
streamWriter.Flush();
response = streamReader.ReadLine();
return response;
}
/// <summary>
/// '认证'状态,则退出. '处理'状态则更新
/// </summary>
/// <returns></returns>
public String QUITResponse()
{
streamWriter.WriteLine("QUIT ");
streamWriter.Flush();
response = streamReader.ReadLine();
return response;
}
/// <summary>
/// 读取回送的整行数据
/// </summary>
/// <returns></returns>
public String ReadResponse()
{
response = streamReader.ReadLine();
return response;
}
private Boolean disposed = false;
private void Dispose(Boolean disposing)
{
if (!disposed)
{
if (disposing)
{
if (streamWriter != null)
{
streamWriter.Close();
streamWriter = null;
}
if (streamReader != null)
{
streamReader.Close();
streamReader = null;
}
disposed = true;
}
}
}
#region IDisposable 成员
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region 析构函数
~POP3Instruction()
{
Dispose(false);
}
#endregion
}
}
|
using MvvmCross.Platform.Plugins;
namespace EsMo.Android.WeiBo.Bootstrap
{
public class MessengerPluginBootstrap
: MvxPluginBootstrapAction<global::MvvmCross.Plugins.Messenger.PluginLoader>
{
}
} |
using Newtonsoft.Json;
namespace Breezy.Sdk.Payloads
{
internal class FileInfoMessage
{
[JsonProperty("friendly_name")]
public string FriendlyName { get; set; }
[JsonProperty("file_size")]
public int FileSize { get; set; }
[JsonProperty("file_type")]
public string FileType { get; set; }
}
} |
namespace Kers.Models.Entities.KERScore
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type ExtensionEventGeoCoordinates.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class ExtensionEventGeoCoordinates
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
/// <summary>
/// Gets or sets altitude.
/// The altitude of the location.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "altitude", Required = Newtonsoft.Json.Required.Default)]
public double? Altitude { get; set; }
/// <summary>
/// Gets or sets latitude.
/// The latitude of the location.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "latitude", Required = Newtonsoft.Json.Required.Default)]
public double? Latitude { get; set; }
/// <summary>
/// Gets or sets longitude.
/// The longitude of the location.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "longitude", Required = Newtonsoft.Json.Required.Default)]
public double? Longitude { get; set; }
/// <summary>
/// Gets or sets accuracy.
/// The accuracy of the latitude and longitude. As an example, the accuracy can be measured in meters, such as the latitude and longitude are accurate to within 50 meters.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "accuracy", Required = Newtonsoft.Json.Required.Default)]
public double? Accuracy { get; set; }
/// <summary>
/// Gets or sets altitudeAccuracy.
/// The accuracy of the altitude.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "altitudeAccuracy", Required = Newtonsoft.Json.Required.Default)]
public double? AltitudeAccuracy { get; set; }
}
}
|
using UnityEngine;
namespace Game
{
public enum UiAction
{
Start,
Exit,
Credits,
Settings,
CanvasHover
}
public class VrUiElement : MonoBehaviour
{
[SerializeField] private UiAction action;
[SerializeField] private GameObject unselectedPanel;
[SerializeField] private GameObject hoverPanel;
private bool _hover;
private void Start()
{
if ((!unselectedPanel || !hoverPanel) && action != UiAction.CanvasHover)
Debug.LogError("Set the UI panels!");
}
public void SetHoverState(bool isHoveringOver)
{
if (_hover && isHoveringOver || !_hover && !isHoveringOver) return;
_hover = isHoveringOver;
if (action == UiAction.CanvasHover) return;
hoverPanel.SetActive(isHoveringOver);
unselectedPanel.SetActive(!isHoveringOver);
}
public void ExecuteAction()
{
switch (action)
{
case UiAction.Start:
GameHandler.Instance.StartGame();
break;
case UiAction.Exit:
Application.Quit();
break;
case UiAction.Credits:
GameSettings.Instance.DisplayCredits();
break;
case UiAction.Settings:
GameSettings.Instance.DisplaySettings();
break;
}
}
public void ToggleActivation(bool active)
{
unselectedPanel.transform.parent.gameObject.SetActive(active);
GetComponent<Collider>().enabled = active;
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace MOClient
{
class Program
{
static void Main(string[] args)
{
HttpClient client = new HttpClient();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://10.156.64.84:99/AcceptanceValidation/UploadFile");
string uploadfile = @"C:\Users\v-susu\Desktop\acceptance files\AT1-AT-ACCEPTANCE-20150401-TO-20150430.CSV";
request.Method = "Post";
//string boundary = "---------------------------7df155351124b4";
string boundary = "----7df155351124b4";
request.ContentType = "multipart/form-data; boundary=" + boundary;
//request.PreAuthenticate = true; //Gets or sets a value that indicates whether to send an Authorization header with the request.
request.Timeout = 600 * 1000; // Set client time out value
request.Credentials = new NetworkCredential("v-susu", "*s712l919*201506", "fareast");
request.Headers.Add("X-Requested-With", "XMLHttpRequest");
//request.Headers.Add("Accept", "application/json, text/javascript, */*; q=0.01");
request.Headers.Add("Accept-Language", "en-US");
request.Headers.Add("Accept-Encoding", "gzip, deflate");
//request.ContentLength = 0;
//string content = string.Empty;
// Send request message
//using (StreamWriter sw = new StreamWriter(request.GetRequestStream()/*, Encoding.UTF8*/))
//{
// sw.Write(content);
//}
UploadFileEx1(request, uploadfile, "filebutton", "application/vnd.ms-excel", boundary);
// Get response from server
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException responseException)
{
if (responseException.Response != null)
{
response = (HttpWebResponse)responseException.Response;
}
}
using (StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string t1 = response.ProtocolVersion.ToString();
string t2 = string.Format("{0}:{1}", (int)response.StatusCode, response.StatusCode);
var t3 = response.Headers;
var t4 = responseReader.ReadToEnd();
var t5 = responseReader.ReadToEnd();
}
}
public static void UploadFileEx(HttpWebRequest webrequest, string uploadfile, string fileFormName, string contenttype, string boundary)
{
// Build up the post message header
StringBuilder sb1 = new StringBuilder();
sb1.Append("--");
sb1.AppendLine(boundary);
sb1.Append("");
sb1.Append("Content-Disposition: form-data; name=\"");
sb1.Append(fileFormName);
sb1.Append("\"");
sb1.AppendLine();
sb1.AppendLine();
sb1.AppendLine();
StringBuilder sb2 = new StringBuilder();
sb2.Append("--");
sb2.AppendLine(boundary);
sb2.Append("");
sb2.Append("Content-Disposition: form-data; name=\"");
sb2.Append(fileFormName);
sb2.Append("\"; filename=\"");
sb2.Append(Path.GetFileName(uploadfile));
sb2.Append("\"");
sb2.AppendLine();
sb2.Append("Content-Type: ");
sb2.AppendLine(contenttype);
sb2.AppendLine();
string postHeader1 = sb1.ToString();
byte[] postHeaderBytes1 = Encoding.UTF8.GetBytes(postHeader1);
string postHeader2 = sb2.ToString();
byte[] postHeaderBytes2 = Encoding.UTF8.GetBytes(postHeader2);
// Build the trailing boundary string as a byte array
// ensuring the boundary appears on a line by itself
byte[] boundaryBytes = Encoding.ASCII.GetBytes("--" + boundary + "");
byte[] boundaryBytes1 = Encoding.ASCII.GetBytes(Environment.NewLine + "--" + boundary + "--");
FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
long length = postHeaderBytes1.Length + postHeaderBytes2.Length + fileStream.Length + boundaryBytes1.Length;
webrequest.ContentLength = length;
Stream requestStream = webrequest.GetRequestStream();
// Write out our post header
requestStream.Write(postHeaderBytes1, 0, postHeaderBytes1.Length);
requestStream.Write(postHeaderBytes2, 0, postHeaderBytes2.Length);
// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
// Write out the trailing boundary
requestStream.Write(boundaryBytes1, 0, boundaryBytes1.Length);
}
public static void UploadFileEx1(HttpWebRequest webrequest, string uploadfile, string fileFormName, string contenttype, string boundary)
{
// Build up the post message header
string part1 = string.Format(@"--{0}
Content-Disposition: form-data; name='filebutton'
",boundary);
string part2 = string.Format(@"--{0}
Content-Disposition: form-data; name='filebutton'; filename='AT1-AT-ACCEPTANCE-20150401-TO-20150430.CSV'
Content-Type: application/vnd.ms-excel
2,10.9800,1,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
MS_TRANSACTION_ID,ACTIVITY_DATE,ACTIVITY_ID,ACTIVITY_TYPE,PARENT_MO_ACTIVITY_ID,PARENT_MS_ACTIVITY_ID,TAX_AMOUNT,GROSS_AMOUNT,CURRENCY,PRODUCT_ID,PRODUCT_NAME,AUTHORIZATION_ID,REFUND_AMOUNT,REFUND_REASON,REFUND_COMMENT,TAX_CITY_NAME,TAX_CITY_TAX,TAX_CITY_TAX_RATE,TAX_CITY_TAX_TYPE,TAX_COUNTY_CODE,TAX_COUNTY_NAME,TAX_COUNTY_TAX,TAX_COUNTY_TAX_RATE,TAX_COUNTY_TAX_TYPE,TAX_STATE_NAME,TAX_STATE_TAX,TAX_STATE_TAX_RATE,TAX_STATE_TAX_TYPE,TAX_COUNTRY_NAME,TAX_COUNTRY_TAX,TAX_COUNTRY_TAX_RATE,TAX_COUNTRY_TAX_TYPE,TAX_CATEGORY,TAX_ZIP,ACCEPTANCE_DATE,REMITTANCE_AMOUNT,REMITTANCE_REVSHARE_AMOUNT,REMITTANCE_REVSHARE_RULE,MS_TAX_AMOUNT
C636F9CB-D5C2-497B-8FA4-9D4EE66725B5,4/6/2015 7:26:58 AM,4/6/2015 7:26:58 AM,1,,,1.6700,9.9900,EUR,,,,,,,,,,,,,,,,,,,,,,,,,,6/28/2015 6:12:31 AM,7.0700,1.2500,8,0
60404C79-2F27-49B9-8224-55FA5A7E6BE5,4/4/2015 5:29:36 AM,4/4/2015 5:29:36 AM,1,,,0.1700,0.9900,EUR,,,,,,,,,,,,,,,,,,,,,,,,,,6/28/2015 6:12:31 AM,0.7000,0.1200,8,0
", boundary);
byte[] postHeaderBytes1 = Encoding.UTF8.GetBytes(part1);
byte[] postHeaderBytes2 = Encoding.UTF8.GetBytes(part2);
// Build the trailing boundary string as a byte array
// ensuring the boundary appears on a line by itself
byte[] boundaryBytes = Encoding.ASCII.GetBytes("--" + boundary + "");
byte[] boundaryBytes1 = Encoding.ASCII.GetBytes(Environment.NewLine + "--" + boundary + "--");
//FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
//long length = postHeaderBytes1.Length + postHeaderBytes2.Length + fileStream.Length + boundaryBytes1.Length;
//webrequest.ContentLength = length;
Stream requestStream = webrequest.GetRequestStream();
// Write out our post header
requestStream.Write(postHeaderBytes1, 0, postHeaderBytes1.Length);
requestStream.Write(postHeaderBytes2, 0, postHeaderBytes2.Length);
// Write out the file contents
//byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
//int bytesRead = 0;
//while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
// requestStream.Write(buffer, 0, bytesRead);
// Write out the trailing boundary
requestStream.Write(boundaryBytes1, 0, boundaryBytes1.Length);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace Millo.Handlers
{
public class FullPipelineMessageHandler : DelegatingHandler
{
const string _header = "full-Pipeline-Timer";
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
{
var timer = Stopwatch.StartNew();
var response = await base.SendAsync(request, token);
var elapsed = timer.ElapsedMilliseconds;
Trace.WriteLine(_header + elapsed + "msec");
response.Headers.Add(_header, elapsed + "msec");
return response;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveForward : MonoBehaviour
{
public float x = 0;
public float speed = 1f;
private void Start()
{
x = transform.localPosition.x;
}
// Update is called once per frame
void FixedUpdate()
{
x += speed;
transform.localPosition = new Vector3(x, transform.localPosition.y, transform.localPosition.z);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace ChuOngThongMinh
{
public partial class BeeOBM : UserControl
{
public BeeOBM()
{
InitializeComponent();
BeeFly();
}
public void BeeFly()
{
StbFlying.RepeatBehavior = RepeatBehavior.Forever;
StbFlying.Begin();
}
public void BeeTired()
{
StbTired.RepeatBehavior = RepeatBehavior.Forever;
StbTired.Begin();
}
public void BeeStrong()
{
StbTired.Stop();
}
/// <summary>
/// Bee Drop Ball
/// </summary>
/// <param name="to">asign value "To" in DoubleAnimation</param>
public void BeeDropBall(double toAsigned)
{
daDropballNumber.To = toAsigned;
daDropballText.To = toAsigned;
stbDropBall.Begin();
stbDropBall.Completed += new EventHandler(stbDropBall_Completed);
}
public void BeeLostBall()
{
imgNumber.Visibility = Visibility.Collapsed;
tblNumber.Visibility = Visibility.Collapsed;
}
public void BeeGetBall()
{
imgNumber.Visibility = Visibility.Visible;
tblNumber.Visibility = Visibility.Visible;
}
void stbDropBall_Completed(object sender, EventArgs e)
{
stbDropBall.Stop();
this.BeeStrong();
}
public void AddNumberToBall(string _number)
{
tblNumber.Text = _number;
}
}
} |
//Class generated
class MyClass1
{
public string MyProperty1 {get;set;}
public string MyProperty2 {get;set;}
}
//Class generated
class MyClass2
{
public string MyProperty1 {get;set;}
public string MyProperty2 {get;set;}
}
|
using Dominio;
using Entidades;
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 Vistas
{
public partial class Frm_Materias : Form
{
public Frm_Materias()
{
InitializeComponent();
}
private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
{
}
private void Frm_Matriculas_Load(object sender, EventArgs e)
{
listarCarreras();
listarMaterias();
listarDocentes();
}
private void listarCarreras()
{
CarreraModel carreraModel = new CarreraModel();
this.cmb_carrera.DataSource = carreraModel.listarCarreras();
this.cmb_carrera.DisplayMember = "carrera";
this.cmb_carrera.ValueMember = "idCarrera";
}
private void listarMaterias()
{
MateriaModel materiaModel = new MateriaModel();
this.dgv_Materias.DataSource = materiaModel.listarMaterias();
}
private void listarDocentes()
{
DocenteModel docenteModel = new DocenteModel();
this.dgv_Docentes.DataSource = docenteModel.listarDocentes();
}
private void txt_BuscarMateria_TextChanged(object sender, EventArgs e)
{
MateriaModel materiaModel = new MateriaModel();
try
{
if (this.chk_CodigoMateria.Checked == true && this.chk_NombreMateria.Checked == false)
{
dgv_Materias.DataSource = materiaModel.filtrarMaterias("XCodigo", txt_BuscarMateria.Text);
}
if (this.chk_NombreMateria.Checked == true && this.chk_CodigoMateria.Checked == false)
{
dgv_Materias.DataSource = materiaModel.filtrarMaterias("XNombre", txt_BuscarMateria.Text);
}
}
catch (Exception ex)
{
MessageBox.Show("Error cuando Filtras" + ex.Message, "Atencion", MessageBoxButtons.OK, MessageBoxIcon.Warning);
throw;
}
}
private void chk_CodigoMateria_CheckedChanged(object sender, EventArgs e)
{
if (this.chk_CodigoMateria.Checked == true)
{
this.chk_NombreMateria.Checked = false;
this.chk_Docente.Checked = false;
this.chk_Carrera.Checked = false;
}
}
private void chk_NombreMateria_CheckedChanged(object sender, EventArgs e)
{
if (this.chk_NombreMateria.Checked == true)
{
this.chk_CodigoMateria.Checked = false;
this.chk_Docente.Checked = false;
this.chk_Carrera.Checked = false;
}
}
private void txt_BuscarAlumno_TextChanged(object sender, EventArgs e)
{
AlumnoModel alumnoModel = new AlumnoModel();
try
{
if (this.chk_Legajo.Checked == true && this.chk_Apellido.Checked == false)
{
dgv_Docentes.DataSource = alumnoModel.filtrarAlumnos("XLU", txt_BuscarAlumno.Text);
}
if (this.chk_Apellido.Checked == true && this.chk_Legajo.Checked == false)
{
dgv_Docentes.DataSource = alumnoModel.filtrarAlumnos("XNombre", txt_BuscarAlumno.Text);
}
}
catch (Exception ex)
{
MessageBox.Show("Error cuando Filtras" + ex.Message, "Atencion", MessageBoxButtons.OK, MessageBoxIcon.Warning);
throw;
}
}
private void chk_AlumnoAlumno_CheckedChanged(object sender, EventArgs e)
{
if (this.chk_Apellido.Checked == true)
{
this.chk_Legajo.Checked = false;
}
}
private void chk_LU_CheckedChanged(object sender, EventArgs e)
{
if (this.chk_Legajo.Checked == true)
{
this.chk_Apellido.Checked = false;
}
}
private void pic_AgregarMatricula_Click(object sender, EventArgs e)
{
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void dgv_Carreras_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
|
namespace DnDPlayerCompanion.Enums
{
public enum AbilityEnum
{
Strength,
Dexterity,
Constitution,
Intelligence,
Wisdom,
Charisma
}
public enum AbilityModEnum
{
StrMod,
DexMod,
ConMod,
IntMod,
WisMod,
ChaMod
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class NavBoatControl : BoatBase {
Rigidbody body;
public enum BoatSideFacingWind {Port, Starboard};
public static NavBoatControl s_instance;
public ParticleSystem left, right;
float currThrust = 0f;
float weakThrust = 150f, strongThrust = 2500f;
float angleToAdjustTo;
float turnStrength = 5f, weakTurnStrength = 4f, strongTurnStrength = 5f;
float turningRate = 60f;
float rudderRotation =40f;
float deadZone = 45f;
Quaternion comeAboutStart, comeAboutEnd;
Quaternion targetRudderRotation = Quaternion.identity;
public bool canMove = false;
public AudioSource correct;
public Animator boatKeel;
public GameObject arrow;
public GameObject rudderR, rudderL;
public GameObject redNavObj, greenNavObj;
public Transform red1,red2,green1,green2;
public Text pointOfSail;
void Start () {
body = GetComponent<Rigidbody>();
}
void Awake() {
if (s_instance == null) {
s_instance = this;
}
else {
Destroy(gameObject);
}
}
void Update () {
MastRotation();
//add keeling into the boat rotation
float animatorBlendVal;
if (angleWRTWind < 360f && angleWRTWind > 180f) {
animatorBlendVal = (angleWRTWind-180f)/360f;
}
else {
animatorBlendVal = (angleWRTWind/360f + .5f);
}
if ((angleWRTWind < 360f && angleWRTWind > 315f) ||
(angleWRTWind > 0f && angleWRTWind < 45f)) {
pointOfSail.text = "In Irons";
}
else if ((angleWRTWind < 315f && angleWRTWind > 293f) ||
(angleWRTWind > 0f && angleWRTWind < 45f)) {
pointOfSail.text = "Close-Hauled Starboard Tack";
}
else if ((angleWRTWind < 293f && angleWRTWind > 270f) ||
(angleWRTWind > 0f && angleWRTWind < 45f)) {
pointOfSail.text = "Close Reach Starboard Tack";
}
else if ((angleWRTWind < 270f && angleWRTWind > 240f) ||
(angleWRTWind > 0f && angleWRTWind < 45f)) {
pointOfSail.text = "Beam Reach Starboard Tack";
}
else if ((angleWRTWind < 240f && angleWRTWind > 190f) ||
(angleWRTWind > 0f && angleWRTWind < 45f)) {
pointOfSail.text = "Broad Reach Starboard Tack";
}
else if (angleWRTWind < 190f && angleWRTWind > 170f) {
pointOfSail.text = "Run";
}
else if (angleWRTWind > 120f && angleWRTWind < 170f) {
pointOfSail.text = "Broad Reach Port Tack";
}
else if (angleWRTWind > 90f && angleWRTWind < 120f) {
pointOfSail.text = "Beam Reach Port Tack";
}
else if (angleWRTWind > 66f && angleWRTWind < 90f) {
pointOfSail.text = "Close Reach Port Tack";
}
else if (angleWRTWind > 45f && angleWRTWind < 66f){
pointOfSail.text = "Close-Hauled Port Tack";
}
boatKeel.SetFloat("rotation", animatorBlendVal);
if (Mathf.Abs(Vector3.Angle(WindManager.s_instance.directionOfWind, transform.forward)) < deadZone) {
if(currThrust > 0) {
currThrust -= 10f;
}
else {
currThrust = 0;
left.enableEmission = false;
right.enableEmission = false;
}
turnStrength = weakTurnStrength;
}
else {
left.enableEmission = true;
right.enableEmission = true;
if (currThrust < strongThrust) {
currThrust += 10f;
}
else {
currThrust = strongThrust;
}
turnStrength = strongTurnStrength;
}
print (currThrust + "CT");
if (NavManager.s_instance.gameState == NavManager.GameState.Win) {
arrow.SetActive(false);
}
}
void FixedUpdate () {
if (canMove) {
if(Input.GetKey(KeyCode.LeftArrow)) {
body.AddRelativeTorque (-Vector3.up*turnStrength);
targetRudderRotation = Quaternion.Euler(0, rudderRotation,0);
}
else if(Input.GetKey(KeyCode.RightArrow)) {
body.AddRelativeTorque (Vector3.up*turnStrength);
targetRudderRotation = Quaternion.Euler(0, -rudderRotation,0);
}
else {
targetRudderRotation = Quaternion.identity;
}
rudderR.transform.localRotation = Quaternion.RotateTowards(rudderR.transform.localRotation, targetRudderRotation, turningRate * Time.deltaTime);
rudderL.transform.localRotation = Quaternion.RotateTowards(rudderL.transform.localRotation, targetRudderRotation, turningRate * Time.deltaTime);
body.AddForce (transform.forward * currThrust);
}
}
void OnTriggerEnter(Collider other) {
// print (other.tag + " " + NavManager.s_instance.ReturnCurrNavPointName());
if (other.tag == "NavTarget" && other.name == NavManager.s_instance.ReturnCurrNavPointName() && Vector3.Distance(transform.position, other.transform.position) <100f) {
NavManager.s_instance.SwitchNavigationPoint();
correct.Play();
}
if (other.tag == "CollisionObject") {
body.AddForce (transform.forward * -1 * currThrust);
}
}
void OnTriggerStay(Collider other){
if (other.tag == "collisionObject") {
body.AddForce(transform.forward * -1 * currThrust);
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Requestrr.WebApi.Controllers.DownloadClients.Ombi
{
public class SaveOmbiTvShowsSettingsModel : OmbiSettingsModel
{
[Required]
public string Restrictions { get; set; }
}
} |
using System.IO;
namespace Vantage.Automation.VaultUITest.Helpers
{
public static class FileUtility
{
public static void CreateDirectoryIfNotExists(string path)
{
Directory.CreateDirectory(path);
}
public static void CreateFileOfSize(string path, long sizeInBytes, FileMode mode = FileMode.Create, FileAccess access = FileAccess.Write,
FileShare share = FileShare.None)
{
using (var fs = new FileStream(path, mode, access, share))
{
fs.SetLength(sizeInBytes);
}
}
public static void RemoveContents(string directory)
{
Log.TestLog.Info($"Trying to clean {directory} contents");
if (Directory.Exists(directory))
{
DirectoryInfo di = new DirectoryInfo(directory);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
Log.TestLog.Info($"{directory} is empty now");
}
else
{
Log.TestLog.Info($"Directory {directory} does not exist");
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using samsung.sedac.alligatormanagerproject.Api.Entities;
namespace samsung.sedac.alligatormanagerproject.Api.DataConfig
{
public class DepartamentosConfiguration : IEntityTypeConfiguration<Departamentos>
{
public void Configure(EntityTypeBuilder<Departamentos> builder)
{
builder.ToTable("Departamentos");
builder.HasKey(dep => dep.Id);
builder.Property(dep => dep.Name)
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
builder.HasMany<Users>()
.WithOne()
.HasForeignKey(dep => dep.DepartamentoId)
.IsRequired();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using challengeApp.DataAccess.Abstract;
using challengeApp.Entities;
namespace challengeApp.DataAccess.Concrete.EntityFrameworkCore
{ //Product'a özel ekstra metotları tanımlayacağımız alandır.
public class EfCoreProductRepository : EfCoreGenericRepository<Product, ChallengeContext>, IProductDal
{
public List<Product> GetSearch(string search)
{
using (var context =new ChallengeContext())
{
var products = context.Products.Where(i => i.İsDone && (i.ProductName.Contains(search) || i.ProductDefinition.Contains(search))).AsQueryable();
return products.ToList();
}
}
public List<Product> GetSort(string sortOrder)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Web.Areas.Admin.ViewModels
{
public class CourseEnrollmentViewModel
{
[Required, Display(Name = "Student"), DataType("UserID")]
public string UserId { get; set; }
[HiddenInput]
public string CourseId { get; set; }
[HiddenInput]
public DateTime? PassedDate { get; set; }
}
} |
using cosmetic_hub__e_shopping_system_.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace cosmetic_hub__e_shopping_system_.Interfaces
{
public interface IShoppingCartItemsRepository
{
IEnumerable<ShoppingCartItems> GetAllShoppingItems();
void AddShoppingItems(ShoppingCartItems shoppingCartItem);
void SaveShoppingItems();
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ApplicationCore.Entities.Basket
{
public class ShoppingCartItem
{
public int ShoppingCartItemId { get; set; }
public string ShoppingCartId { get; set; }
public Cosmetics Cosmetics { get; set; }
public int Amount { get; set; }
}
}
|
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NopSolutions.NopCommerce.BusinessLogic.Products.Specs;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.Colors;
namespace NopSolutions.NopCommerce.Web.Administration.Modules
{
public partial class SpecificationAttributeOptionAddControl : BaseNopAdministrationUserControl
{
private bool IsColor
{
get
{
SpecificationAttribute sa = SpecificationAttributeManager.GetSpecificationAttributeByID(SpecificationAttributeID);
return (sa != null && sa.Name.Equals("цвет", StringComparison.CurrentCultureIgnoreCase));
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsColor)
{
ToolTipLabelColor.Visible = true;
txtColorArgb.Visible = true;
cusCustom.Enabled = true;
FileUploadControl.Visible = true;
}
hlBack.NavigateUrl = "~/Administration/SpecificationAttributeDetails.aspx?SpecificationAttributeID=" + SpecificationAttributeID;
}
protected void AddButton_Click(object sender, EventArgs e)
{
if (Page.IsValid && IsValidUpload())
{
try
{
SpecificationAttributeOption sao = null;
if (IsColor)
{
int colorArgb = -1;
if(!String.IsNullOrEmpty(txtColorArgb.Text))
{
colorArgb = Int32.Parse(txtColorArgb.Text, System.Globalization.NumberStyles.AllowHexSpecifier);
}
ColorManager.InsertColor(txtNewOptionName.Text, colorArgb);
ColorItem colorItem = ColorManager.GetColorByColorName(txtNewOptionName.Text);
Upload(colorItem);
}
sao = SpecificationAttributeManager.InsertSpecificationAttributeOption(SpecificationAttributeID, txtNewOptionName.Text, txtNewOptionDisplayOrder.Value);
Response.Redirect("SpecificationAttributeDetails.aspx?SpecificationAttributeID=" + sao.SpecificationAttributeID.ToString());
}
catch (Exception exc)
{
ProcessException(exc);
}
}
}
public int SpecificationAttributeID
{
get
{
return CommonHelper.QueryStringInt("SpecificationAttributeID");
}
}
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = ColorManager.GetColorByColorName(txtNewOptionName.Text) == null;
}
private bool IsValidUpload()
{
if (IsColor)
{
if (FileUploadControl.HasFile)
{
if (FileUploadControl.PostedFile.ContentType != "image/jpeg")
{
ProcessException(new Exception("Допустим только файлы jpeg!"));
return false;
}
if (FileUploadControl.PostedFile.ContentLength > 5242880)
{
ProcessException(new Exception("Файл должен быть меньше чем 5 Mb!"));
return false;
}
}
else if (String.IsNullOrEmpty(txtColorArgb.Text))
{
ProcessException(new Exception("Выберите цвет или палитру"));
return false;
}
}
return true;
}
protected void Upload(ColorItem item)
{
try
{
if (FileUploadControl.HasFile)
{
string directory = Server.MapPath("~/images/palette/");
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string newFileName = String.Format("{0}{1}{2}", directory, item.ColorID,
Path.GetExtension(FileUploadControl.FileName));
if(File.Exists(newFileName))
{
File.Delete(newFileName);
}
FileUploadControl.SaveAs(newFileName);
}
}
catch (Exception ex)
{
ProcessException(ex);
}
}
}
} |
using System;
namespace RockPaperScissors
{
class Program
{
public static bool loop = true;
public static int wins;
public static int totalwins;
public static int losses;
public static int totallosses;
public static int ties;
public static int totalties;
public static int totalrounds;
public static int roundnum;
public static int compguess;
public static string playerthrow;
public static string compthrow;
public static Random random = new Random();
static void Main(string[] args)
{
// KEWL ASCII TITLE
Console.WriteLine(@" _ _ ");
Console.WriteLine(@" | | (_) ");
Console.WriteLine(@" _ __ ___ ___| | __ _ __ __ _ _ __ ___ _ __ ___ ___ _ ___ ___ ___ _ __ ___ ");
Console.WriteLine(@"| '__/ _ \ / __| |/ / | '_ \ / _` | '_ \ / _ \ '__| / __|/ __| / __/ __|/ _ \| '__/ __|");
Console.WriteLine(@"| | | (_) | (__| < | |_) | (_| | |_) | __/ | \__ \ (__| \__ \__ \ (_) | | \__ \");
Console.WriteLine(@"|_| \___/ \___|_|\_\ | .__/ \__,_| .__/ \___|_| |___/\___|_|___/___/\___/|_| |___/");
Console.WriteLine(@" | | | | ");
Console.WriteLine(@" |_| |_| ");
Console.WriteLine("\n");
Console.WriteLine("Program by: William Pasbrig Title generated at: \'http://patorjk.com/software/taag\'");
Console.WriteLine("\n");
// Press any key to start...
System.Threading.Thread.Sleep(1000);
Console.WriteLine("\n");
Console.WriteLine("Press enter to start . . .");
_ = Console.ReadLine();
// call game method
Game();
while (loop == true)
{
System.Threading.Thread.Sleep(1000);
Console.WriteLine($"\nSince running this program, we've played a total of {totalrounds} rounds.\n");
System.Threading.Thread.Sleep(500);
Console.WriteLine($"Over which you have won {totalwins} times and lost {totallosses} times.\n");
System.Threading.Thread.Sleep(500);
Console.WriteLine($"You have also managed to tie {totalties} times.");
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Would you like to play again? Y/N");
string input = Console.ReadLine();
if (input.ToLower() == "y")
{
Game();
}
else
{
Console.WriteLine("Thank you for playing! This program will now exit.");
break;
}
}
// after game, ask if they want to play again, else quit.
}
static int NumRounds()
{
while (true)
{
Console.WriteLine("How many rounds would you like to play? Enter a number between 1 to 10");
string input = Console.ReadLine();
if (Int32.TryParse(input, out int result))
{
if (result > 0 && result < 11)
{
return result;
}
}
else
{
Console.WriteLine("Input is not valid. This program will now exit.");
System.Threading.Thread.Sleep(2000);
Environment.Exit(0);
}
}
}
static void Game()
{
wins = 0;
losses = 0;
ties = 0;
// determine number of rounds
Console.Clear();
roundnum = NumRounds();
System.Threading.Thread.Sleep(1000);
if (roundnum == 1)
{
Console.WriteLine($"We will be playing {roundnum} round.");
}
else
{
Console.WriteLine($"We will be playing {roundnum} rounds.");
}
System.Threading.Thread.Sleep(2000);
for (int i = 0; i < roundnum; i++)
{
// ask user for choice
while (true)
{
Console.Clear();
Console.WriteLine("Make your throw! Type \'Rock\', \'Paper\', or \'Scissors\'.");
string input = Console.ReadLine().ToLower();
if (input == "rock" || input.ToLower() == "paper" || input.ToLower() == "scissors")
{
playerthrow = input;
break;
}
else if (input.ToLower() == "gun")
{
Console.WriteLine("Hey that's cheating! Try again.");
}
else
{
Console.WriteLine("Input is not valid. Try again.");
}
}
// computer randomly makes choice
compguess = random.Next(3);
switch (compguess)
{
case 0:
compthrow = "rock";
Console.WriteLine("I throw \'Rock\'");
break;
case 1:
compthrow = "paper";
Console.WriteLine("I throw \'Paper\'");
break;
case 2:
compthrow = "scissors";
Console.WriteLine("I throw \'Scissors\'");
break;
}
System.Threading.Thread.Sleep(1000);
Console.WriteLine($"\nSo you threw {playerthrow} and I threw {compthrow} . . .\n");
System.Threading.Thread.Sleep(1000);
// compare the two values using... something?
bool x = true;
switch (x)
{
case true when playerthrow == compthrow:
Console.WriteLine("It's a tie!");
ties++;
break;
case true when playerthrow == "rock" && compthrow == "scissors":
case true when playerthrow == "paper" && compthrow == "rock":
case true when playerthrow == "scissors" && compthrow == "paper":
Console.WriteLine("Wow, you win!");
wins++;
break;
case true when playerthrow == "rock" && compthrow == "paper":
case true when playerthrow == "paper" && compthrow == "scissors":
case true when playerthrow == "scissors" && compthrow == "rock":
Console.WriteLine("It look's like I have won!");
losses++;
break;
}
System.Threading.Thread.Sleep(2000);
// track rounds played and WLT. print out results
if (i == 0)
{
Console.WriteLine($"\nSo far . . . we have played {i + 1} round");
}
else
{
Console.WriteLine($"\nSo far . . . we have played {i + 1} rounds");
}
System.Threading.Thread.Sleep(1000);
Console.Write($"You have won {wins} times.");
System.Threading.Thread.Sleep(500);
Console.Write($" You have lost {losses} times.");
System.Threading.Thread.Sleep(500);
Console.Write($" We have tied {ties} times.");
System.Threading.Thread.Sleep(2000);
if ((i + 1) < roundnum)
{
Console.WriteLine("\n\nLet's throw again!");
System.Threading.Thread.Sleep(2000);
}
}
// after all rounds complete, declare winner
System.Threading.Thread.Sleep(1000);
Console.Clear();
Console.WriteLine("Looks like we have completed all rounds.\n");
System.Threading.Thread.Sleep(1000);
Console.WriteLine($"You have won {wins}, I won {losses} times, afterwhich we tied {ties} times.\n");
System.Threading.Thread.Sleep(1000);
if (wins > losses)
{
Console.WriteLine("You are the RPS Champion!");
}
else if (wins < losses)
{
Console.WriteLine("I have bested you! I WIN!");
}
else if (wins == losses)
{
Console.WriteLine("Amazing, after all of that we still are tied!");
}
totalwins += wins;
totallosses += losses;
totalties += ties;
totalrounds += roundnum;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace challenge
{
class Program
{
static void Main(string[] args)
{
string input;
int number1 = 1;
int number2 = 1;
Console.WriteLine("type 1 for a Quadrilateral shape");
Console.WriteLine("type 2 for a Triangle shape");
Console.WriteLine("type anythig elsa to quit");
input = Console.ReadLine();
Console.Clear();
if (input == "1")
{
Console.WriteLine("type 1 for a Square shape");
Console.WriteLine("type 2 for a Rectangle shape");
Console.WriteLine("type anythig elsa to quit");
input = Console.ReadLine();
Console.Clear();
if (input == "1")
{
try
{
Console.WriteLine("what Lenght do you want the sides to be?");
number1 = int.Parse(Console.ReadLine());
if (number1 >= 1)
{
}
else
{
throw new numberIslessThenOne();
}
}
catch (numberIslessThenOne)
{
Console.WriteLine("Number can't be less then one!");
Console.ReadLine();
Environment.Exit(0);
}
catch (Exception)
{
Console.WriteLine("Please wite a number");
Console.ReadLine();
Environment.Exit(0);
}
Console.WriteLine("The Perimeter is " + (number1 * 4));
Console.WriteLine("The Area is " + (number1 * number1));
Console.ReadLine();
}
else if (input == "2")
{
try
{
Console.Write("what Lenght do you want the first set of side to be?");
number1 = int.Parse(Console.ReadLine());
Console.Write("what Lenght do you want the sceond set of side to be?");
number2 = int.Parse(Console.ReadLine());
if (number2 >= 1 && number1 >= 1)
{
}
else
{
throw new numberIslessThenOne();
}
}
catch (numberIslessThenOne)
{
Console.WriteLine("Number can't be less then one!");
Console.ReadLine();
Environment.Exit(0);
}
catch (Exception)
{
Console.WriteLine("Please wite a number");
Console.ReadLine();
Environment.Exit(0);
}
Console.WriteLine("The Perimeter is " + (number1 * 2 + number2 * 2));
Console.WriteLine("The Area is " + (number1 * number2));
Console.ReadLine();
}
else
{
Environment.Exit(0);
}
}
else if (input == "2")
{
Console.WriteLine("type 1 for a Right Angle Triangle shape");
Console.WriteLine("type 2 for a Equilateral Triangle shape");
Console.WriteLine("type anythig elsa to quit");
input = Console.ReadLine();
Console.Clear();
if (input == "1")
{
try
{
Console.Write("what Lenght do you want the first set of side to be?");
number1 = int.Parse(Console.ReadLine());
Console.Write("what Lenght do you want the sceond set of side to be?");
number2 = int.Parse(Console.ReadLine());
if (number2 >= 1 && number1 >= 1)
{
}
else
{
throw new numberIslessThenOne();
}
}
catch (numberIslessThenOne)
{
Console.WriteLine("Number can't be less then one!");
Console.ReadLine();
Environment.Exit(0);
}
catch (Exception)
{
Console.WriteLine("Please wite a number");
Console.ReadLine();
Environment.Exit(0);
}
Console.WriteLine("The hypotenuse is " + (Math.Sqrt(number1 * number1 + number2 * number2)));
Console.WriteLine("The Perimeter is " + (number1 + number2 + (Math.Sqrt(number1 * number1 + number2 * number2))));
Console.WriteLine("The Area is " + (number1 * number2 / 2));
Console.ReadLine();
}
else if (input == "2")
{
try
{
Console.WriteLine("what Lenght do you want the sides to be?");
number1 = int.Parse(Console.ReadLine());
if (number1 >= 1)
{
}
else
{
throw new numberIslessThenOne();
}
}
catch (numberIslessThenOne)
{
Console.WriteLine("Number can't be less then one!");
Console.ReadLine();
Environment.Exit(0);
}
catch (Exception)
{
Console.WriteLine("Please wite a number");
Console.ReadLine();
Environment.Exit(0);
}
Console.WriteLine("The Perimeter is " + (number1 * 3));
Console.WriteLine("The Area is " + (Math.Sqrt(3f) / 4 * number1 * number1));
Console.ReadLine();
}
else
{
Environment.Exit(0);
}
}
else
{
Environment.Exit(0);
}
}
}
public class numberIslessThenOne : Exception
{
public numberIslessThenOne()
{
}
public numberIslessThenOne(string message)
: base(message)
{
}
public numberIslessThenOne(string message, Exception inner)
: base(message, inner)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DiscBagStuff.Classes
{
public class Application
{
private static MenuController _menuController = MenuController.Instance;
public static void Run()
{
_menuController.ShowMenu();
}
public static void Exit()
{
Environment.Exit(0);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
[SerializeField]
private GameObject _laserPrefab;
[SerializeField]
private GameObject _tripleShotPrefab;
[SerializeField]
private GameObject _ExplosionPrefab;
[SerializeField]
private GameObject _ShieldObject;
private GameManager _gameManager;
[SerializeField]
private GameObject[] _engines;
private int _hitCount = 0;
[SerializeField]
private float _fireRate = 0.25f;
private float _canFire = 0.0f;
public bool canTripleShot = true;
public bool speedBoostOn = true;
public bool shieldIsOn = false;
public int playerHealth = 3;
private UIManager _uiManager;
[SerializeField]
private float _speed = 5.0f;
private Spawn_Manager _spawnManager;
private AudioSource _audioSource;
[SerializeField]
private AudioClip _clip;
// Use this for initialization
void Start () {
_audioSource = GetComponent<AudioSource>();
_spawnManager = GameObject.Find("SpawnManager").GetComponent<Spawn_Manager>();
// _spawnManager.StartSpawnRoutine();
_uiManager = GameObject.Find("Canvas").GetComponent<UIManager>();
if (_uiManager != null)
{
_uiManager.UpdateLives(playerHealth);
}
transform.position = new Vector3(0, 0, 0);
_gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
if(_spawnManager != null)
{
_spawnManager.StartSpawnRoutine();
}
_hitCount = 0;
}
// Update is called once per frame
void Update () {
Movement();
if ((Input.GetKeyDown(KeyCode.Space)) || Input.GetKeyDown(KeyCode.Mouse0))
{
Shoot();
}
}
private void Shoot()
{
if (Time.time > _canFire)
{
_audioSource.Play();
if (canTripleShot)
{
Instantiate(_tripleShotPrefab, transform.position, Quaternion.identity);
}else
{
Instantiate(_laserPrefab, transform.position + new Vector3(0, 0.88f, 0), Quaternion.identity);
}
}
_canFire = Time.time + _fireRate;
}
private void Movement()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
if (speedBoostOn)
{
transform.Translate(Vector3.right * _speed * 1.50f * horizontalInput * Time.deltaTime);
transform.Translate(Vector3.up * _speed * 1.50f * verticalInput * Time.deltaTime);
}
else
{
transform.Translate(Vector3.right * _speed * horizontalInput * Time.deltaTime);
transform.Translate(Vector3.up * _speed * verticalInput * Time.deltaTime);
}
if (transform.position.x < -9.4f)
{
transform.position = new Vector3(9.2f, transform.position.y, 0);
}
else if (transform.position.x > 9.4f)
{
transform.position = new Vector3(-9.3f, transform.position.y, 0);
}
else if (transform.position.y > 4.2f)
{
transform.position = new Vector3(transform.position.x, 4.2f, 0);
}
else if (transform.position.y < -4.2f)
{
transform.position = new Vector3(transform.position.x, -4.2f, 0);
}
}
public void SpeedPowerupOn()
{
AudioSource.PlayClipAtPoint(_clip, Camera.main.transform.position);
speedBoostOn = true;
StartCoroutine(SpeedBoostPowerDownRoutine());
}
public IEnumerator SpeedBoostPowerDownRoutine()
{
yield return new WaitForSeconds(10.0f);
speedBoostOn = false;
}
public void TripleShotPowerupOn()
{
AudioSource.PlayClipAtPoint(_clip, Camera.main.transform.position);
canTripleShot = true;
StartCoroutine(TripleShotPowerDownRoutine());
}
public IEnumerator TripleShotPowerDownRoutine()
{
yield return new WaitForSeconds(5.0f);
canTripleShot = false;
}
public void ShieldPowerupOn()
{
AudioSource.PlayClipAtPoint(_clip, Camera.main.transform.position);
shieldIsOn = true;
_ShieldObject.SetActive(true);
}
public void takeDamage()
{
_hitCount++;
if (shieldIsOn == true)
{
shieldIsOn = false;
_ShieldObject.SetActive(false);
return;
}
else
{
playerHealth -= 1;
_uiManager.UpdateLives(playerHealth);
}
if (playerHealth < 1)
{
Instantiate(_ExplosionPrefab, transform.position, Quaternion.identity);
Destroy(this.gameObject);
_uiManager.ShowTitleScreen();
_gameManager.gameOver = true;
}
if (_hitCount == 1)
{
_engines[Random.Range(0,1)].SetActive(true);
} else if (_hitCount == 2 && _engines[0])
{
_engines[1].SetActive(true);
} else
{
_engines[0].SetActive(true);
}
}
}
|
using VideoServiceBL.DTOs;
namespace VideoServiceBL.Services.Interfaces
{
public interface IGenreService: IBaseService<GenreDto>
{
}
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Sqlite.Internal;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.EntityFrameworkCore.Query
{
public class NorthwindAggregateOperatorsQuerySqliteTest : NorthwindAggregateOperatorsQueryRelationalTestBase<
NorthwindQuerySqliteFixture<NoopModelCustomizer>>
{
public NorthwindAggregateOperatorsQuerySqliteTest(
NorthwindQuerySqliteFixture<NoopModelCustomizer> fixture,
ITestOutputHelper testOutputHelper)
: base(fixture)
{
ClearLog();
//Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper);
}
public override Task Sum_with_division_on_decimal(bool async)
=> Assert.ThrowsAsync<NotSupportedException>(() => base.Sum_with_division_on_decimal(async));
public override Task Sum_with_division_on_decimal_no_significant_digits(bool async)
=> Assert.ThrowsAsync<NotSupportedException>(() => base.Sum_with_division_on_decimal_no_significant_digits(async));
public override Task Average_with_division_on_decimal(bool async)
=> Assert.ThrowsAsync<NotSupportedException>(() => base.Average_with_division_on_decimal(async));
public override Task Average_with_division_on_decimal_no_significant_digits(bool async)
=> Assert.ThrowsAsync<NotSupportedException>(() => base.Average_with_division_on_decimal_no_significant_digits(async));
public override async Task Multiple_collection_navigation_with_FirstOrDefault_chained(bool async)
{
Assert.Equal(
SqliteStrings.ApplyNotSupported,
(await Assert.ThrowsAsync<InvalidOperationException>(
() => base.Multiple_collection_navigation_with_FirstOrDefault_chained(async))).Message);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButterflyCluster : MonoBehaviour
{
public Vector3 clusterDirection;
private Transform playerMesh;
private Vector3 positionBehindPlayer;
public float clusterSpeed;
[SerializeField]
float currentSpeed;
float targetSpeed;
public bool followPlayer = false;
Transform player;
float randomoffset;
void Start()
{
if(GameObject.FindGameObjectWithTag("Player") != null)
{
player = GameObject.FindGameObjectWithTag("Player").transform;
playerMesh = AnimationManager.m_instance.transform;
}
if (followPlayer)
{
clusterSpeed = 0;
}
randomoffset = Random.Range(0, 100);
}
void Update()
{
if (followPlayer)
{
if(player != null)
{
positionBehindPlayer = player.transform.position - (playerMesh.forward * 1f);
clusterDirection = (positionBehindPlayer- transform.position).normalized;
//clusterDirection = Vector3.Lerp(clusterDirection, ((positionBehindPlayer) - transform.position).normalized, Time.deltaTime * 2);
float distanceToPos = Vector3.Distance(transform.position, positionBehindPlayer);
currentSpeed = Mathf.Lerp(0, clusterSpeed, Mathf.Clamp01(distanceToPos/2));
MoveTowardsPlayer();
}
}
else
{
clusterDirection = new Vector3((Mathf.PerlinNoise(Time.time/5 + randomoffset, Time.time/5 + randomoffset) -.5f) * 2,0, (Mathf.PerlinNoise(Time.time/5 + randomoffset, Time.time/5 + randomoffset) - .5f) * 2);
//clusterDirection = transform.forward + transform.right * Mathf.PerlinNoise(Time.time, Time.time)*2;
currentSpeed = clusterSpeed;
MoveForward();
}
//currentSpeed = Mathf.Lerp(0, clusterSpeed, Time.deltaTime*2);
}
void MoveTowardsPlayer()
{
if (Vector3.Distance(transform.position, positionBehindPlayer) > 0.05f)
{
transform.position += (clusterDirection * currentSpeed * Time.deltaTime);
}
//transform.position = positionBehindPlayer;
//transform.position = Vector3.Lerp(transform.position, positionBehindPlayer, Time.deltaTime * 2);
}
void MoveForward()
{
transform.position += (clusterDirection * currentSpeed * Time.deltaTime);
}
}
|
using System;
using System.Collections.Generic;
using Kers.Models.Entities.KERScore;
namespace Kers.Models.ViewModels
{
public class KesrUserBriefViewModel{
public int Id {get;set;}
public string Name {get;set;}
public string Position {get;set;}
public string Title {get;set;}
public string Image {get;set;}
public string Phone {get;set;}
public string PlanningUnitName {get;set;}
public int PlanningUnitId {get;set;}
}
} |
using Hayalpc.Library.Repository;
namespace Hayalpc.Fatura.Data
{
public class HpUnitOfWork : HpUnitOfWork<HpDbContext>
{
public HpUnitOfWork(HpDbContext context) : base(context)
{
}
}
}
|
using System;
using Locky.Shared;
using UIKit;
using Microsoft.WindowsAzure.MobileServices;
namespace Locky.iOS
{
public partial class ViewController : UIViewController
{
bool hasLoggedIn = false;
private MobileServiceUser user;
public MobileServiceUser User
{
get{ return user; }
}
public ViewController(IntPtr handle)
: base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
signInButton.TouchUpInside += SignInButton_TouchUpInside;
}
async void SignInButton_TouchUpInside (object sender, EventArgs e)
{
try
{
user = await Passwords.client.LoginAsync(this, MobileServiceAuthenticationProvider.Facebook);
hasLoggedIn = true;
this.PerformSegue("loggedInSegue", this);
}
catch (Exception)
{
UIAlertView alert = new UIAlertView()
{
Message = "There was an error signing you in",
Title = "Error"
};
alert.AddButton("Ok");
alert.Show();
}
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
public override bool ShouldPerformSegue(string segueIdentifier, Foundation.NSObject sender)
{
if (segueIdentifier == "loggedInSegue")
{
return hasLoggedIn;
}
return true;
}
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
using Triton.Game.Mono;
[Attribute38("SpellAreaEffectInfo")]
public class SpellAreaEffectInfo : MonoClass
{
public SpellAreaEffectInfo(IntPtr address) : this(address, "SpellAreaEffectInfo")
{
}
public SpellAreaEffectInfo(IntPtr address, string className) : base(address, className)
{
}
public bool m_Enabled
{
get
{
return base.method_2<bool>("m_Enabled");
}
}
public SpellFacing m_Facing
{
get
{
return base.method_2<SpellFacing>("m_Facing");
}
}
public SpellFacingOptions m_FacingOptions
{
get
{
return base.method_3<SpellFacingOptions>("m_FacingOptions");
}
}
public Spell m_Prefab
{
get
{
return base.method_3<Spell>("m_Prefab");
}
}
public float m_SpawnDelaySecMax
{
get
{
return base.method_2<float>("m_SpawnDelaySecMax");
}
}
public float m_SpawnDelaySecMin
{
get
{
return base.method_2<float>("m_SpawnDelaySecMin");
}
}
public bool m_UseSuperSpellLocation
{
get
{
return base.method_2<bool>("m_UseSuperSpellLocation");
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Vinarish.Models;
namespace Vinarish.Data
{
public partial class TCMMSContext : DbContext
{
public TCMMSContext()
{
}
public TCMMSContext(DbContextOptions<TCMMSContext> options)
: base(options)
{
ChangeTracker.LazyLoadingEnabled = true;
}
public virtual DbSet<Department> Department { get; set; }
public virtual DbSet<Person> Person { get; set; }
public virtual DbSet<Train> Train { get; set; }
public virtual DbSet<Wagon> Wagon { get; set; }
public virtual DbSet<Category> Category { get; set; }
public virtual DbSet<StatCode> StatCode { get; set; }
public virtual DbSet<Report> Report { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Data Source=185.10.75.8;User ID=vinarish;Password=Hibernate70!;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.4-servicing-10062");
modelBuilder.Entity<Department>(entity =>
{
entity.Property(e => e.Name).IsUnicode(true);
});
modelBuilder.Entity<Person>(entity =>
{
entity.HasIndex(e => e.DepartmentId);
entity.Property(e => e.FirstName).IsUnicode(true);
entity.Property(e => e.LastName).IsUnicode(true);
entity.HasOne(d => d.Department)
.WithMany(p => p.Person)
.HasForeignKey(d => d.DepartmentId)
.HasConstraintName("FK_Persons_Department");
});
modelBuilder.Entity<Train>(entity =>
{
entity.HasIndex(e => e.TrainId).IsUnique(true);
entity.Property(e => e.TrainId).ValueGeneratedNever();
});
modelBuilder.Entity<Wagon>(entity =>
{
entity.HasIndex(e => e.TrainId);
entity.HasIndex(e => e.WagonId).IsUnique(true);
entity.Property(e => e.WagonId).ValueGeneratedNever();
entity.HasOne(d => d.Train)
.WithMany(p => p.Wagon)
.HasForeignKey(d => d.TrainId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Wagon_Train");
});
modelBuilder.Entity<Category>(entity =>
{
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.HasOne(d => d.Department)
.WithMany(p => p.Category)
.HasForeignKey(d => d.DepartmentId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Category_Department");
});
modelBuilder.Entity<StatCode>(entity =>
{
entity.HasIndex(e => e.Code).IsUnique(true);
entity.HasOne(d => d.Cat)
.WithMany(p => p.StatCode)
.HasForeignKey(d => d.CatId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Code_Cat");
});
modelBuilder.Entity<Report>(entity =>
{
entity.Property(e => e.AppendixReportId).HasDefaultValue(null);
entity.HasOne(d => d.Cat)
.WithMany(p => p.Report)
.HasForeignKey(d => d.CatId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Report_Cat");
entity.HasOne(d => d.Code)
.WithMany(p => p.Report)
.HasForeignKey(d => d.CodeId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Report_CodeId");
entity.HasOne(d => d.Place)
.WithMany(p => p.Report)
.HasForeignKey(d => d.PlaceId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Report_PlaceId");
entity.HasOne(d => d.Reporter)
.WithMany(p => p.Report)
.HasForeignKey(d => d.ReporterId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Report_Reporter");
entity.HasOne(d => d.AppendixReport)
.WithMany(p => p.AppendixReports)
.HasForeignKey(d => d.AppendixReportId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Report_AppendixReport");
entity.HasOne(d => d.Wagon)
.WithMany(p => p.Report)
.HasForeignKey(d => d.WagonId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Report_Wagon");
});
}
public DbSet<Vinarish.Models.Place> Place { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FadableTutorialStep : FTUEStep
{
public float FadeTime;
public float WaitTime;
private CanvasGroup canvasGroup;
public override IEnumerator OnExecute()
{
Hashtable hash = iTween.Hash("from", 0, "to", 1, "time", FadeTime, "onupdate", "Fade");
iTween.ValueTo(gameObject, hash);
yield return new WaitForSeconds(WaitTime);
hash = iTween.Hash("from", 1, "to", 0, "time", FadeTime, "onupdate", "Fade");
iTween.ValueTo(gameObject, hash);
yield return new WaitForSeconds(WaitTime);
OnStepExit();
}
public override void OnStepExit()
{
base.OnStepExit();
}
public override void OnStepStart()
{
base.OnStepStart();
canvasGroup = GetComponent<CanvasGroup>();
}
#region Helper MEthods
public void Fade(float newValue)
{
canvasGroup.alpha = newValue;
}
#endregion
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using DotNetNuke.Services.Installer.Packages;
#endregion
namespace DotNetNuke.Services.Installer.Writers
{
/// -----------------------------------------------------------------------------
/// <summary>
/// The LibraryPackageWriter class
/// </summary>
/// <remarks>
/// </remarks>
/// -----------------------------------------------------------------------------
public class LibraryPackageWriter : PackageWriterBase
{
public LibraryPackageWriter(PackageInfo package) : base(package)
{
BasePath = "DesktopModules\\Libraries";
AssemblyPath = "bin";
}
protected override void GetFiles(bool includeSource, bool includeAppCode)
{
base.GetFiles(includeSource, false);
}
}
}
|
using System;
using System.Web.Mvc;
using Logs.Authentication.Contracts;
using Logs.Providers.Contracts;
using Logs.Services.Contracts;
using Logs.Web.Infrastructure.Factories;
using Logs.Web.Models.Upload;
namespace Logs.Web.Controllers
{
[Authorize]
public class UploadController : Controller
{
private readonly IUserService userService;
private readonly IAuthenticationProvider authenticationProvider;
private readonly ICloudinaryFactory cloudinaryFactory;
private readonly IViewModelFactory viewModelFactory;
public UploadController(IUserService userService,
IAuthenticationProvider authenticationProvider,
ICloudinaryFactory cloudinaryFactory,
IViewModelFactory viewModelFactory
)
{
if (userService == null)
{
throw new ArgumentNullException(nameof(userService));
}
if (authenticationProvider == null)
{
throw new ArgumentNullException(nameof(authenticationProvider));
}
if (cloudinaryFactory == null)
{
throw new ArgumentNullException(nameof(cloudinaryFactory));
}
if (viewModelFactory == null)
{
throw new ArgumentNullException(nameof(viewModelFactory));
}
this.userService = userService;
this.authenticationProvider = authenticationProvider;
this.cloudinaryFactory = cloudinaryFactory;
this.viewModelFactory = viewModelFactory;
}
public ActionResult Index()
{
var userId = this.authenticationProvider.CurrentUserId;
var user = this.userService.GetUserById(userId);
var cloudinary = this.cloudinaryFactory.GetCloudinary();
var model = this.viewModelFactory.CreateUploadViewModel(cloudinary, user.ProfileImageUrl);
return this.View(model);
}
[HttpPost]
public ActionResult Index(UploadViewModel model)
{
if (ModelState.IsValid)
{
var userId = this.authenticationProvider.CurrentUserId;
this.userService.ChangeProfilePicture(userId, model.ImageUrl);
}
model.Cloudinary = this.cloudinaryFactory.GetCloudinary();
return this.View(model);
}
}
} |
//using System;
//using System.Collections;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//namespace Alfheim.FuzzyLogic.Rules.Model
//{
// class TermsChainEnumerator : IEnumerator<TermsChainListNode>
// {
// private TermsChainList chain;
// private int position;
// private TermsChainListNode CurrentNode { get; set; }
// object IEnumerator.Current {
// get
// {
// return CurrentNode;
// }
// }
// public TermsChainListNode Current
// {
// get
// {
// return CurrentNode;
// }
// }
// public TermsChainEnumerator(TermsChainList chain)
// {
// this.chain = chain;
// CurrentNode = chain.Head;
// }
// public bool MoveNext()
// {
// if (CurrentNode.ChainRuleNextCondition == null)
// return false;
// CurrentNode = CurrentNode.ChainRuleNextCondition.Node;
// return true;
// }
// public void Reset()
// {
// CurrentNode = chain.Head;
// }
// public void Dispose()
// {
// }
// }
//}
|
using Football.DAL.Entities;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Football.API.Dto
{
public class MatchBroadcastDto
{
public int Id { get; set; }
public string Name { get; set; }
public int MatchTournamentId { get; set; }
public string MatchTournamentName { get; set; }
public double DefaultPayment { get; set; }
public double Payment { get; set; }
}
}
|
using System;
using UnityEngine;
using strange.extensions.context.api;
using strange.extensions.context.impl;
using strange.extensions.dispatcher.eventdispatcher.api;
using strange.extensions.dispatcher.eventdispatcher.impl;
using strange.extensions.command.api;
using strange.extensions.command.impl;
using syscrawl.Game.Services.Levels;
using syscrawl.Game.Models.Levels;
using syscrawl.Game.Controllers.Levels;
using syscrawl.Game.Controllers.Player;
using syscrawl.Game.Models;
using syscrawl.Game.Views.Nodes;
using syscrawl.Game.Views.Levels;
using syscrawl.Game.Controllers;
using syscrawl.Game.Camera;
namespace syscrawl.Game
{
public class GameContext : MVCSContext
{
public GameContext(MonoBehaviour view)
: base(view)
{
}
public GameContext(MonoBehaviour view, ContextStartupFlags flags)
: base(view, flags)
{
}
// Unbind the default EventCommandBinder and rebind the SignalCommandBinder
protected override void addCoreComponents()
{
base.addCoreComponents();
injectionBinder.Unbind<ICommandBinder>();
injectionBinder.Bind<ICommandBinder>().To<SignalCommandBinder>().ToSingleton();
}
// Override Start so that we can fire the StartSignal
override public IContext Start()
{
base.Start();
var startSignal = injectionBinder.GetInstance<GameStartSignal>();
startSignal.Dispatch();
return this;
}
protected override void mapBindings()
{
//Models
injectionBinder.Bind<ILevel>().To<Level>().ToSingleton();
injectionBinder.Bind<IPlayer>().To<Player>().ToSingleton();
//Commands & Signals
commandBinder.Bind<GameStartSignal>().To<GameStartCommand>();
commandBinder.Bind<GenerateLevelSignal>().To<GenerateLevelSceneCommand>();
commandBinder.Bind<PositionNodesSignal>().To<PositionNodesCommand>();
commandBinder.Bind<CreateNodeSignal>().To<CreateNodeCommand>();
commandBinder.Bind<CreateNodeConnectionSignal>().To<CreateNodeConnectionCommand>();
commandBinder.Bind<PlayerMoveToSignal>().To<PlayerMoveToCommand>();
//Singleton signals
injectionBinder.Bind<PlayerMovedSignal>().ToSingleton();
injectionBinder.Bind<LevelGeneratedSignal>().ToSingleton();
injectionBinder.Bind<NodeWrapperClickedSignal>().ToSingleton();
//Mediation
mediationBinder.Bind<LevelSceneView>().To<LevelSceneMediator>();
//Services
injectionBinder.Bind<ILevelGenerator>().To<SpecificLevelGenerator>();
injectionBinder.Bind<INodePositionServices>().To<NodePositionServices>().ToSingleton();
}
protected override void postBindings()
{
var context = (contextView as GameObject);
var cam = context.GetComponentInChildren<UnityEngine.Camera>();
injectionBinder.Bind<UnityEngine.Camera>().ToValue(cam);
var configs = context.GetComponentInChildren<Configs>();
injectionBinder.Bind<Configs>().ToValue(configs);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace UrTLibrary.Bsp.Elements
{
public class Vertex : BspElement
{
public float[] Position;
public float[,] TextureCoordinates;
public float[] Normal;
public byte[] Color;
public Vertex()
{
base.ElementSize = 44;
}
internal override void Read(BinaryReader reader)
{
this.Position = new float[3];
for (int i = 0; i < 3; i++)
this.Position[i] = reader.ReadSingle();
this.TextureCoordinates = new float[2, 2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
this.TextureCoordinates[i, j] = reader.ReadSingle();
this.Normal = new float[3];
for (int i = 0; i < 3; i++)
this.Normal[i] = reader.ReadSingle();
this.Color = reader.ReadBytes(4);
}
internal override void Write(BinaryWriter writer)
{
foreach (float f in this.Position)
writer.Write(f);
foreach (float f in this.TextureCoordinates)
writer.Write(f);
foreach (float f in this.Normal)
writer.Write(f);
writer.Write(this.Color);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine.Rendering;
public class ECSManagerTwo : MonoBehaviour
{
private EntityManager manager;
public GameObject sheepPrefab;
private const int numSheep = 105000;
private const float range = 40;
private void Start()
{
manager = World.DefaultGameObjectInjectionWorld.EntityManager;
var settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);
var prefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(sheepPrefab, settings);
for (int i = 0; i < numSheep; i++)
{
var instance = manager.Instantiate(prefab);
var position = transform.TransformPoint(new float3(UnityEngine.Random.Range(-range, range), UnityEngine.Random.Range(0, range*2), UnityEngine.Random.Range(-range, range)));
manager.SetComponentData(instance, new Translation {Value = position});
manager.SetComponentData(instance, new Rotation {Value = new quaternion(0,0,0,0)});
}
}
}
|
using System;
using System.Text;
namespace Grisaia.Extensions {
partial class StringExtensions {
#region ToNullTerminated
/// <summary>
/// Returns a new string that is ended at the first index of a null character.
/// </summary>
/// <param name="s">The string to null terminate.</param>
/// <returns>The null terminated string.-or- <paramref name="s"/> if there was no null character.</returns>
///
/// <exception cref="ArgumentNullException">
/// <paramref name="s"/> is null.
/// </exception>
public static string ToNullTerminated(this string s) {
if (s == null)
throw new ArgumentNullException(nameof(s));
int index = s.IndexOf('\0');
return (index != -1 ? s.Substring(0, index) : s);
}
/// <summary>
/// Returns a new string that is ended at the first index of a null character in the array.
/// </summary>
/// <param name="chars">The character array to null terminate.</param>
/// <returns>
/// The null terminated string.-or- the full character array as a string if there was no null character.
/// </returns>
///
/// <exception cref="ArgumentNullException">
/// <paramref name="chars"/> is null.
/// </exception>
public static string ToNullTerminatedString(this char[] chars) {
return new string(chars, 0, chars.IndexOfNullTerminator());
}
/// <summary>
/// Returns a new string that is ended at the first index of a 0 byte in the array.
/// </summary>
/// <param name="bytes">The byte array to encode and null terminate.</param>
/// <param name="encoding">The encoding to use for the bytes to get the string.</param>
/// <returns>
/// The null terminated string.-or- the full encoded string if there was no null character.
/// </returns>
///
/// <exception cref="ArgumentNullException">
/// <paramref name="bytes"/> or <paramref name="encoding"/> is null.
/// </exception>
public static string ToNullTerminatedString(this byte[] bytes, Encoding encoding) {
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
return encoding.GetString(bytes, 0, bytes.IndexOfNullTerminator());
}
#endregion
#region IndexOfNullTerminator
/// <summary>
/// Gets the index of the null terminator character in the string.
/// </summary>
/// <param name="s">The string to find the null terminator in.</param>
/// <returns>The index of the null terminator.-or- -1 if no null terminator was found.</returns>
///
/// <exception cref="ArgumentNullException">
/// <paramref name="s"/> is null.
/// </exception>
public static int IndexOfNullTerminator(this string s) {
if (s == null)
throw new ArgumentNullException(nameof(s));
int index = s.IndexOf('\0');
return (index != -1 ? index : s.Length);
}
/// <summary>
/// Gets the index of the null terminator character in the character array.
/// </summary>
/// <param name="chars">The character array to find the null terminator in.</param>
/// <returns>The index of the null terminator.-or- -1 if no null terminator was found.</returns>
///
/// <exception cref="ArgumentNullException">
/// <paramref name="chars"/> is null.
/// </exception>
public static int IndexOfNullTerminator(this char[] chars) {
if (chars == null)
throw new ArgumentNullException(nameof(chars));
int index = Array.IndexOf(chars, '\0');
return (index != -1 ? index : chars.Length);
}
/// <summary>
/// Gets the index of the 0 byte in the byte array.
/// </summary>
/// <param name="bytes">The byte array to find the 0 byte in.</param>
/// <returns>The index of the 0 byte.-or- -1 if no 0 byte was found.</returns>
///
/// <exception cref="ArgumentNullException">
/// <paramref name="bytes"/> is null.
/// </exception>
public static int IndexOfNullTerminator(this byte[] bytes) {
if (bytes == null)
throw new ArgumentNullException(nameof(bytes));
int index = Array.IndexOf(bytes, (byte) 0);
return (index != -1 ? index : bytes.Length);
}
#endregion
}
}
|
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet;
using System.Management.Automation;
namespace NtObjectManager.Cmdlets.Object
{
/// <summary>
/// <para type="synopsis">Tests an access mask for empty or specific bits set.</para>
/// <para type="description">This cmdlet tests if an access mask is empty or if one or all bits are set from a
/// comparison access mask.</para>
/// </summary>
/// <example>
/// <code>Test-NtAccessMask $access WriteDac</code>
/// <para>Checks if an access mask has WriteDac access.</para>
/// </example>
/// <example>
/// <code>Test-NtAccessMask $access WriteDac, ReadControl -All</code>
/// <para>Checks if an access mask has WriteDac and ReadControl access.</para>
/// </example>
/// <example>
/// <code>Test-NtAccessMask $access WriteDac, ReadControl</code>
/// <para>Checks if an access mask has WriteDac or ReadControl access.</para>
/// </example>
/// <example>
/// <code>Test-NtAccessMask $access -Empty</code>
/// <para>Checks if an access mask is empty.</para>
/// </example>
[Cmdlet(VerbsDiagnostic.Test, "NtAccessMask", DefaultParameterSetName = "AccessCompare")]
public class TestNtAccessMaskCmdlet : PSCmdlet
{
/// <summary>
/// <para type="description">The access mask to test.</para>
/// </summary>
[Parameter(Position = 0, Mandatory = true)]
public AccessMask AccessMask { get; set; }
/// <summary>
/// <para type="description">The access mask to compare to.</para>
/// </summary>
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "AccessCompare")]
public GenericAccessRights AccessCompare { get; set; }
/// <summary>
/// <para type="description">The raw access mask to compare to.</para>
/// </summary>
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "RawAccessCompare")]
public AccessMask RawAccessCompare { get; set; }
/// <summary>
/// <para type="description">Check all access is in the mask.</para>
/// </summary>
[Parameter(ParameterSetName = "AccessCompare")]
[Parameter(ParameterSetName = "RawAccessCompare")]
public SwitchParameter All { get; set; }
/// <summary>
/// <para type="description">Test if access mask is empty.</para>
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "AccessEmpty")]
public SwitchParameter Empty { get; set; }
/// <summary>
/// <para type="description">Specify the GenericMapping to check if Access Mask would be Write Restricted.</para>
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "WriteRestricted")]
public GenericMapping WriteRestricted { get; set; }
private AccessMask GetAccessMask()
{
if (ParameterSetName == "RawAccessCompare")
{
return RawAccessCompare;
}
return AccessCompare;
}
/// <summary>
/// Process record.
/// </summary>
protected override void ProcessRecord()
{
if (Empty)
{
WriteObject(AccessMask.IsEmpty);
}
else if (ParameterSetName == "WriteRestricted")
{
GenericMapping std_map = NtSecurity.StandardAccessMapping;
WriteObject((std_map.GenericWrite & ~(std_map.GenericRead | std_map.GenericExecute)
| WriteRestricted.GenericWrite & ~(WriteRestricted.GenericRead | WriteRestricted.GenericExecute)).IsEmpty);
}
else if (All)
{
WriteObject(AccessMask.IsAllAccessGranted(GetAccessMask()));
}
else
{
WriteObject(AccessMask.IsAccessGranted(GetAccessMask()));
}
}
}
}
|
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using KaVE.Commons.Model.SSTs.Impl.Expressions.Assignable;
using NUnit.Framework;
using Fix = KaVE.RS.Commons.Tests_Integration.Analysis.SSTAnalysisTestSuite.SSTAnalysisFixture;
namespace KaVE.RS.Commons.Tests_Integration.Analysis.SSTAnalysisTestSuite.Expressions
{
internal class TypeCheckExpressionAnalysisTest : BaseSSTAnalysisTest
{
[Test]
public void Is_Standard()
{
CompleteInMethod(@"var a = this is Exception; $");
AssertBody(
VarDecl("a", Fix.Bool),
Assign("a", new TypeCheckExpression {Reference = VarRef("this"), Type = Fix.Exception}),
Fix.EmptyCompletion);
}
[Test]
public void Is_FullQualified()
{
CompleteInMethod(@"var a = this is System.Exception; $");
AssertBody(
VarDecl("a", Fix.Bool),
Assign("a", new TypeCheckExpression {Reference = VarRef("this"), Type = Fix.Exception}),
Fix.EmptyCompletion);
}
[Test]
public void Is_Alias()
{
CompleteInMethod(@"var a = this is int; $");
AssertBody(
VarDecl("a", Fix.Bool),
Assign("a", new TypeCheckExpression {Reference = VarRef("this"), Type = Fix.Int}),
Fix.EmptyCompletion);
}
[Test]
public void Is_MethodResult()
{
CompleteInClass(@"
public void M()
{
var a = GetHashCode() is int;
$
}");
AssertBody(
"M",
VarDecl("a", Fix.Bool),
VarDecl("$0", Fix.Int),
Assign("$0", Invoke("this", Fix.Object_GetHashCode)),
Assign("a", new TypeCheckExpression {Reference = VarRef("$0"), Type = Fix.Int}),
Fix.EmptyCompletion);
}
}
} |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Scripting.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// Represents a runtime execution context for C# scripts.
/// </summary>
internal class ScriptBuilder
{
/// <summary>
/// Unique prefix for generated uncollectible assemblies.
/// </summary>
/// <remarks>
/// The full names of uncollectible assemblies generated by this context must be unique,
/// so that we can resolve references among them. Note that CLR can load two different assemblies of the very
/// identity into the same load context.
///
/// We are using a certain naming scheme for the generated assemblies (a fixed name prefix followed by a number).
/// If we allowed the compiled code to add references that match this exact pattern it might happen that
/// the user supplied reference identity conflicts with the identity we use for our generated assemblies and
/// the AppDomain assembly resolve event won't be able to correctly identify the target assembly.
///
/// To avoid this problem we use a prefix for assemblies we generate that is unlikely to conflict with user specified references.
/// We also check that no user provided references are allowed to be used in the compiled code and report an error ("reserved assembly name").
/// </remarks>
private static readonly string s_globalAssemblyNamePrefix;
private static int s_engineIdDispenser;
private int _submissionIdDispenser = -1;
private readonly string _assemblyNamePrefix;
private readonly UncollectibleCodeManager _uncollectibleCodeManager;
/// <summary>
/// Lockable object only instance is knowledgeable about.
/// </summary>
private readonly object _gate = new object();
#region Testing and Debugging
private const string UncollectibleModuleFileName = "UncollectibleModule.dll";
// Setting this flag will add DebuggableAttribute on the emitted code that disables JIT optimizations.
// With optimizations disabled JIT will verify the method before it compiles it so we can easily
// discover incorrect code.
internal static bool DisableJitOptimizations;
#endregion
static ScriptBuilder()
{
s_globalAssemblyNamePrefix = "\u211B*" + Guid.NewGuid().ToString() + "-";
}
public ScriptBuilder(AssemblyLoader assemblyLoader = null)
{
if (assemblyLoader == null)
{
assemblyLoader = new InteractiveAssemblyLoader();
}
_assemblyNamePrefix = s_globalAssemblyNamePrefix + "#" + Interlocked.Increment(ref s_engineIdDispenser).ToString();
_uncollectibleCodeManager = new UncollectibleCodeManager(assemblyLoader, _assemblyNamePrefix);
}
internal string AssemblyNamePrefix
{
get { return _assemblyNamePrefix; }
}
internal static bool IsReservedAssemblyName(AssemblyIdentity identity)
{
return identity.Name.StartsWith(s_globalAssemblyNamePrefix, StringComparison.Ordinal);
}
public int GenerateSubmissionId(out string assemblyName, out string typeName)
{
int id = Interlocked.Increment(ref _submissionIdDispenser);
string idAsString = id.ToString();
assemblyName = _assemblyNamePrefix + idAsString;
typeName = "Submission#" + idAsString;
return id;
}
/// <summary>
/// Builds a delegate that will execute just this scripts code.
/// </summary>
public Func<object[], object> Build(
Script script,
DiagnosticBag diagnostics,
CancellationToken cancellationToken)
{
var compilation = script.GetCompilation();
var options = script.Options;
DiagnosticBag emitDiagnostics = DiagnosticBag.GetInstance();
byte[] compiledAssemblyImage;
string entryPointTypeName;
string entryPointMethodName;
bool success = compilation.Emit(
emitDiagnostics,
out entryPointTypeName,
out entryPointMethodName,
out compiledAssemblyImage,
cancellationToken);
if (diagnostics != null)
{
diagnostics.AddRange(emitDiagnostics);
}
bool hadEmitErrors = emitDiagnostics.HasAnyErrors();
emitDiagnostics.Free();
// emit can fail due to compilation errors or because there is nothing to emit:
if (!success)
{
return null;
}
Debug.Assert(compiledAssemblyImage != null);
// TODO: do not actually load the assemblies, only notify the loader of mapping from AssemblyIdentity to location.
foreach (var referencedAssembly in compilation.GetBoundReferenceManager().GetReferencedAssemblies())
{
_uncollectibleCodeManager.Load(
identity: referencedAssembly.Value.Identity,
location: (referencedAssembly.Key as PortableExecutableReference)?.FilePath);
}
var assembly = Assembly.Load(compiledAssemblyImage);
_uncollectibleCodeManager.AddFallBackAssembly(assembly);
var entryPointType = assembly.GetType(entryPointTypeName, throwOnError: true, ignoreCase: false).GetTypeInfo();
var entryPointMethod = entryPointType.GetDeclaredMethod(entryPointMethodName);
return entryPointMethod.CreateDelegate<Func<object[], object>>();
}
/// <summary>
/// Resolves assembly references from CCI generated metadata.
/// The resolution is triggered by the CLR Type Loader.
/// </summary>
private sealed class UncollectibleCodeManager : AssemblyLoader
{
private readonly AssemblyLoader _assemblyLoader;
private readonly string _assemblyNamePrefix;
// lock(_gate) on access
private HashSet<Assembly> _fallBackAssemblies; // additional uncollectible assemblies created due to a Ref.Emit falling back to CCI
private Dictionary<string, Assembly> _mapping; // { simple name -> fall-back assembly }
/// <summary>
/// Lockable object only instance is knowledgeable about.
/// </summary>
private readonly object _gate = new object();
internal UncollectibleCodeManager(AssemblyLoader assemblyLoader, string assemblyNamePrefix)
{
_assemblyLoader = assemblyLoader;
_assemblyNamePrefix = assemblyNamePrefix;
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(Resolve);
}
internal void AddFallBackAssembly(Assembly assembly)
{
lock (_gate)
{
if (_fallBackAssemblies == null)
{
Debug.Assert(_mapping == null);
_fallBackAssemblies = new HashSet<Assembly>();
_mapping = new Dictionary<string, Assembly>();
}
_fallBackAssemblies.Add(assembly);
_mapping[assembly.GetName().Name] = assembly;
}
}
private Assembly Resolve(object sender, ResolveEventArgs args)
{
if (!args.Name.StartsWith(_assemblyNamePrefix, StringComparison.Ordinal))
{
return null;
}
lock (_gate)
{
if (_fallBackAssemblies != null && _fallBackAssemblies.Contains(args.RequestingAssembly))
{
int comma = args.Name.IndexOf(',');
return ResolveNoLock(args.Name.Substring(0, (comma != -1) ? comma : args.Name.Length));
}
}
return null;
}
private Assembly Resolve(string simpleName)
{
lock (_gate)
{
return ResolveNoLock(simpleName);
}
}
private Assembly ResolveNoLock(string simpleName)
{
Assembly assembly;
if (_mapping != null && _mapping.TryGetValue(simpleName, out assembly))
{
return assembly;
}
return null;
}
public override Assembly Load(AssemblyIdentity identity, string location = null)
{
return Resolve(identity.Name) ?? _assemblyLoader.Load(identity, location);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace TypeLite.Tests.RegressionTests {
public class Issue15_ConvertSystemType {
[Fact]
public void WhenClassContainsPropertyOfSystemType_InvalidCastExceptionIsntThrown() {
var builder = new TsModelBuilder();
builder.Add<Issue15Example>();
var generator = new TsGenerator();
var model = builder.Build();
var ex = Record.Exception(() => generator.Generate(model));
Assert.Null(ex);
}
}
public class Issue15Example {
public System.Type Type { get; set; }
}
}
|
using PTJ.Base.DataLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PTJ.Person.DataLayer
{
public class PersonHanterare : Base<int, Person, DBPersonDataContext, int, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing>
{
public enum Relations
{
Adress,
}
public PersonHanterare()
{
initiate();
}
protected override void initiate()
{
timeView = DateTime.Now;
ctx = new DBPersonDataContext();
lstResults = new List<Person>();
result = new Person();
}
public List<Person> GetAll()
{
return base.getAll();
}
protected override List<Person> all()
{
return ctx.Persons.Where(w => ((w.UpdateradDatum.Value == null || w.UpdateradDatum.Value <= timeView) && w.SkapadDatum <= timeView) == true).OrderBy(s => s.Efternamn + ":" + s.MellanNamn + ";" + s.FörNamn).ToList();
}
public bool Exists(List<Person> lstItems)
{
return base.exists(lstItems);
}
protected override bool existsItems(List<Person> lstItems)
{
return (from a in ctx.Persons
where lstItems.Select(s => s.Efternamn.Trim() + ", " + s.MellanNamn.Trim() + ", " + s.FörNamn.Trim().ToLower()).Contains(a.Efternamn.Trim() + ", " + a.MellanNamn.Trim() + ", " + a.FörNamn.Trim().ToLower())
select a).Count() > 0;
}
public bool Exists(List<int> lstIds)
{
return base.exists(lstIds);
}
protected override bool existsItems(List<int> lstIds)
{
return (from a in ctx.Persons
where lstIds.Select(s => s).Contains(a.Id)
select a).Count() > 0;
}
public Person GetById(int id)
{
return base.getById(id);
}
protected override Person byId(int id)
{
return ctx.Persons.Where(w => ((w.UpdateradDatum.Value == null || w.UpdateradDatum.Value <= timeView) && w.SkapadDatum <= timeView)).Single(s => s.Id == id);
}
public List<Person> GetByName(string name)
{
return base.getBy1(name);
}
protected override List<Person> by1(object value)
{
return ctx.Persons
.Where(w => ((w.UpdateradDatum.Value == null || w.UpdateradDatum.Value <= timeView) && w.SkapadDatum <= timeView))
.Where(w => (w.Efternamn.Trim() + ", " + w.MellanNamn.Trim() + ", " + w.FörNamn.Trim()).ToLower().IndexOf(value.ToString().ToLower()) > -1)
.OrderBy(o => (o.Efternamn.Trim() + ", " + o.MellanNamn.Trim() + ", " + o.FörNamn.Trim()).ToLower()).ToList();
}
public object GetByRelation(Relations relation, int id)
{
return base.getByRelation(relation, id);
}
protected override bool isRelation1(string relation)
{
return Relations.Adress.ToString() == relation;
}
protected override object getRelation1(int id)
{
return (from a in ctx.Persons
join b in ctx.Adresses on a.Id equals b.Person_FKID
where b.Id == id
select new Base.Schemas.KeyValue<Person, Adress>() { Key = a, Value = b }).Distinct().ToList();
}
public List<Person> Add(List<Person> lstItems)
{
return base.add(lstItems);
}
protected override List<Person> addItems(List<Person> lstItems)
{
int newId = getNewId();
lstItems.ForEach(f => f.Id = newId++);
lstItems.ForEach(f => f.SkapadDatum = DateTime.Now); lstItems.ForEach(f => f.UpdateradDatum = DBDateTimeHelper.getDefaultDateTime());
ctx.Persons.InsertAllOnSubmit(lstItems);
ctx.SubmitChanges();
return lstItems;
}
private int getNewId()
{
int Id = 1;
if (ctx.Mails.Count() != 0)
{
Id = ctx.Mails.Select(s => s.Id).Max() + 1;
}
return Id;
}
public List<Person> Update(List<Person> lstItems)
{
return base.update(lstItems);
}
protected override List<Person> updateItems(List<Person> lstItems)
{
List<Person> lstPersonResult = new List<Person>();
foreach (var item in (from au in ctx.Persons
where lstItems.Select(s => s.Id).Contains(au.Id)
select au))
{
var updateItem = lstItems.Where(w => w.Id == item.Id).Single();
item.FörNamn = updateItem.FörNamn;
item.MellanNamn = updateItem.MellanNamn;
item.Efternamn = updateItem.Efternamn;
item.PersonNummer = updateItem.PersonNummer;
item.UpdateradDatum = DateTime.Now;
lstPersonResult.AddRange(this.Add(new List<Person>() { item }));
}
ctx.SubmitChanges();
return lstPersonResult;
}
public List<Person> Delete(List<Person> lstItems)
{
return base.delete(lstItems);
}
protected override List<Person> deleteItems(List<Person> lstItems)
{
List<Person> lstPersonResult = new List<Person>();
foreach (var item in (from au in ctx.Persons
where lstItems.Select(s => s.Id).Contains(au.Id)
select au))
{
var updateItem = lstItems.Where(w => w.Id == item.Id).Single();
item.FörNamn = updateItem.FörNamn;
item.MellanNamn = updateItem.MellanNamn;
item.Efternamn = updateItem.Efternamn;
item.PersonNummer = updateItem.PersonNummer;
item.UpdateradDatum = DateTime.Now;
}
ctx.SubmitChanges();
return lstItems;
}
}
}
|
using CarRental.ViewModels.Order;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CarRental.Models.Interfaces
{
public interface IRentReposiotry
{
List<Rent> GetAll();
void AddRent(Rent rent);
void UpdateRent(Rent rent);
void DeleteRent(Rent rent);
void ArchiveRent(Rent rent, Archives archives);
Rent GetRent(int id);
Rent GetRentByStatus(string status);
List<Rent> GetMyRents(string username);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float velocidade = 2f;
public BoxCollider2D areaJogo;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// Movimentação do Jogador
var vertical = Input.GetAxis("Vertical");
var horizontal = Input.GetAxis("Horizontal");
transform.Translate(new Vector2(horizontal, vertical) * velocidade * Time.deltaTime);
// Garantir que o jogador está dentro da área de jogo
var position = areaJogo.transform.position;
var extents = areaJogo.bounds.extents;
var offset = areaJogo.offset;
var limiteXMin = -extents.x + position.x + offset.x * 2.5f;
var limiteXMax = extents.x + position.x + offset.x * 2.5f;
var limiteYMin = -extents.y + position.y + offset.y * 2.5f;
var limiteYMax = extents.y + position.y + offset.y * 2.5f;
transform.position = new Vector2(
Mathf.Clamp(transform.position.x, limiteXMin, limiteXMax),
Mathf.Clamp(transform.position.y, limiteYMin, limiteYMax)
);
}
}
|
using System.Windows;
using PhonebookImportClient.ViewModels;
namespace PhonebookImportClient.Views
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public MainWindow(MainViewModel dataContext)
{
this.DataContext = dataContext;
InitializeComponent();
}
}
}
|
using MCC.Utility.Binding;
namespace MCC.Bouyomi
{
public class SettingPageViewModel : BindableBase
{
private Setting setting = Setting.Instance;
public string Format
{
get => setting.Format;
set => Set(ref setting.Format, value);
}
public string ApplicationPath
{
get => setting.ApplicationPath;
set => Set(ref setting.ApplicationPath, value);
}
public bool Enable
{
get => setting.Enable;
set => Set(ref setting.Enable, value);
}
public bool BlackListEnable
{
get => setting.BlackListEnable;
set => Set(ref setting.BlackListEnable, value);
}
}
}
|
using JoySoftware.HomeAssistant.Client;
using NetDaemon.Common.Fluent;
namespace NetDaemon.Mapping
{
public static class ContextMapper
{
public static Context Map(HassContext? hassContext)
{
if (hassContext == null)
return new Context();
return new Context
{
Id = hassContext.Id,
ParentId = hassContext.ParentId,
UserId = hassContext.UserId
};
}
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using DotNetNuke.ComponentModel;
using DotNetNuke.Data;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security.Roles;
using DotNetNuke.Services.Cache;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Log.EventLog;
using Moq;
using DotNetNuke.Services.FileSystem;
namespace DotNetNuke.Tests.Utilities.Mocks
{
public class MockComponentProvider
{
public static Mock<T> CreateNew<T>() where T : class
{
if (ComponentFactory.Container == null)
{
ResetContainer();
}
//Try and get mock
var mockComp = ComponentFactory.GetComponent<Mock<T>>();
var objComp = ComponentFactory.GetComponent<T>();
if (mockComp == null)
{
mockComp = new Mock<T>();
ComponentFactory.RegisterComponentInstance<Mock<T>>(mockComp);
}
if (objComp == null)
{
ComponentFactory.RegisterComponentInstance<T>(mockComp.Object);
}
return mockComp;
}
public static Mock<T> CreateNew<T>(string name) where T : class
{
if (ComponentFactory.Container == null)
{
ResetContainer();
}
//Try and get mock
var mockComp = ComponentFactory.GetComponent<Mock<T>>();
var objComp = ComponentFactory.GetComponent<T>(name);
if (mockComp == null)
{
mockComp = new Mock<T>();
ComponentFactory.RegisterComponentInstance<Mock<T>>(mockComp);
}
if (objComp == null)
{
ComponentFactory.RegisterComponentInstance<T>(name, mockComp.Object);
}
return mockComp;
}
public static Mock<CachingProvider> CreateDataCacheProvider()
{
return CreateNew<CachingProvider>();
}
public static Mock<EventLogController> CreateEventLogController()
{
return CreateNew<EventLogController>();
}
public static Mock<DataProvider> CreateDataProvider()
{
return CreateNew<DataProvider>();
}
public static Mock<FolderProvider> CreateFolderProvider(string name)
{
return CreateNew<FolderProvider>(name);
}
public static Mock<ILocalizationProvider> CreateLocalizationProvider()
{
return CreateNew<ILocalizationProvider>();
}
public static Mock<ILocaleController> CreateLocaleController()
{
return CreateNew<ILocaleController>();
}
public static Mock<RoleProvider> CreateRoleProvider()
{
return CreateNew<RoleProvider>();
}
public static void ResetContainer()
{
ComponentFactory.Container = new SimpleContainer();
}
}
}
|
using System;
using System.Collections;
namespace SequentialCollections
{
class RunQueue
{
static void Main(string[] args)
{
//Creating a queue
Queue newQueue = new Queue();
newQueue.Enqueue("First");
newQueue.Enqueue("Second");
newQueue.Enqueue("Third");
newQueue.Enqueue("Fourth");
Console.WriteLine("First element: {0}", newQueue.Peek());
while (newQueue.Count > 0)
{
object obj = newQueue.Dequeue();
Console.WriteLine("From queue: {0}", obj);
}
//Write blank line
Console.WriteLine();
//Creating a stack
Stack newStack = new Stack();
newStack.Push("First");
newStack.Push("Second");
newStack.Push("Third");
newStack.Push("Fourth");
Console.WriteLine("First element: {0}", newStack.Peek());
while (newStack.Count > 0)
{
object obj = newStack.Pop();
Console.WriteLine("From stack: {0}", obj);
}
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model.InvoiceManagement;
using Model.DataEntity;
using Utility;
using Model.Locale;
using Model.Schema.EIVO.B2B;
using Model.UploadManagement;
using Model.Schema.EIVO;
namespace Model.Helper
{
public class B2BExceptionInfo
{
public OrganizationToken Token { get; set; }
public Dictionary<int, Exception> ExceptionItems { get; set; }
public SellerInvoiceRoot InvoiceData { get; set; }
public CancelInvoiceRoot CancelInvoiceData { get; set; }
public AllowanceRoot AllowanceData { get; set; }
public CancelAllowanceRoot CancelAllowanceData { get; set; }
public BuyerInvoiceRoot BuyerInvoiceData { get; set; }
public ReceiptRoot ReceiptData { get; set; }
public CancelReceiptRoot CancelReceiptData { get; set; }
public IEnumerable<ItemUpload<Organization>> CounterpartBusinessError { get; set; }
public ReturnInvoiceRoot ReturnInvoiceData { get; set; }
public ReturnCancelInvoiceRoot ReturnCancelInvoiceData { get; set; }
public ReturnAllowanceRoot ReturnAllowanceData { get; set; }
public ReturnCancelAllowanceRoot ReturnCancelAllowanceData { get; set; }
public DeleteInvoiceRoot DeleteInvoiceData { get; set; }
public DeleteCancelInvoiceRoot DeleteCancelInvoiceData { get; set; }
public DeleteAllowanceRoot DeleteAllowanceData { get; set; }
public DeleteCancelAllowanceRoot DeleteCancelAllowanceData { get; set; }
}
public static class B2BExceptionNotification
{
public static EventHandler<ExceptionEventArgs> SendExceptionNotification;
public static void SendNotification(object stateInfo)
{
B2BExceptionInfo info = stateInfo as B2BExceptionInfo;
if (info == null)
return;
try
{
if (info.InvoiceData != null)
{
notifyExceptionWhenUploadInvoice(info);
}
else if (info.CancelInvoiceData != null)
{
notifyExceptionWhenUploadCancellation(info);
}
else if (info.AllowanceData != null)
{
notifyExceptionWhenUploadAllowance(info);
}
else if (info.CancelAllowanceData != null)
{
notifyExceptionWhenUploadAllowanceCancellation(info);
}
else if (info.BuyerInvoiceData != null)
{
notifyExceptionWhenUploadBuyerInvoice(info);
}
else if (info.ReceiptData != null)
{
notifyExceptionWhenUploadReceipt(info);
}
else if (info.CancelReceiptData != null)
{
notifyExceptionWhenUploadReceiptCancellation(info);
}
else if (info.ReturnInvoiceData != null)
{
notifyExceptionWhenUploadInvoiceReturn(info);
}
else if (info.ReturnCancelInvoiceData != null)
{
notifyExceptionWhenUploadInvoiceCancellationReturn(info);
}
else if (info.ReturnAllowanceData != null)
{
notifyExceptionWhenUploadAllowanceReturn(info);
}
else if (info.ReturnCancelAllowanceData != null)
{
notifyExceptionWhenUploadAllowanceCancellationReturn(info);
}
else if (info.DeleteInvoiceData != null)
{
notifyExceptionWhenUploadInvoiceDelete(info);
}
else if (info.DeleteCancelInvoiceData != null)
{
notifyExceptionWhenUploadInvoiceCancellationDelete(info);
}
else if (info.DeleteAllowanceData != null)
{
notifyExceptionWhenUploadAllowanceDelete(info);
}
else if (info.DeleteCancelAllowanceData != null)
{
notifyExceptionWhenUploadAllowanceCancellationDelete(info);
}
else if(info.CounterpartBusinessError!=null)
{
notifyExceptionWhenUploadCounterpartBusiness(info);
}
processNotification();
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
private static void processNotification()
{
using (InvoiceManager mgr = new InvoiceManager())
{
var items = mgr.GetTable<ExceptionLog>().Where(e => e.ExceptionReplication != null);
foreach (var item in items.GroupBy(i => i.CompanyID))
{
SendExceptionNotification(mgr, new ExceptionEventArgs
{
Enterprise = item.First().Organization.EnterpriseGroupMember.Count>0
? item.First().Organization.EnterpriseGroupMember.First().EnterpriseGroup
: null,
CompanyID = item.Key,
EMail = item.First().Organization.ContactEmail
});
}
SendExceptionNotification(mgr, new ExceptionEventArgs
{
///送給系統管理員接收全部異常資料
///
});
mgr.GetTable<ExceptionReplication>().DeleteAllOnSubmit(items.Select(i => i.ExceptionReplication));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadInvoiceReturn(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_Invoice,
Message = e.Value.Message,
DataContent = info.ReturnInvoiceData.ReturnInvoice[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadInvoiceDelete(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_Invoice,
Message = e.Value.Message,
DataContent = info.DeleteInvoiceData.DeleteInvoice[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadInvoiceCancellationReturn(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_InvoiceCancellation,
Message = e.Value.Message,
DataContent = info.ReturnCancelInvoiceData.ReturnCancelInvoice[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadInvoiceCancellationDelete(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_InvoiceCancellation,
Message = e.Value.Message,
DataContent = info.DeleteCancelInvoiceData.DeleteCancelInvoice[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadAllowanceReturn(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_Allowance,
Message = e.Value.Message,
DataContent = info.ReturnAllowanceData.ReturnAllowance[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadAllowanceDelete(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_Allowance,
Message = e.Value.Message,
DataContent = info.DeleteAllowanceData.DeleteAllowance[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadAllowanceCancellationReturn(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_AllowanceCancellation,
Message = e.Value.Message,
DataContent = info.ReturnCancelAllowanceData.ReturnCancelAllowance[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadAllowanceCancellationDelete(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_AllowanceCancellation,
Message = e.Value.Message,
DataContent = info.DeleteCancelAllowanceData.DeleteCancelAllowance[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadInvoice(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_Invoice,
Message = e.Value.Message,
DataContent = info.InvoiceData.Invoice[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadBuyerInvoice(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_Invoice,
Message = e.Value.Message,
DataContent = info.BuyerInvoiceData.Invoice[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadAllowance(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_Allowance,
Message = e.Value.Message,
DataContent = info.AllowanceData.Allowance[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadCancellation(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_InvoiceCancellation,
Message = e.Value.Message,
DataContent = info.CancelInvoiceData.CancelInvoice[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadAllowanceCancellation(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_AllowanceCancellation,
Message = e.Value.Message,
DataContent = info.CancelAllowanceData.CancelAllowance[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadReceipt(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.B2BInvoiceDocumentTypeDefinition.收據,
Message = e.Value.Message,
DataContent = info.ReceiptData.Receipt[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadReceiptCancellation(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.ExceptionItems.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.B2BInvoiceDocumentTypeDefinition.作廢收據,
Message = e.Value.Message,
DataContent = info.CancelReceiptData.CancelReceipt[e.Key].GetXml()
}));
mgr.SubmitChanges();
}
}
private static void notifyExceptionWhenUploadCounterpartBusiness(B2BExceptionInfo info)
{
int? companyID = info.Token != null ? info.Token.CompanyID : (int?)null;
using (InvoiceManager mgr = new InvoiceManager())
{
var table = mgr.GetTable<ExceptionLog>();
table.InsertAllOnSubmit(info.CounterpartBusinessError.Select(e => new ExceptionLog
{
CompanyID = companyID,
LogTime = DateTime.Now,
TypeID = (int)Naming.DocumentTypeDefinition.E_InvoiceCancellation,
Message = e.Status,
DataContent = e.DataContent
}));
mgr.SubmitChanges();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RegSide
{
public partial class Form1 : Form
{
List<NewAccount> lstAccount = new List<NewAccount>();
public Form1()
{
InitializeComponent();
LoadPage();
}
private void LoadPage()
{
NewAccount();
LoadAccountList();
//ChangePassword();
}
private void LoadAccountList()
{
String fileFolder = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Output");
if (!Directory.Exists(fileFolder))
{
MessageBox.Show("Output Folder does not exist!");
return;
}
DirectoryInfo dinfo = new DirectoryInfo(fileFolder);
lstAccount.Add(new NewAccount() { Account= "123", Password="111111111111", SafeCode = "222222222222"});
foreach (FileInfo f in dinfo.GetFiles())
{
String tmpFile = Path.Combine(fileFolder, f.Name);
StreamReader sr = new StreamReader(tmpFile, Encoding.Default);
String line;
while ((line = sr.ReadLine()) != null)
{
NewAccount account = new NewAccount();
String[] tmp = line.Split('|');
account.Account = tmp[0];
account.Password = tmp[1];
account.SafeCode = tmp[2];
lstAccount.Add(account);
}
break;
}
}
private void NewAccount()
{
try
{
string url = "http://www.shiqi.so/register2.htm";
wbPage.Navigate(url);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ChangePassword()
{
try
{
string url = "http://www.shiqi.so/changepass.htm";
wbPage.Navigate(url);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void wbPage_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
}
private void wbPage_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
CreateAccountInputValue();
//ChangePasswordInputValue();
}
private void CreateAccountInputValue()
{
NewAccount account = new NewAccount();
if(lstAccount.Count >= 1)
{
account = lstAccount[0];
}
wbPage.Document.GetElementById("name").SetAttribute("value", account.Account);
wbPage.Document.GetElementById("pass").SetAttribute("value", account.Password);
wbPage.Document.GetElementById("pass2").SetAttribute("value", account.Password);
wbPage.Document.GetElementById("pass3").SetAttribute("value", account.SafeCode);
wbPage.Document.GetElementById("pass4").SetAttribute("value", account.SafeCode);
wbPage.Document.GetElementById("authinput").SetAttribute("value", "");
Random ran = new Random();
int RandKey = ran.Next(100000, 9999999);
wbPage.Document.GetElementById("qqmsn").SetAttribute("value", RandKey.ToString());
lstAccount.RemoveAt(0);
}
private void ChangePasswordInputValue()
{
wbPage.Document.GetElementById("id").SetAttribute("value", "");
wbPage.Document.GetElementById("oldpass").SetAttribute("value", "xiaohuilili");
wbPage.Document.GetElementById("oldpass2").SetAttribute("value", "LYJ074");
wbPage.Document.GetElementById("pass").SetAttribute("value", "HS34243982C");
wbPage.Document.GetElementById("pass2").SetAttribute("value", "HS34243982C");
wbPage.Document.GetElementById("pass3").SetAttribute("value", "GHX086");
wbPage.Document.GetElementById("pass4").SetAttribute("value", "GHX086");
wbPage.Document.GetElementById("authinput").SetAttribute("value", "");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.