text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Panacea.Multilinguality
{
public sealed class IsTranslatableAttribute : Attribute
{
public int MaxChars { get; set; }
public IsTranslatableAttribute(int maxChars = 0)
{
MaxChars = maxChars;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Srinivas_Akhil_Assignment1_MS806
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
//TootTips for Clear and Exit Buttons
ToolTips.SetToolTip(ClearButton, "Press to Clear form for the next user");
ToolTips.SetToolTip(ExitButton, "Press to Exit Application");
ToolTips.SetToolTip(OrderButton, "Enter quantity of your favourite Pizza/s");
}
//setting maximum length for ServerNameTextBox
private void ServerNameTextBox_TextChanged(object sender, EventArgs e)
{
ServerNameTextBox.MaxLength = 50;
}
//Disabling numeric values for servername
private void ServerNameTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar) && (e.KeyChar != ' '))
{
e.Handled = true;
}
}
//Disabling alphabetical values for table Number
private void TableNoTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != ' '))
{
e.Handled = true;
}
}
//Limiting the table numbers -- Upto 15
private void TableNoTextBox_TextChanged(object sender, EventArgs e)
{
int TableNo;
int.TryParse(this.TableNoTextBox.Text, out TableNo);
if (TableNo > 15)
{
MessageBox.Show("Enter a Table Number value between 1-15 in numeric format");
TableNoTextBox.Focus();
}
if (TableNoTextBox.Text == "0")
{
MessageBox.Show("Enter a Table Number value between 1-15 in numeric format");
TableNoTextBox.Focus();
}
}
//Start Button Function
private void StartButton_Click(object sender, EventArgs e)
{
int TableNo;
int.TryParse(this.TableNoTextBox.Text, out TableNo);
string firstname;
firstname = this.ServerNameTextBox.Text;
//Getting the first name for Form Text
int spacesep;
spacesep = firstname.IndexOf(' ');
string TableNoinstr = Convert.ToString(TableNo);
//Changing the form Text
if (ServerNameTextBox.Text.Contains(' '))
{
firstname = ServerNameTextBox.Text.Remove(spacesep);
this.Text = firstname + " " + "@ Table Number" + " " + TableNoinstr;
}
else
{
this.Text = ServerNameTextBox.Text + " " + "@ Table Number" + " " + TableNoinstr;
}
//Condition statement for empty value of Server name or Table Number
if (ServerNameTextBox.Text.Trim() == string.Empty | TableNoTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Please Enter valid name and table no to continue", "Oops!");
this.Text = "Welcome to Sult";
}
//Displaying and hiding required Panels
else
{
StartPanel.Visible = false;
SultLogo.Visible = true;
OverallPizzaPanel.Visible = true;
FunctionPanel.Visible = true;
OrderButton.Enabled = true;
SummaryButton.Enabled = true;
MargheritaPizzatextBox.Focus();
}
}
//Declaring Global Variables for Overall Summary
int totalcompanytranscation;
int totalcompanypizza;
float totalcompanyreceipts;
private void OrderButton_Click(object sender, EventArgs e)
{
//Arithmetic Calculations for Receipt and total pizza
int pizza1, pizza2, pizza3;
int.TryParse(this.MargheritaPizzatextBox.Text, out pizza1);
int.TryParse(this.PepperoniPizzaTextBox.Text, out pizza2);
int.TryParse(this.HamPineappleTextBox.Text, out pizza3);
int totalpizzaordered = pizza1 + pizza2 + pizza3;
totalcompanypizza += totalpizzaordered;
string totalpizzaorderedstring = totalpizzaordered.ToString();
float pizza1cost = pizza1 * 9;
float pizza2cost = (float)(pizza2 * 11.50);
float pizza3cost = (float)(pizza3 * 12.79);
float singleordercost = (float)(pizza1cost + pizza2cost + pizza3cost + 2.49);
//Overall Company Receipt using Global Variable
totalcompanyreceipts += singleordercost;
//Handling Exception if no pizza is ordered
try
{
if (totalpizzaorderedstring != "0")
{
if (MessageBox.Show("Is this your final order?\nNote : Server fee of €2.49 will be added to the total bill", "Order", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
OrderNameServerNameDisplayLabel.Text = this.ServerNameTextBox.Text;
OrderTotalNumberOfPizzaLabel.Text = totalpizzaordered.ToString();
OrderTotalTableReceiptsLabel.Text = "€"+singleordercost.ToString();
OverallPizzaPanel.Enabled = false;
OverallOrderPanel.Visible = true;
OverallSummaryPanel.Visible = false;
//Overall CompanyTranscation using Global Variable
totalcompanytranscation += 1;
}
}
}
catch (Exception)
{
throw;
}
}
//Clear Button to reset to the start Panel
private void ClearButton_Click(object sender, EventArgs e)
{
OverallPizzaPanel.Enabled = true;
OverallPizzaPanel.Visible = false;
OverallOrderPanel.Visible = false;
OverallSummaryPanel.Visible = false;
FunctionPanel.Visible = false;
SultLogo.Visible = false;
OverallSummaryPanel.Visible = false;
MargheritaPizzatextBox.Text = "0";
PepperoniPizzaTextBox.Text = "0";
HamPineappleTextBox.Text = "0";
StartPanel.Visible = true;
TableNoTextBox.Text = "";
ServerNameTextBox.Text = "";
this.Text = "Welcome to Sult";
}
//Summary Button function
private void SummaryButton_Click(object sender, EventArgs e)
{
OrderButton.Enabled = false;
SummaryButton.Enabled = false;
OverallOrderPanel.Visible = false;
OverallSummaryPanel.Visible = true;
OverallPizzaPanel.Visible = false;
//Changing the form Text
this.Text = "Sult Company Summary Data";
//Displaying the Overall Company values from Global Variables calculated in Order Function
TotalCompanyTranscationsDisplayLabel.Text = totalcompanytranscation.ToString();
TotalCompanyPizzaDisplayLabel.Text = totalcompanypizza.ToString();
TotalCompanyReceiptsDisplayLabel.Text = "€" + totalcompanyreceipts.ToString();
float avgcompanytranscation = totalcompanyreceipts / totalcompanytranscation;
//Rounding off Avg Transcation to 2 Decimal Places
Math.Round(avgcompanytranscation, 2);
AvgTranscationValueDisplayLabel.Text = "€" + avgcompanytranscation.ToString();
}
//Exit Button to Close the Application
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
//This namespace holds Indicators in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Indicators.Filt4b
{
public class Filt4bFirmaOhlc : Indicator
{
private double Mo;
private double Md, MdFl, MdCl, Md1;
private double MFl, MCl;
private bool MIsInt;
private Filt4bFirma y;
private int dataValidCount;
private bool CheckInt(double x)
{
return Math.Abs(x-Math.Ceiling(x)) < 1e-5 || Math.Abs(x-Math.Floor(x)) < 1e-5;
}
private double FirmaUnBias(double m, int q)
{
return m >= Math.Sqrt((double)q) ? Math.Sqrt((double)q)*m-q+1.0 : 1.0;
}
public int ValidBarsStart
{
get
{
return (int)Math.Ceiling(UnBias ? FirmaUnBias(M, Q) : M);
}
}
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Filt4b FirmaOhlc";
Name = "Filt4bFirmaOhlc";
Calculate = Calculate.OnBarClose;
IsOverlay = false;
DisplayInDataBox = true;
DrawOnPricePanel = false;
DrawHorizontalGridLines = true;
DrawVerticalGridLines = true;
PaintPriceMarkers = true;
ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
//Disable this property if your indicator requires custom values that cumulate with each new market data event.
//See Help Guide for additional information.
IsSuspendedWhileInactive = false;
MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
// Properties
M = 10;
Q = 2;
UnBias = false;
// Plots
AddPlot(Brushes.Goldenrod, "FirmaOpen");
AddPlot(Brushes.Goldenrod, "FirmaHigh");
AddPlot(Brushes.Goldenrod, "FirmaLow");
AddPlot(Brushes.Goldenrod, "FirmaClose");
}
else if (State == State.Configure)
{
Mo = UnBias ? FirmaUnBias(M, Q) : M;
MIsInt = CheckInt(Mo);
Md = (double)Q / (Mo + (double)Q - 1.0);
MFl = Math.Floor(Mo);
MCl = Math.Ceiling(Mo);
MdFl = (double)Q / (MFl + (double)Q - 1.0);
MdCl = (double)Q / (MCl + (double)Q - 1.0);
Md1 = (MCl - Mo) * MdFl + (Mo - MFl) * MdCl;
dataValidCount = 0;
}
else if (State == State.DataLoaded)
{
BarsRequiredToPlot = ValidBarsStart;
y = Filt4bFirma(Close, Mo, Q, false);
}
}
protected override void OnBarUpdate()
{
dataValidCount += 1;
if (dataValidCount >= ValidBarsStart)
{
if (MIsInt)
{
Values[0][0] = y[0] + (Open[0]-Close[0]) * Md;
Values[1][0] = y[0] + (High[0]-Close[0]) * Md;
Values[2][0] = y[0] + (Low[0]-Close[0]) * Md;
}
else
{
Values[0][0] = y[0] + (Open[0]-Close[0]) * Md1;
Values[1][0] = y[0] + (High[0]-Close[0]) * Md1;
Values[2][0] = y[0] + (Low[0]-Close[0]) * Md1;
}
Values[3][0] = y[0];
}
}
#region Properties
[NinjaScriptProperty]
[Range(1, double.MaxValue)]
[Display(Name="M", Description="Period", Order=1, GroupName="Parameters")]
public double M
{ get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="Q", Description="Mechanism", Order=2, GroupName="Parameters")]
public int Q
{ get; set; }
[NinjaScriptProperty]
[Display(Name="UnBias", Description="RemoveBias", Order=3, GroupName="Parameters")]
public bool UnBias
{ get; set; }
[Browsable(false)]
[XmlIgnore]
public Series<double> Open
{
get {return Values[0]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> High
{
get {return Values[1]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> Low
{
get {return Values[2]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> Close
{
get {return Values[3]; }
}
#endregion
}
}
#region NinjaScript generated code. Neither change nor remove.
namespace NinjaTrader.NinjaScript.Indicators
{
public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
{
private Filt4b.Filt4bFirmaOhlc[] cacheFilt4bFirmaOhlc;
public Filt4b.Filt4bFirmaOhlc Filt4bFirmaOhlc(double m, int q, bool unBias)
{
return Filt4bFirmaOhlc(Input, m, q, unBias);
}
public Filt4b.Filt4bFirmaOhlc Filt4bFirmaOhlc(ISeries<double> input, double m, int q, bool unBias)
{
if (cacheFilt4bFirmaOhlc != null)
for (int idx = 0; idx < cacheFilt4bFirmaOhlc.Length; idx++)
if (cacheFilt4bFirmaOhlc[idx] != null && cacheFilt4bFirmaOhlc[idx].M == m && cacheFilt4bFirmaOhlc[idx].Q == q && cacheFilt4bFirmaOhlc[idx].UnBias == unBias && cacheFilt4bFirmaOhlc[idx].EqualsInput(input))
return cacheFilt4bFirmaOhlc[idx];
return CacheIndicator<Filt4b.Filt4bFirmaOhlc>(new Filt4b.Filt4bFirmaOhlc(){ M = m, Q = q, UnBias = unBias }, input, ref cacheFilt4bFirmaOhlc);
}
}
}
namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
{
public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
{
public Indicators.Filt4b.Filt4bFirmaOhlc Filt4bFirmaOhlc(double m, int q, bool unBias)
{
return indicator.Filt4bFirmaOhlc(Input, m, q, unBias);
}
public Indicators.Filt4b.Filt4bFirmaOhlc Filt4bFirmaOhlc(ISeries<double> input , double m, int q, bool unBias)
{
return indicator.Filt4bFirmaOhlc(input, m, q, unBias);
}
}
}
namespace NinjaTrader.NinjaScript.Strategies
{
public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
{
public Indicators.Filt4b.Filt4bFirmaOhlc Filt4bFirmaOhlc(double m, int q, bool unBias)
{
return indicator.Filt4bFirmaOhlc(Input, m, q, unBias);
}
public Indicators.Filt4b.Filt4bFirmaOhlc Filt4bFirmaOhlc(ISeries<double> input , double m, int q, bool unBias)
{
return indicator.Filt4bFirmaOhlc(input, m, q, unBias);
}
}
}
#endregion
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Converter.Units
{
[Unit(nameof(DataUnit))]
abstract class DataUnit : Unit
{
protected abstract double UnitDevidedByByte { get; }
public override double GetShift => 0;
public override double GetRation => UnitDevidedByByte;
}
}
|
using System.Threading;
using System.Threading.Tasks;
using LubyClocker.CrossCuting.Shared;
using LubyClocker.CrossCuting.Shared.Exceptions;
using LubyClocker.Infra.Data.Context;
using MediatR;
namespace LubyClocker.Application.BoundedContexts.Projects.Commands.Delete
{
public class DeleteProjectCommandHandler : IRequestHandler<DeleteProjectCommand, bool>
{
private readonly LubyClockerContext _context;
public DeleteProjectCommandHandler(LubyClockerContext context)
{
_context = context;
}
public async Task<bool> Handle(DeleteProjectCommand request, CancellationToken cancellationToken)
{
var entity = await _context.Projects.FindAsync(request.Id);
if (entity == null)
{
throw new InvalidRequestException(MainResource.ResourceNotExists);
}
_context.Projects.Remove(entity);
await _context.SaveChangesAsync(cancellationToken);
return true;
}
}
} |
namespace DipDemo.Cataloguer.Infrastructure.Presentation.EventBinding
{
public class EventBindingFactory : IEventBindingFactory
{
private readonly IEventBinder[] binders;
public EventBindingFactory(IEventBinder[] binders)
{
this.binders = binders;
}
public void WireEvents(IPresenter presenter)
{
if (presenter.View == null)
return;
foreach (var binder in binders)
{
binder.Bind(presenter);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Linq;
using System.Data;
using CakeShop.Data;
using Microsoft.Win32;
namespace CakeShop.Views
{
/// <summary>
/// Interaction logic for AddNewCake.xaml
/// </summary>
///
#region
/// ViewModel for AddNewCake
public class AddNewCakeViewModel
{
CakeShopDAO dao;
public AddNewCakeViewModel()
{
dao = new CakeShopDAO();
}
public List<CATEGORY> GetCATEGORies()
{
return dao.CategoryList();
}
}
#endregion
public partial class NewCake : Page
{
CAKE curCake;
AddNewCakeViewModel _mainvm;
List<CATEGORY> categories;
int isCakeAdded;
public NewCake()
{
InitializeComponent();
Prepare();
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
}
private void Prepare()
{
curCake = new CAKE();
_mainvm = new AddNewCakeViewModel();
categories = _mainvm.GetCATEGORies();
chosenCategory.ItemsSource = categories;
isCakeAdded = 0;
}
private void SaveCake_Click(object sender, RoutedEventArgs e)
{
bool check = CheckInputError();
if (check == true)
{
try {
StoreCakeData();
RefreshDataInput();
Prepare();
isCakeAdded++;
MessageBox.Show("Thêm Cake thành công", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch(Exception ex)
{
MessageBox.Show("Lỗi thêm cake", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
private void Refresh_Click(object sender, RoutedEventArgs e)
{
RefreshDataInput();
Prepare();
}
private void StoreCakeData()
{
OurCakeShopEntities database = new OurCakeShopEntities();
int index = (int)chosenCategory.SelectedIndex;
CAKE cake = new CAKE
{
ID = 1000,
Name = cakeName.Text,
SellPrice = long.Parse(sellPrice.Text),
BasePrice = long.Parse(basePrice.Text),
InventoryNum = long.Parse(inventoryNumber.Text),
Introduction = introduction.Text,
Description = description.Text,
AvatarImage = curCake.AvatarImage,
CatID = categories[index].ID,
DateAdded = DateTime.Now,
};
database.CAKEs.Add(cake);
database.SaveChanges();
}
private void AddAvatarImage_Click(object sender, RoutedEventArgs e)
{
//Hiển thị cửa sổ chọn ảnh
var screen = new OpenFileDialog();
// Thiết đặt bộ lọc (filter) cho file hình ảnh
var codecs = ImageCodecInfo.GetImageEncoders();
var sep = string.Empty;
foreach (var c in codecs)
{
string codecName = c.CodecName.Substring(8).Replace("Codec", "Files").Trim();
screen.Filter = String.Format("{0}{1}{2} ({3})|{3}", screen.Filter, sep, codecName, c.FilenameExtension);
sep = "|";
}
screen.Filter = String.Format("{0}{1}{2} ({3})|{3}", screen.Filter, sep, "All Files", "*.*");
screen.Title = "Chọn ảnh lộ trình";
screen.Multiselect = false;
screen.RestoreDirectory = true;
if (screen.ShowDialog() == true)
{
var path = screen.FileName;
byte[] array = UnknownImageToByteArrayConverter.ImageToByteArray(path);
AvatarImage.ImageSource = AlternativeByteArrayToImageConveter.Convert(array);
curCake.AvatarImage = array.ToArray();
}
}
private bool CheckInputError()
{
bool check = true;
if (AvatarImage.ImageSource == null)
{
check = false;
MessageBox.Show("Bạn chưa đổi ảnh Avatar", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (introduction.Text == "" || description.Text == "" || cakeName.Text == "" || sellPrice.Text == "" ||
basePrice.Text == "" || inventoryNumber.Text == "")
{
check = false;
MessageBox.Show("Bạn chưa nhập đủ thông tin", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
if (check == true)
{
try
{
long sellprice = long.Parse(sellPrice.Text);
if (sellprice < 0)
throw new Exception("1");
}
catch (Exception ex)
{
check = false;
MessageBox.Show("Giá bán không hơp lệ\n Dữ liệu phải là dạng số và lớn hơn 0", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
if (check == true)
{
try
{
long baseprice = long.Parse(basePrice.Text);
if (baseprice < 0)
throw new Exception("1");
}
catch (Exception ex)
{
check = false;
MessageBox.Show("Giá bán không hơp lệ\n Dữ liệu phải là dạng số và lớn hơn 0", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
if (check == true)
{
try
{
long inventorynumber = long.Parse(inventoryNumber.Text);
if (inventorynumber < 0)
throw new Exception("1");
}
catch (Exception ex)
{
check = false;
MessageBox.Show("Giá gốc không hơp lệ\n Dữ liệu phải là dạng số và lớn hơn 0", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
return check;
}
private void RefreshDataInput()
{
cakeName.Text = "";
chosenCategory.SelectedIndex = -1;
inventoryNumber.Text = "";
sellPrice.Text = "";
basePrice.Text = "";
introduction.Text = "";
description.Text = "";
AvatarImage.ImageSource = null;
curCake = new CAKE();
}
private void ComeBack_Click(object sender, RoutedEventArgs e)
{
try
{
if(isCakeAdded==0)// Không cake nào được tạo
{
App.mainWindow.mainContentFrame.Content = App.homePage;
}
else
{
App.homePage = new Home();
App.mainWindow.mainContentFrame.Content = App.homePage;
}
}
catch(Exception ex)
{
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace WebService.WCFREST
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
[OperationContract]
[WebGet(UriTemplate="/ToUpper/{input}", ResponseFormat = WebMessageFormat.Json)]
public string ToUpper(string input)
{
return input.ToUpper();
}
}
}
|
using System;
class SelectionSort
{
static void Main()
{
//Sorting an array means to arrange its elements in increasing order. Write a program to sort an array.
//Use the Selection sort algorithm: Find the smallest element, move it at the first position, find the
//smallest from the rest, move it at the second position, etc.
Console.Write("Enter number of elements: ");
int length = int.Parse(Console.ReadLine());
int[] array = new int[length];
int min = int.MaxValue;
int minIndex = 0;
int temp = 0;
string output;
for (int i = 0; i < length; i++)
{
Console.Write("Enter element {0}: ", i);
array[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < length; i++)
{
for (int j = i; j < length; j++)
{
if (array[j] < min)
{
min = array[j];
minIndex = j;
}
}
temp = array[i];
array[i] = min;
array[minIndex] = temp;
min = int.MaxValue;
}
output = string.Join(", ", array);
Console.WriteLine(output);
}
}
|
using MonoGame.Extended.Sprites;
using Xunit;
namespace MonoGame.Extended.Entities.Tests
{
//public class ComponentTypeTests
//{
// [Fact]
// public void CreateComponentType()
// {
// var type = typeof(Sprite);
// var componentType = new ComponentType(type, 3);
// Assert.Same(type, componentType.Type);
// Assert.Equal(3, componentType.Id);
// Assert.Equal(new ComponentType(typeof(Sprite), 3), componentType);
// Assert.Equal(componentType.Id, componentType.GetHashCode());
// }
//}
} |
using System;
using System.Collections.Generic;
using UnityEngine;
public class LifeManager : MonoBehaviour
{
public static GameObject player;
private static float life = 1.0f;
WavesVisuals visuals;
SinusMovement sinusMovement;
public float lifeLossBaseRate = 1 / 3000f;
private void Awake()
{
player = gameObject;
}
private void Start()
{
visuals = GetComponent<WavesVisuals>();
sinusMovement = GetComponent<SinusMovement>();
}
void FixedUpdate()
{
float distanceFromBaseFrequency = sinusMovement.currentFrequency - sinusMovement.baseFrequency;
float proportionalDistance;
if (distanceFromBaseFrequency > 0)
proportionalDistance = distanceFromBaseFrequency / (sinusMovement.frequencyMax - sinusMovement.baseFrequency);
else
proportionalDistance = distanceFromBaseFrequency / (sinusMovement.frequencyMin - sinusMovement.baseFrequency);
Color color = new Color(1, 1 - proportionalDistance, 1 - proportionalDistance, life);
visuals.SetColor(color);
life -= lifeLossBaseRate + proportionalDistance * lifeLossBaseRate * 2;
if (life <= 0)
{
//Insert loss logic here
life = 0;
}
}
//Negative numbers also work
public static void IncreaseLife(float increaseAmount)
{
life += increaseAmount;
if (life > 1)
life = 1;
}
}
|
using GoalBook.Core.Domain.Entities;
using System;
namespace GoalBook.Core.Domain.Builders
{
/// <summary>
/// Собирает данные объекта цели.
/// </summary>
public class GoalBuilder
{
private readonly Goal _goal;
/// <summary>
/// Инициализирует поля.
/// </summary>
public GoalBuilder()
{
_goal = new();
}
/// <summary>
/// Присваивает идентификатор.
/// </summary>
/// <param name="id"> Параметр идентификатор. </param>
/// <returns> Объект строителя. </returns>
public GoalBuilder SetId(Guid id)
{
_goal.Id = id;
return this;
}
/// <summary>
/// Присваивает наименование.
/// </summary>
/// <param name="title"> Параметр наименование. </param>
/// <returns> Объект строителя. </returns>
public GoalBuilder SetTitle(string title)
{
if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException("Передано пустое значение.", nameof(title));
}
_goal.Title = title;
return this;
}
/// <summary>
/// Присваивает описание.
/// </summary>
/// <param name="description"> Параметр описание. </param>
/// <returns> Объект строителя. </returns>
public GoalBuilder SetDescription(string description)
{
if (string.IsNullOrEmpty(description))
{
throw new ArgumentNullException("Передано пустое значение.", nameof(description));
}
_goal.Description = description;
return this;
}
/// <summary>
/// Присваивает даты создания и окончания.
/// </summary>
/// <param name="dateCreated"> Параметр дата создания. </param>
/// <param name="dateFinished"> Параметр дата окончания. </param>
/// <returns> Объект строителя. </returns>
public GoalBuilder SetDate(DateTime dateCreated, DateTime? dateFinished)
{
if ((dateFinished != null) && (dateFinished < DateTime.Now))
{
throw new ArgumentException("Некорректное значение даты окончания.", nameof(dateFinished));
}
_goal.DateCreated = dateCreated;
_goal.DateFinished = dateFinished;
return this;
}
/// <summary>
/// Возвращает собранный объект цели.
/// </summary>
/// <returns> Цель. </returns>
public Goal Build()
{
if (_goal.Id == default)
{
_goal.Id = Guid.NewGuid();
}
return _goal;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] CharacterController characterController;
[SerializeField] Animator characterAnimator;
[SerializeField] float movementSpeed = 5f;
[SerializeField] Transform followCamera;
[SerializeField] Transform groundCheck;
[SerializeField] LayerMask groundMask;
float turnSmoothVelocity;
float turnSmoothTime = 0.1f;
const float gravity = -35f;
Vector3 velocity;
float groundDistance = 0.49f;
float jumpHeight = 3f;
float terminalVelocity = -25f;
bool isGrounded;
bool validSlope;
Vector3 slideVelocity;
const float slideFriction = 0.8f;
void Update()
{
CheckGrounded();
HandleMovement();
HandleJumping();
HandleSliding();
}
private void CheckGrounded() {
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
characterAnimator.SetBool("IsGrounded", isGrounded);
if(isGrounded) {
velocity.y = 0f;
}
}
private void HandleMovement() {
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
characterAnimator.SetFloat("Vertical", vertical);
characterAnimator.SetFloat("Horizontal", horizontal);
transform.eulerAngles = new Vector3(0f, Camera.main.transform.eulerAngles.y, 0f);
if(direction.magnitude >= 0.1f) {
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + followCamera.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
// transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
characterController.Move(moveDirection * movementSpeed * Time.deltaTime);
}
}
private void HandleJumping() {
if (Input.GetButtonDown("Jump") && isGrounded) {
characterAnimator.SetTrigger("Jump");
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
if (velocity.y < terminalVelocity) {
velocity.y = terminalVelocity;
}
characterController.Move(velocity * Time.deltaTime);
}
void OnControllerColliderHit (ControllerColliderHit hit) {
Vector3 groundNormal = hit.normal;
Debug.DrawLine(transform.position, transform.position + Vector3.up, Color.yellow, 1f);
Debug.DrawLine(transform.position, transform.position + groundNormal, Color.green, 1f);
if(Vector3.Angle(Vector3.up, groundNormal) < characterController.slopeLimit) {
validSlope = true;
slideVelocity = Vector3.zero;
} else {
validSlope = false;
slideVelocity.x += (1f - groundNormal.y) * groundNormal.x * (1f - slideFriction);
slideVelocity.z += (1f - groundNormal.y) * groundNormal.z * (1f - slideFriction);
}
}
private void HandleSliding() {
if(!validSlope) {
characterController.Move(slideVelocity * Time.deltaTime);
}
}
void OnDrawGizmos() {
Gizmos.DrawWireSphere(groundCheck.position, groundDistance);
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Senai.Sistema.Carfel.ProjetoFinalDezoito.Models;
namespace Senai.Sistema.Carfel.ProjetoFinalDezoito.Repositorio {
public class ComentarioRepositorio {
public ComentarioModel Criar (ComentarioModel comentario) {
if (File.Exists ("comentarioDB.txt")) {
comentario.Id = File.ReadAllLines ("comentarioDB.txt").Length + 1;
} else {
comentario.Id = 1;
}
UsuarioModel usuario = new UsuarioModel ();
using (StreamWriter sw = new StreamWriter ("comentarioDB.txt", true)) {
sw.WriteLine ($"{comentario.Id};{comentario.Descricao};{comentario.DataCriacao};{comentario.Aprovado};{comentario.NomeUsuario}");
}
return comentario;
}
public List<ComentarioModel> ListarADM () => LerTxtNaoAprovado ();
public List<ComentarioModel> Listar () => LerTxtAprovado ();
private List<ComentarioModel> LerTxtNaoAprovado () {
List<ComentarioModel> lsComentarios = new List<ComentarioModel> ();
if (File.Exists ("comentarioDB.txt")) {
string[] lines = File.ReadAllLines ("comentarioDB.txt");
foreach (string line in lines) {
if (string.IsNullOrEmpty (line)) {
continue;
}
string[] dadosLine = line.Split (';');
if (!Boolean.Parse (dadosLine[3])) {
ComentarioModel comentario = new ComentarioModel (
id: int.Parse (dadosLine[0]),
descricao: (dadosLine[1]),
dataCriacao: DateTime.Parse (dadosLine[2]),
aprovado: Boolean.Parse (dadosLine[3]),
nomeUsuario: (dadosLine[4])
);
lsComentarios.Add (comentario);
}
}
}
return lsComentarios .OrderBy (x => x.DataCriacao).Reverse ().ToList () ;
}
private List<ComentarioModel> LerTxtAprovado () {
List<ComentarioModel> lsComentarios = new List<ComentarioModel> ();
if (File.Exists ("comentarioDB.txt")) {
string[] lines = File.ReadAllLines ("comentarioDB.txt");
foreach (string line in lines) {
if (string.IsNullOrEmpty (line)) {
continue;
}
string[] dadosLine = line.Split (';');
if (Boolean.Parse (dadosLine[3])) {
ComentarioModel comentario = new ComentarioModel (
id: int.Parse (dadosLine[0]),
descricao: (dadosLine[1]),
dataCriacao: DateTime.Parse (dadosLine[2]),
aprovado: Boolean.Parse (dadosLine[3]),
nomeUsuario: (dadosLine[4])
);
lsComentarios.Add (comentario);
}
}
}
return lsComentarios .OrderBy (x => x.DataCriacao).Reverse ().ToList () ;
}
public static void Excluir(int id)
{
//Abre o stream de leitura do arquivo
string[] linhas = File.ReadAllLines("comentarioDB.txt");
//Lê cada registro no CSV
for (int i = 0; i < linhas.Length; i++)
{
//Separa os dados da linha
string[] dadosDaLinha = linhas[i].Split(';');
if (id.ToString() == dadosDaLinha[0]) {
linhas[i] = "";
break;
}
}
File.WriteAllLines("comentarioDB.txt", linhas);
}
public static void Aprovar(int id)
{
//Abre o stream de leitura do arquivo
string[] linhas = File.ReadAllLines("comentarioDB.txt");
//Lê cada registro no DataBase
for (int i = 0; i < linhas.Length; i++)
{
//Separa os dados da linha
string[] dadosDaLinha = linhas[i].Split(';');
if (id.ToString() == dadosDaLinha[0]) {
linhas[i] = $"{dadosDaLinha[0]};{dadosDaLinha[1]};{dadosDaLinha[2]};True;{dadosDaLinha[4]};";
continue;
}
}
File.WriteAllLines("comentarioDB.txt", linhas);
}
}
} |
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moonmile.XmlDom;
using System.Xml.Linq;
namespace TestXmlDom
{
[TestClass]
public class TestXNavi
{
[TestMethod]
public void TestNormal1()
{
XDocument doc = new XDocument(
new XElement("root",
new XElement("person",
new XElement("name", "masuda"))));
var q = new XNavigator(doc.FirstNode)
.Where(n => n.TagName() == "name")
.FirstOrDefault();
Assert.AreEqual("masuda", q.Value());
}
[TestMethod]
public void TestNormal2()
{
XDocument doc = new XDocument(
new XElement("root",
new XElement("person",
new XElement("name", "masuda"),
new XElement("name", "yamada"),
new XElement("name", "yamasaki"))));
// タグが検索できた場合
var q = new XNavigator(doc.FirstNode)
.Where(n => n.TagName() == "name")
.Select( n => n );
Assert.AreEqual(3, q.Count());
Assert.AreEqual("masuda", q.First().Value());
}
[TestMethod]
public void TestNormal3()
{
XDocument doc = new XDocument(
new XElement("root",
new XElement("person",
new XAttribute("id", "1"),
new XElement("name", "masuda"),
new XElement("age","44")),
new XElement("person",
new XAttribute("id", "2"),
new XElement("name", "yamada"),
new XElement("age","20")),
new XElement("person",
new XAttribute("id", "3"),
new XElement("name", "tanaka"),
new XElement("age","10"))));
// タグが検索できた場合
var q = new XNavigator(doc.FirstNode)
.Where(n => n.Attrs("id") == "2")
.FirstOrDefault();
Assert.AreEqual("person", q.TagName());
// 拡張メソッドを利用
Assert.AreEqual("yamada", q.Child("name").Value());
Assert.AreEqual("20", q.Child("age").Value());
}
[TestMethod]
public void TestNormal4()
{
XDocument doc = new XDocument(
new XElement("root",
new XElement("person",
new XAttribute("id", "1"),
new XElement("name", "masuda"),
new XElement("age","44")),
new XElement("person",
new XAttribute("id", "2"),
new XElement("name", "yamada"),
new XElement("age","20")),
new XElement("person",
new XAttribute("id", "3"),
new XElement("name", "tanaka"),
new XElement("age","10"))));
// クエリ文にしてみる
var q = from n in new XNavigator(doc.FirstNode)
where n.Attrs("id") == "2"
select n;
Assert.AreEqual("person", q.First().TagName());
// 拡張メソッドを利用
Assert.AreEqual("yamada", q.First().Child("name").Value());
Assert.AreEqual("20", q.First().Child("age").Value());
}
}
}
|
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 CamadaApresentacao
{
public partial class FrmRepPregacoes : Form
{
public FrmRepPregacoes()
{
InitializeComponent();
}
private void FrmRepPregacoes_Load(object sender, EventArgs e)
{
// TODO: esta linha de código carrega dados na tabela 'dbpregacoesDataSet.programa'. Você pode movê-la ou removê-la conforme necessário.
this.programaTableAdapter.Fill(this.dbpregacoesDataSet.programa);
this.reportViewer1.RefreshReport();
}
}
}
|
using UnityEngine;
public class rotateY : MonoBehaviour
{
#region Fields
[SerializeField]
private float turnSpeed;
#endregion
#region Unity Methods
void Update()
{
this.transform.Rotate(new Vector3(0.0f, this.turnSpeed * Time.deltaTime, 0.0f));
}
#endregion
} |
using System;
namespace Lab3
{
public class Circle
{
double diameter;
Point center;
public void SetDiameter(string diameter)
{
double newDiameter;
if (diameter != null)
newDiameter = double.Parse(diameter);
else
throw new ArgumentNullException("diameter");
if (newDiameter >= 0)
this.diameter = newDiameter;
else
throw new ArgumentException("Value is not a positive double", "diameter");
}
public void SetDiameter(double diameter)
{
if (diameter >= 0)
this.diameter = diameter;
else
throw new ArgumentException("Value is not a positive double", "diameter");
}
public double GetDiameter()
{
return diameter;
}
public void SetCenter(Point p)
{
if(p != null)
center = p;
else
throw new ArgumentNullException("center");
}
public Point GetCenter()
{
return center;
}
public Circle() { }
public Circle(double diameter, Point center)
{
this.diameter = diameter;
this.center = center;
}
public double GetCircumference()
{
return diameter * Math.PI;
}
public double GetArea()
{
return (diameter / 2) * (diameter / 2) * Math.PI;
}
}
}
|
using UnityEngine;
using System.Collections;
public class HealthController : MonoBehaviour {
/// <summary>
/// Saúde inicial do objeto
/// </summary>
public float startingHealth;
/// <summary>
/// Saúde máxima do objeto
/// </summary>
public float maxHealth = 100;
/// <summary>
/// Tempo que o objeto fica invulnerável após receber dano (em segundos).
/// </summary>
public float invulnerableTime;
/// <summary>
/// Contador de tempo de invulnerabilidade
/// </summary>
private float invulnerableCounter;
// Propriedades
/// <summary>
/// Indica se o objeto está invulnerável ou não.
/// </summary>
public bool IsInvulnerable { get; private set; }
/// <summary>
/// Saúde atual do objeto
/// </summary>
public float CurrentHealth { get; set; }
// Eventos
public delegate void EnterInvulnerableModeAction();
public event EnterInvulnerableModeAction OnEnterInvulnerableMode;
public delegate void ExitInvulnerableModeAction();
public event ExitInvulnerableModeAction OnExitInvulnerableMode;
public delegate void BeforeTakeDamageAction(float amount);
public event BeforeTakeDamageAction OnBeforeTakeDamage;
public delegate void TakeDamageAction(float amount);
public event TakeDamageAction OnTakeDamage;
public delegate void ReachZeroHealthAction();
public event ReachZeroHealthAction OnReachZeroHealth;
void Start () {
// Atribui o valor inicial para a saúde do objeto.
if (startingHealth <= 0)
CurrentHealth = 1;
else if (startingHealth > maxHealth)
CurrentHealth = maxHealth;
else
CurrentHealth = startingHealth;
}
void Update () {
if (IsInvulnerable)
{
// Conta o tempo em que está invulnerável
invulnerableCounter += Time.deltaTime;
// Ao atingir o tempo, sai do modo de invulnerabildade
if (invulnerableCounter >= invulnerableTime)
{
invulnerableCounter = 0;
IsInvulnerable = false;
// Chama o evento de sair do modo invulnerável
if (OnExitInvulnerableMode != null)
OnExitInvulnerableMode.Invoke();
}
}
}
public void TakeDamage(float amount)
{
if (IsInvulnerable) // Se estiver no modo invulnerável, não recebe dano.
return;
if (OnBeforeTakeDamage != null)
OnBeforeTakeDamage.Invoke(amount);
// Remove a quantidade de saúde passada como parâmetro
CurrentHealth -= amount;
// Chama o evento ao receber dano
if (OnTakeDamage != null)
OnTakeDamage.Invoke(amount);
// Chama evento ao zerar a saúde do objeto
if (CurrentHealth <= 0)
{
if (OnReachZeroHealth != null)
OnReachZeroHealth.Invoke();
}
// Altera o estado para invulnerável caso seja necessário
if (invulnerableTime > 0)
{
IsInvulnerable = true;
// Chama o evento de entrar em modo invulnerável
if (OnEnterInvulnerableMode != null)
OnEnterInvulnerableMode.Invoke();
}
}
public void Add(float amount)
{
if (Mathf.Sign(amount) == -1)
throw new System.Exception("O valor para ser adicionado à saúde não pode ser negativo");
float newHealth = CurrentHealth + amount;
if(newHealth > maxHealth)
{
CurrentHealth = maxHealth;
}else
{
CurrentHealth = newHealth;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Restaurant_System
{
public enum DrinkTypes
{
Alcohol,
FuzzyDrink,
Juice,
Water
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace SDKWebPortalWebAPI.Migrations
{
public partial class InitialCreateUnique : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddUniqueConstraint(
name: "AlternateKey_TC",
table: "FamilyMembers",
column: "TC");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropUniqueConstraint(
name: "AlternateKey_TC",
table: "FamilyMembers");
}
}
}
|
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Asset.BisnessLogic.Library.Organizations;
using Asset.Models.Library.EntityModels.OrganizationModels;
namespace AssetTrackingSystem.MVC.Controllers.Organizations
{
[Authorize]
public class BranchesController : Controller
{
private readonly OrganizationManager _organizationManager;
private readonly BranchManager _branchManager;
public BranchesController()
{
_organizationManager = new OrganizationManager();
_branchManager = new BranchManager();
}
// GET: Branches
public ActionResult Index()
{
var branches = _branchManager.GetBranchWithOrganization();
return View(branches.ToList());
}
// GET: Branches/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Branch branch = _branchManager.SingleBranch((int)id);
if (branch == null)
{
return HttpNotFound();
}
return View(branch);
}
// GET: Branches/Create
public ActionResult Create()
{
ViewBag.OrganizationId = new SelectList(_organizationManager.GetAll(), "Id", "Name");
return View();
}
// POST: Branches/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,OrganizationId,Name,ShortName,BranchCode")] Branch branch)
{
if (ModelState.IsValid)
{
bool isBranchName = _branchManager.IsBranchNameExist(branch.Name);
bool isBranchShortName = _branchManager.IsBranchShortNameExist(branch.ShortName);
bool isBranchCode = _branchManager.IsBranchCodeExist(branch.BranchCode);
if (isBranchName)
{
ViewBag.NameCssClass = "Alert Alert-warning";
ViewBag.NameMessageType = "Warning";
ViewBag.NameMessage = "This branch name is already exist!";
}
else if (isBranchShortName)
{
ViewBag.ShortNameCssClass = "Alert Alert-warning";
ViewBag.ShortNameMessageType = "Warning";
ViewBag.ShortNameMessage = "This branch short-name is already exist!";
}
else if (isBranchCode)
{
ViewBag.CodeCssClass = "Alert Alert-warning";
ViewBag.CodeMessageType = "Warning";
ViewBag.CodeMessage = "This branch code is already exist!";
}
else
{
_branchManager.Add(branch);
return RedirectToAction("Index");
}
}
ViewBag.OrganizationId = new SelectList(_organizationManager.GetAll(), "Id", "Name", branch.OrganizationId);
return View(branch);
}
// GET: Branches/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Branch branch = _branchManager.SingleBranch((int)id);
if (branch == null)
{
return HttpNotFound();
}
ViewBag.OrganizationId = new SelectList(_organizationManager.GetAll(), "Id", "Name", branch.OrganizationId);
return View(branch);
}
// POST: Branches/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,OrganizationId,Name,ShortName,BranchCode")] Branch branch)
{
if (ModelState.IsValid)
{
_branchManager.Update(branch);
return RedirectToAction("Index");
}
ViewBag.OrganizationId = new SelectList(_branchManager.GetAll(), "Id", "Name", branch.OrganizationId);
return View(branch);
}
// GET: Branches/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Branch branch = _branchManager.SingleBranch((int)id);
if (branch == null)
{
return HttpNotFound();
}
return View(branch);
}
// POST: Branches/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Branch branch = _branchManager.SingleBranch(id);
if (branch != null) _branchManager.Remove(branch);
return RedirectToAction("Index");
}
}
}
|
using Models.RegularGame;
using strange.extensions.signal.impl;
namespace Client.Signals
{
public class AddRegularGameViewSignal: Signal<BaseRegularGame>
{
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TQ.SaveFilesExplorer.Helpers
{
public static class TQPath
{
#region various path
public static string SaveDirectoryTQITModded
{
get
{
var p = $@"{PersonalFolderTQIT}\SaveData\User";
return Directory.Exists(p) ? p : null;
}
}
public static string[] SaveDirectoryTQITModdedPlayers
{
get
{
var p = SaveDirectoryTQITModded;
return p is null ? Array.Empty<string>() : Directory.GetDirectories(p, "_*");
}
}
public static string[] SaveDirectoryTQITModdedTransferStash
{
get
{
var sys = SaveDirectoryTQITTransferStash;
return sys is null ? Array.Empty<string>() : Directory.GetDirectories(sys);
}
}
public static string SaveDirectoryTQITTransferStash
{
get
{
var p = $@"{PersonalFolderTQIT}\SaveData\Sys";
return Directory.Exists(p) ? p : null;
}
}
public static string DefaultSaveDirectory
{
get
{
string path = SaveDirectoryTQIT;
if (path != null)
return path;
return SaveDirectoryTQ;
}
}
public static string SaveDirectoryTQ
{
get
{
var p = $@"{PersonalFolderTQ}\SaveData\Main";
return Directory.Exists(p) ? p : null;
}
}
public static string SaveDirectoryTQIT
{
get
{
var p = $@"{PersonalFolderTQIT}\SaveData\Main";
return Directory.Exists(p) ? p : null;
}
}
/// <summary>
/// Gets the Immortal Throne personal folder
/// </summary>
public static string PersonalFolderTQIT
{
get
{
return System.IO.Path.Combine(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "My Games"), "Titan Quest - Immortal Throne");
}
}
/// <summary>
/// Gets the Titan Quest Character personnal folder.
/// </summary>
public static string PersonalFolderTQ
{
get
{
return System.IO.Path.Combine(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "My Games"), "Titan Quest");
}
}
#endregion
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Zzz.PublicApi.Host
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddApplication<ZzzPublicApiModule>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.InitializeApplication();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.IO;
namespace EsMo.Android.Support.Async
{
public abstract class BaseAsyncTask<TParams,TResult> : AsyncTask<TParams, int, TResult>
{
Action<TParams[], TResult> onFinished;
protected TParams[] p;
protected override void OnPreExecute()
{
Process.SetThreadPriority(ThreadPriority.Background);
}
public BaseAsyncTask(Action<TParams[],TResult> onFinished)
{
this.onFinished = onFinished;
}
protected override void OnPostExecute(TResult result)
{
if (this.IsCancelled) return;
if(onFinished != null)
this.onFinished(p,result);
}
}
} |
using Common.CommunicationModel;
using Common.Repository;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Common.CommunicationBus
{
public class CommunicationBusModule
{
private XNode XmlRequest;
private ISqlQueryExecutor sqlQueryExecutor;
public CommunicationBusModule()
{
XmlRequest = null;
sqlQueryExecutor = new SqlQueryExecutor();
}
public CommunicationBusModule(ISqlQueryExecutor sqe)
{
sqlQueryExecutor = sqe;
}
public string SendRequest(string jsonRequest)
{
XmlRequest = JsonConvert.DeserializeXNode(jsonRequest, "Request");
XmlToSql xmlToSql = new XmlToSql();
string sqlQuery = xmlToSql.Convert(XmlRequest);
var xmlResponse = sqlQueryExecutor.ExecuteSqlQuery(sqlQuery);
return JsonConvert.SerializeXmlNode(xmlResponse, Formatting.Indented);
}
}
}
|
using DemoScriptShp.Poco;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WebParts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace DemoScriptShp.Dal
{
public static class SharePoint
{
public static void AnalizarColeccion(Config cfg)
{
AnalizarSitioRecursivo(cfg.Admin, cfg.Pass, cfg.Url);
}
private static void AnalizarSitioRecursivo(string admin, string pass, Uri url)
{
using (var ctx = GetContext(admin, pass, url))
{
Web oWebsite = ctx.Web;
ctx.Load(oWebsite, w => w.Webs, w => w.Title, w => w.Url);
ctx.ExecuteQuery();
Console.WriteLine("URL: " + oWebsite.Url);
AnalizarPaginasSitio(ctx, oWebsite);
foreach (Web oRecWebsite in oWebsite.Webs)
{
AnalizarSitioRecursivo(admin, pass, new Uri(oRecWebsite.Url));
}
}
}
private static void AnalizarPaginasSitio(ClientContext ctx, Web web)
{
string[] bibliotecas = { "Páginas del sitio", "SitePages" };
foreach (string biblioteca in bibliotecas)
{
try
{
List lista = web.Lists.GetByTitle(biblioteca);
ListItemCollection items = lista.GetItems(CamlQuery.CreateAllItemsQuery());
ctx.Load(lista);
ctx.Load(items);
ctx.ExecuteQuery();
Console.WriteLine(" LISTA: " + lista.Title);
foreach (ListItem li in items)
{
SetWP(ctx, li["FileRef"] as string);
}
}
catch (Microsoft.SharePoint.Client.ServerException ex)
{
Console.WriteLine(" Ex: " + ex.Message);
}
}
}
private static void SetWP(ClientContext ctx, string pageUrl)
{
if (string.IsNullOrEmpty(pageUrl))
return;
Console.WriteLine(" PAG: " + pageUrl);
File page = ctx.Web.GetFileByServerRelativeUrl(pageUrl);
LimitedWebPartManager wpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
string zoneId = WPContenido.ZoneId;
int zoneIdx = WPContenido.ZoneIndex;
var queryWPs = wpm.WebParts.Where(x => x.WebPart.Title == WPContenido.Title);
/*var queryWPs = from wp in wpm.WebParts
where wp.WebPart.Title == WPContenido.Title
select wp;*/
IEnumerable<WebPartDefinition> definicionesWP = ctx.LoadQuery(queryWPs);
ctx.ExecuteQuery();
//Elimina el WP si existe para actualizarlo
foreach (WebPartDefinition wpdef in definicionesWP)
{
ctx.Load(wpdef.WebPart);
ctx.ExecuteQuery();
zoneIdx = wpdef.WebPart.ZoneIndex;
Console.WriteLine(" WP encontrado en zona " + zoneIdx + ". Borrando");
wpdef.DeleteWebPart();
ctx.ExecuteQuery();
}
//Inserta nuevo
var importedWebPart = wpm.ImportWebPart(WPContenido.DefinicionWP(""));
var webPart = wpm.AddWebPart(importedWebPart.WebPart, zoneId, zoneIdx);
ctx.Load(webPart);
ctx.ExecuteQuery();
Console.WriteLine(" WP agregado.");
}
private static ClientContext GetContext(Config cfg)
{
return GetContext(cfg.Admin, cfg.Pass, cfg.Url);
}
private static ClientContext GetContext(string user, string password, Uri url)
{
var securePassword = new SecureString();
foreach (var ch in password)
securePassword.AppendChar(ch);
return new ClientContext(url)
{
Credentials = new SharePointOnlineCredentials(user, securePassword)
};
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Hospital.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace HospitalList.Controllers
{
public class SpecialtiesController : Controller
{
private readonly HospitalContext _db;
public SpecialtiesController(HospitalContext db)
{
_db = db;
}
public ActionResult Index()
{
List <Specialty> model = _db.Specialties.ToList();
return View (model);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Specialty specialty)
{
_db.Specialties.Add(specialty);
_db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Details(int id)
{
Specialty thisSpecialty = _db.Specialties
.Include(specialty => specialty.Doctors)
.ThenInclude(join => join.Doctor)
.FirstOrDefault(x => x.SpecialtyId == id);
return View(thisSpecialty);
}
public ActionResult Edit(int id)
{
Specialty thisSpecialty = _db.Specialties.FirstOrDefault(x=>x.SpecialtyId == id);
return View(thisSpecialty);
}
[HttpPost]
public ActionResult Edit(Specialty specialty)
{
_db.Entry(specialty).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Delete(int id)
{
Specialty thisSpecialty = _db.Specialties.FirstOrDefault(x => x.SpecialtyId == id);
return View(thisSpecialty);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Specialty thisSpecialty = _db.Specialties.FirstOrDefault(x => x.SpecialtyId ==id);
_db.Specialties.Remove(thisSpecialty);
_db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult AddDoctor(int id)
{
Specialty thisSpecialty = _db.Specialties.FirstOrDefault(x => x.SpecialtyId ==id);
ViewBag.DoctorId = new SelectList(_db.Doctors, "DoctorId", "DoctorName");
return View(thisSpecialty);
}
[HttpPost]
public ActionResult AddDoctor(Specialty specialty, int DoctorId)
{
if (DoctorId != 0)
{
_db.DoctorSpecialty.Add(new DoctorSpecialty() { DoctorId = DoctorId, SpecialtyId = specialty.SpecialtyId });
}
_db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult RemoveDoctor(int DoctorSpecialtyId)
{
DoctorSpecialty joinEntry = _db.DoctorSpecialty.FirstOrDefault(x => x.DoctorSpecialtyId == DoctorSpecialtyId);
_db.DoctorSpecialty.Remove(joinEntry);
_db.SaveChanges();
return RedirectToAction("Index"); // no view for Remove Doctor
}
}
}
|
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
// VisualNovelToolkit /_/_/_/_/_/_/_/_/_/.
// Copyright ©2013 - Sol-tribe. /_/_/_/_/_/_/_/_/_/.
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
using UnityEngine;
using System.Collections;
using System.Xml.Serialization;
namespace ViNoToolkit{
/// <summary>
/// Dialog Unit.
/// </summary>
[ System.Serializable]
public class DialogPartData {
[ XmlAttribute()] public bool active = true;
[ XmlAttribute()] public int dialogID = 0;
[ XmlAttribute()] public bool show = false;
[ XmlAttribute()] public bool isName = false;
[ XmlAttribute()] public bool isBGM = false;
[ XmlAttribute()] public bool isSE = false;
[ XmlAttribute()] public bool isVoice = false;
[ XmlAttribute()] public bool isAnim = false;
[ XmlAttribute()] public bool isClearMessageAfter = true;
[ XmlAttribute()] public int textBoxID = 0;
[ System.NonSerialized ] public bool toggle;
public string nameText = "";
public string dialogText = "";
[ XmlAttribute()] public DialogPartNodeActionType actionID;
// About Audio.
public string bgmAudioKey;
public string seAudioKey;
public string voiceAudioKey;
public int bgmAudioID;
public int seAudioID;
public int voiceAudioID;
/// <summary>
/// Actor entry.
/// </summary>
[ System.Serializable]
public class ActorEntry{
public string actorName;
public string state = null;
public ViNoToolkit.SceneEvent.ActorPosition position;
public bool withFade;
}
/// <summary>
/// Scene entry.
/// </summary>
[ System.Serializable]
public class SceneEntry{
public string sceneName;
public bool withFade;
public bool clearSceneAndLoad = true; // if true , under the "ADVScene" will be cleared.
}
/// <summary>
/// Events category data.
/// </summary>
[ System.Serializable]
public class DialogEventData : ViNoEventData{
public string targetObjectName;
public string methodName;
// Parameter strings.
public string[] attr = null; // key,value,key,value,....
[HideInInspector] public bool condition; // if condition is true , then flagName == isFlagTrue => Execute SendEvent .
[HideInInspector] public string flagName;
[HideInInspector] public bool isFlagTrue;
[HideInInspector] public float delaySeconds;
}
/// <summary>
/// EnterScene action data.
/// </summary>
public SceneEntry scene = null;
/// <summary>
/// EnterActor , ExitActor , MoveActor and ChangeState action data.
/// </summary>
public ActorEntry[] enterActorEntries;
public ActorEntry[] exitActorEntries;
/// <summary>
/// Events category data.
/// </summary>
public DialogEventData[] enterEventData = null;
public DialogEventData[] exitEventData = null;
/// <summary>
/// GetUserInput.
/// </summary>
public GetUserInputData inputData = null;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using FileImport.Base;
using FileImport.Common;
namespace FileImport.LayoutSample
{
public class Sample2 : ImportAttributes
{
#region "Methods"
public Sample2() : base(ImportEncodingType.Default, ImportType.Delimited, ";")
{
//Sample2 layout is delimited so it's not necessary define the layout
//All the columns are stored internally using "System.Data.DataColumn"
//and the columns are named as "Col_1", "Col_2", ... "Col_N"
}
#endregion
#region "Enum"
public enum RecordType
{
Header = 0,
Detail = 1,
Trailer = 2
}
#endregion
#region "Rows"
public List<Sample2.HeaderRow> HeaderRows = new List<Sample2.HeaderRow>();
public List<Sample2.DetailRow> DetailRows = new List<Sample2.DetailRow>();
public List<Sample2.TrailerRow> TrailerRows = new List<Sample2.TrailerRow>();
public class HeaderRow : LayoutRow
{
public HeaderRow(DataRow Row): base(Row)
{
this.Record = "Header";
}
public string Field1
{
get { return Row["Col_1"].ToString(); }
}
public string Field2
{
get { return Row["Col_2"].ToString(); }
}
}
public class DetailRow : LayoutRow
{
public DetailRow(DataRow Row)
: base(Row)
{
this.Record = "Detail";
}
public string Field1
{
get { return Row["Col_1"].ToString(); }
}
public string Field2
{
get { return Row["Col_2"].ToString(); }
}
public string Field3
{
get { return Row["Col_3"].ToString(); }
}
}
public class TrailerRow : LayoutRow
{
public TrailerRow(DataRow Row)
: base(Row)
{
this.Record = "Trailer";
}
public string Field1
{
get { return Row["Col_1"].ToString(); }
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BPiaoBao.Client.Module
{
public delegate void DoActionEventHander(object sender, PluginEventArgs args);
public class MessageObserver
{
private MessageObserver()
{
}
private static object lockIn = new object();
private static MessageObserver createInstance;
public static MessageObserver CreateInstance
{
get {
if (createInstance == null)
{
lock (lockIn)
{
if (createInstance == null)
createInstance = new MessageObserver();
}
}
return createInstance;
}
}
public event DoActionEventHander DoAction;
public void OnAction(PluginEventArgs args)
{
if (DoAction != null)
DoAction(this, args);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Emanate.Core;
using Emanate.Core.Configuration;
using Serilog;
namespace Emanate.Vso
{
public class VsoConfiguration : IInputConfiguration
{
public string Key { get; } = "vso";
public Memento CreateMemento()
{
Log.Information("=> VsoConfiguration.CreateMemento");
var moduleElement = new XElement("module");
moduleElement.Add(new XAttribute("key", Key));
moduleElement.Add(new XAttribute("type", "input"));
var devicesElement = new XElement("devices");
foreach (var device in Devices)
{
var deviceElement = device.CreateMemento();
devicesElement.Add(deviceElement);
}
moduleElement.Add(devicesElement);
return new Memento(moduleElement);
}
public void SetMemento(Memento memento)
{
Log.Information("=> VsoConfiguration.SetMemento");
if (memento.Key != Key)
throw new ArgumentException("Cannot load non-Visual Studio Online configuration");
// TODO: Error handling
var element = memento.Element;
var devicesElement = element.Element("devices");
if (devicesElement != null)
{
foreach (var deviceElement in devicesElement.Elements("device"))
{
var device = new VsoDevice();
device.SetMemento(deviceElement);
devices.Add(device);
}
}
}
public void AddDevice(VsoDevice deviceInfo)
{
devices.Add(deviceInfo);
}
private readonly List<VsoDevice> devices = new List<VsoDevice>();
public IEnumerable<IInputDevice> Devices => devices;
public void RemoveDevice(VsoDevice deviceInfo)
{
devices.Remove(deviceInfo);
}
}
} |
namespace Development.CodeGeneration.Editor.Templates
{
public partial class AnimationTrackTemplate
{
private readonly string _bindingName;
public AnimationTrackTemplate(string bindingName)
{
_bindingName = bindingName;
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using BPiaoBao.Common;
using BPiaoBao.Common.Enums;
using BPiaoBao.DomesticTicket.Domain.Models;
using BPiaoBao.DomesticTicket.Domain.Services;
using PnrAnalysis;
namespace BPiaoBao.DomesticTicket.Platforms.PTInterface
{
/// <summary>
/// 缓存接口政策
/// </summary>
public class CachePolicyManage
{
string platformCode = string.Empty;
int cacheDay = 10;
bool IsGetAll = true;
DataSet policyData;
PnrAnalysis.PnrModel pnrMode = null;
PnrAnalysis.PatModel patMode = null;
public CachePolicyManage(EnumPlatform platform, DataSet dsPolicy, PnrData pnrData)
{
//缓存政策几天过期
int.TryParse(System.Configuration.ConfigurationManager.AppSettings["CachePolicyDay"], out cacheDay);
//true缓存所有接口政策 false缓存最高的一条接口政策
IsGetAll = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["IsGetAll"]);
pnrMode = pnrData.PnrMode;
patMode = pnrData.PatMode;
this.policyData = dsPolicy;
this.platformCode = platform.ToString();
}
public void StartCachePolicy(object o)
{
StringBuilder sbAddSQL = new StringBuilder();
StringBuilder sbLog = new StringBuilder();
try
{
GetFlightBasicData manage = new GetFlightBasicData();
//获取政策
List<PolicyCache> policyList = GetPolicyList(this.policyData);
//过滤政策点数为负数或者0的政策
policyList = policyList.Where(p => p.Point > 0).ToList();
if (policyList.Count > 0)
{
int patchNo = 0;
sbLog.AppendFormat("IsGetAll={0}\r\n", IsGetAll);
//获取所有政策
if (IsGetAll)
{
//批量添加
manage.TableValuedToDB(policyList, patchNo, cacheDay);
}
else
{
#region 取一条最优的
PolicyCache Pc = policyList.OrderByDescending(p => p.Point).FirstOrDefault();
if (Pc != null)
{
sbAddSQL.Append("INSERT INTO [dbo].[PolicyCache]([_id],[PolicyId],[PlatformCode],[CarrierCode],[CabinSeatCode],[FromCityCode],[MidCityCode],[ToCityCode],[SuitableFlightNo],[ExceptedFlightNo],[SuitableWeek],[CheckinTime_FromTime],[CheckinTime_EndTime],[IssueTime_FromTime],[IssueTime_EndTime],[ServiceTime_WeekendTime_FromTime],[ServiceTime_WeekendTime_EndTime],[ServiceTime_WeekTime_FromTime],[ServiceTime_WeekTime_EndTime],[TFGTime_WeekendTime_FromTime],[TFGTime_WeekendTime_EndTime],[TFGTime_WeekTime_FromTime],[TFGTime_WeekTime_EndTime],[Remark],[TravelType],[PolicyType],[Point],[CacheDate],[CacheExpiresDate],[PatchNo])VALUES(");
sbAddSQL.AppendFormat("'{0}',", Pc._id.ToString());
sbAddSQL.AppendFormat("'{0}',", Pc.PolicyId.ToString());
sbAddSQL.AppendFormat("'{0}',", Pc.PlatformCode.ToString());
sbAddSQL.AppendFormat("'{0}',", Pc.CarrierCode.ToString());
sbAddSQL.AppendFormat("'{0}',", string.Join("/", Pc.CabinSeatCode));
sbAddSQL.AppendFormat("'{0}',", Pc.FromCityCode);
sbAddSQL.AppendFormat("'{0}',", Pc.MidCityCode);
sbAddSQL.AppendFormat("'{0}',", Pc.ToCityCode);
sbAddSQL.AppendFormat("'{0}',", string.Join("/", Pc.SuitableFlightNo));
sbAddSQL.AppendFormat("'{0}',", string.Join("/", Pc.ExceptedFlightNo));
string strSuitableWeek = "";
if (Pc.SuitableWeek != null && Pc.SuitableWeek.Length > 0)
{
List<string> ll = new List<string>();
for (int i = 0; i < Pc.SuitableWeek.Length; i++)
{
ll.Add(((int)Pc.SuitableWeek[i]).ToString());
}
strSuitableWeek = string.Join("/", ll.ToArray());
}
sbAddSQL.AppendFormat("'{0}',", strSuitableWeek);
sbAddSQL.AppendFormat("'{0}',", Pc.CheckinTime.FromTime.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.CheckinTime.EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.IssueTime.FromTime.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.IssueTime.EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.ServiceTime.WeekendTime.FromTime.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.ServiceTime.WeekendTime.EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.ServiceTime.WeekTime.FromTime.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.ServiceTime.WeekTime.EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.TFGTime.WeekendTime.FromTime.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.TFGTime.WeekendTime.EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.TFGTime.WeekTime.FromTime.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.TFGTime.WeekTime.EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.Remark);
sbAddSQL.AppendFormat("'{0}',", ((int)Pc.TravelType).ToString());
sbAddSQL.AppendFormat("'{0}',", Pc.PolicyType.ToString());
sbAddSQL.AppendFormat(" {0},", Pc.Point);
sbAddSQL.AppendFormat("'{0}',", Pc.CacheDate.ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat("'{0}',", Pc.CacheExpiresDate.AddDays(cacheDay).ToString("yyyy-MM-dd HH:mm:ss"));
sbAddSQL.AppendFormat(" {0} ", patchNo);
sbAddSQL.Append(") \r\n");
string sqlExist = string.Format("select count(*) from PolicyCache where PolicyId='{0}' ", Pc.PolicyId);
object obj = manage.ExecuteScalar(sqlExist);
bool IsExist = false;
if (obj != null)
{
int cc = int.Parse(obj.ToString());
if (cc > 0)
{
IsExist = true;
}
}
if (!IsExist)
{
manage.ExecuteSQL(sbAddSQL.ToString());
}
}
#endregion
}
//删除重复的
manage.ExecRepeatSQL();
}
}
catch (Exception ex)
{
sbLog.Append("异常信息:" + ex.Message + "\r\n");
if (sbAddSQL.ToString() != "")
{
sbLog.Append("SQL:" + sbAddSQL.ToString() + "\r\n\r\n");
}
}
finally
{
if (sbAddSQL.ToString() != "")
{
PTLog.LogWrite(sbLog.ToString(), string.Format(@"PT\StartCachePolicy{0}_Err", this.platformCode));
}
}
}
private List<PolicyCache> GetPolicyList(DataSet dsPolicy)
{
List<PolicyCache> policyList = new List<PolicyCache>();
string platformCode = this.platformCode.Replace("_", "");
if (dsPolicy != null && dsPolicy.Tables.Count > 0)
{
if (dsPolicy.Tables.Contains(platformCode)
&& dsPolicy.Tables.Contains("Policy")
&& dsPolicy.Tables[platformCode].Rows.Count > 0)
{
DataRow dr_Price = dsPolicy.Tables[platformCode].Rows[0];
if (dr_Price["Status"].ToString() == "T")
{
DataRowCollection drs = dsPolicy.Tables[0].Rows;
foreach (DataRow dr in drs)
{
try
{
PolicyCache pc = new PolicyCache();
pc.PlatformCode = platformCode;
pc.CacheDate = System.DateTime.Now;
pc.CacheExpiresDate = pc.CacheDate.AddDays(cacheDay);
#region 处理每一条数据
switch (platformCode)
{
case "517":
{
pc = _517DrToPolicyCache(pc, dr);
}
break;
case "8000YI":
{
if (int.Parse(dr["A7"] != DBNull.Value ? dr["A7"].ToString() : "1") > 2)
{
continue;
}
if ((dr["A9"] != DBNull.Value ? dr["A9"].ToString() : "").ToUpper() == "ALL")
{
continue;
}
pc = _8000YIDrToPolicyCache(pc, dr);
}
break;
case "PiaoMeng":
{
pc = _PiaoMengDrToPolicyCache(pc, dr);
}
break;
case "Today":
{
pc = _TodayDrToPolicyCache(pc, dr);
}
break;
case "BaiTuo":
{
pc = _BaiTuoDrToPolicyCache(pc, dr);
}
break;
case "YeeXing":
{
pc = _YeeXingDrToPolicyCache(pc, dr);
}
break;
case "51Book":
{
pc = _51BookDrToPolicyCache(pc, dr);
}
break;
default:
break;
}
#endregion
//添加
policyList.Add(pc);
}
catch (Exception ex)
{
PTLog.LogWrite("GetPolicyList::" + ex.Message, string.Format(@"PT\GetPolicyList_{0}_Err", platformCode));
}
}//EndFor
}
}
}
return policyList;
}
private PolicyCache _517DrToPolicyCache(PolicyCache pc, DataRow dr)
{
pc.PolicyId = dr["PolicyID"] != DBNull.Value ? dr["PolicyID"].ToString() : "";
pc.CarrierCode = dr["CarryCode"] != DBNull.Value ? dr["CarryCode"].ToString() : "";
decimal strPoint = 0m;
decimal.TryParse((dr["Policy"] != DBNull.Value ? dr["Policy"].ToString() : "0"), out strPoint);
pc.Point = strPoint;
pc.CabinSeatCode = (dr["Space"] != DBNull.Value ? dr["Space"].ToString() : "").Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
pc.FromCityCode = dr["FromCity"] != DBNull.Value ? dr["FromCity"].ToString() : "";
pc.MidCityCode = "";
pc.ToCityCode = dr["ToCity"] != DBNull.Value ? dr["ToCity"].ToString() : "";
string strPolicyType = (dr["PolicyType"] != DBNull.Value ? dr["PolicyType"].ToString() : "B2B");
pc.PolicyType = (strPolicyType == "1") ? PolicyType.BSP : PolicyType.B2B;
pc.Remark = dr["Remark"] != DBNull.Value ? dr["Remark"].ToString() : "";
string strTravelType = dr["TravelType"] != DBNull.Value ? dr["TravelType"].ToString() : "单程";
//单程 单程/往返 往返 中转
pc.TravelType = strTravelType == "单程" ? TravelType.Oneway : (strTravelType == "往返" ? TravelType.Twoway : (strTravelType == "中转" ? TravelType.Connway : TravelType.OneTwoway));
string strFlightType = dr["FlightType"] != DBNull.Value ? dr["FlightType"].ToString() : "";
string[] strFlight = (dr["Flight"] != DBNull.Value ? dr["Flight"].ToString() : "").Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
if (strFlightType == "1")
{
pc.SuitableFlightNo = strFlight;
}
else if (strFlightType == "2")
{
pc.ExceptedFlightNo = strFlight;
}
else
{
pc.SuitableFlightNo = new string[] { };
}
//班期限制
string[] strDayOfWeek = (dr["ScheduleConstraints"] != DBNull.Value ? dr["ScheduleConstraints"].ToString() : "").Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); ;
List<DayOfWeek> daylist = new List<DayOfWeek>();
foreach (string item in strDayOfWeek)
{
switch (item)
{
case "1":
daylist.Add(DayOfWeek.Monday);
break;
case "2":
daylist.Add(DayOfWeek.Tuesday);
break;
case "3":
daylist.Add(DayOfWeek.Wednesday);
break;
case "4":
daylist.Add(DayOfWeek.Thursday);
break;
case "5":
daylist.Add(DayOfWeek.Friday);
break;
case "6":
daylist.Add(DayOfWeek.Saturday);
break;
case "7":
daylist.Add(DayOfWeek.Sunday);
break;
default: break;
}
}
pc.SuitableWeek = daylist.ToArray();
//时间
DateTime FromTime = System.DateTime.Now;
DateTime EndTime = System.DateTime.Now;
if (dr["EffectDate"] != DBNull.Value)
{
FromTime = DateTime.Parse(dr["EffectDate"].ToString());
}
if (dr["ExpirationDate"] != DBNull.Value)
{
EndTime = DateTime.Parse(dr["ExpirationDate"].ToString());
}
pc.CheckinTime = new TimePeriod()
{
FromTime = FromTime,
EndTime = EndTime
};
pc.IssueTime = new TimePeriod()
{
FromTime = FromTime,
EndTime = EndTime
};
DateTime WeekStartTime = System.DateTime.Now;
DateTime WeekEndTime = System.DateTime.Now;
if (dr["GYOnlineTime"] != DBNull.Value)
{
string[] strArrTime = dr["GYOnlineTime"].ToString().Split('-');
if (strArrTime.Length == 2)
{
WeekStartTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strArrTime[0] + ":00");
WeekEndTime = DateTime.Parse(WeekEndTime.ToString("yyyy-MM-dd") + " " + strArrTime[1] + ":00");
}
}
DateTime WeekendStartTime = System.DateTime.Now;
DateTime WeekendEndTime = System.DateTime.Now;
if (dr["GYOutlineTime"] != DBNull.Value)
{
string[] strArrTime = dr["GYOutlineTime"].ToString().Split('-');
if (strArrTime.Length == 2)
{
WeekendStartTime = DateTime.Parse(WeekendStartTime.ToString("yyyy-MM-dd") + " " + strArrTime[0] + ":00");
WeekendEndTime = DateTime.Parse(WeekendEndTime.ToString("yyyy-MM-dd") + " " + strArrTime[1] + ":00");
}
}
pc.ServiceTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = WeekStartTime,
EndTime = WeekEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = WeekendStartTime,
EndTime = WeekendEndTime
}
};
DateTime VoidWeekTimeStartTime = System.DateTime.Now;
DateTime VoidWeekTimeEndTime = System.DateTime.Now;
if (dr["GYFPTime"] != DBNull.Value)
{
string[] strArrTime = dr["GYFPTime"].ToString().Split('-');
if (strArrTime.Length == 2)
{
VoidWeekTimeStartTime = DateTime.Parse(VoidWeekTimeStartTime.ToString("yyyy-MM-dd") + " " + strArrTime[0] + ":00");
VoidWeekTimeEndTime = DateTime.Parse(VoidWeekTimeEndTime.ToString("yyyy-MM-dd") + " " + strArrTime[1] + ":00");
}
}
DateTime VoidWeekendStartTime = System.DateTime.Now;
DateTime VoidWeekendEndTime = System.DateTime.Now;
if (dr["GYFPTimeNew"] != DBNull.Value)
{
string[] strArrTime = dr["GYFPTimeNew"].ToString().Split('-');
if (strArrTime.Length == 2)
{
VoidWeekendStartTime = DateTime.Parse(VoidWeekendStartTime.ToString("yyyy-MM-dd") + " " + strArrTime[0] + ":00");
VoidWeekendEndTime = DateTime.Parse(VoidWeekendEndTime.ToString("yyyy-MM-dd") + " " + strArrTime[1] + ":00");
}
}
pc.TFGTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = VoidWeekTimeStartTime,
EndTime = VoidWeekTimeEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = VoidWeekendStartTime,
EndTime = VoidWeekendEndTime
}
};
return pc;
}
private PolicyCache _8000YIDrToPolicyCache(PolicyCache pc, DataRow dr)
{
pc.PolicyId = dr["A1"] != DBNull.Value ? dr["A1"].ToString() : "";
pc.FromCityCode = (dr["A2"] != DBNull.Value ? dr["A2"].ToString() : "").ToUpper();//.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
pc.ToCityCode = (dr["A3"] != DBNull.Value ? dr["A3"].ToString() : "").ToUpper();//.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
pc.CarrierCode = (dr["A4"] != DBNull.Value ? dr["A4"].ToString() : "").ToUpper();
pc.SuitableFlightNo = (dr["A5"] != DBNull.Value ? dr["A5"].ToString() : "").ToUpper().Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
pc.ExceptedFlightNo = (dr["A6"] != DBNull.Value ? dr["A6"].ToString() : "").ToUpper().Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
int i_TravelType = int.Parse(dr["A7"] != DBNull.Value ? dr["A7"].ToString() : "1");
//if (i_TravelType > 2)
//{
// continue;
//}
pc.TravelType = (TravelType)i_TravelType;
decimal point = decimal.Parse(dr["A8"] != DBNull.Value ? dr["A8"].ToString() : "0");
pc.Point = point;
pc.CabinSeatCode = (dr["A9"] != DBNull.Value ? dr["A9"].ToString() : "").ToUpper().Replace("#", "").Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
DateTime FromTime = System.DateTime.Now;
DateTime EndTime = System.DateTime.Now;
if (dr["A10"] != DBNull.Value)
{
FromTime = DateTime.Parse(dr["A10"].ToString());
}
if (dr["A11"] != DBNull.Value)
{
EndTime = DateTime.Parse(dr["A11"].ToString());
}
pc.CheckinTime = new TimePeriod()
{
FromTime = FromTime,
EndTime = EndTime
};
pc.IssueTime = new TimePeriod()
{
FromTime = FromTime,
EndTime = EndTime
};
DateTime WeekStartTime = System.DateTime.Now;
DateTime WeekEndTime = System.DateTime.Now;
if (dr["A12"] != DBNull.Value)
{
string[] strArrTime = dr["A12"].ToString().Split('|');
if (strArrTime.Length == 2)
{
WeekStartTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strArrTime[0] + ":00");
WeekEndTime = DateTime.Parse(WeekEndTime.ToString("yyyy-MM-dd") + " " + strArrTime[1] + ":00");
}
}
DateTime WeekendStartTime = System.DateTime.Now;
DateTime WeekendEndTime = System.DateTime.Now;
if (dr["A13"] != DBNull.Value)
{
string[] strArrTime = dr["A13"].ToString().Split('|');
if (strArrTime.Length == 2)
{
WeekendStartTime = DateTime.Parse(WeekendStartTime.ToString("yyyy-MM-dd") + " " + strArrTime[0] + ":00");
WeekendEndTime = DateTime.Parse(WeekendEndTime.ToString("yyyy-MM-dd") + " " + strArrTime[1] + ":00");
}
}
pc.ServiceTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = WeekStartTime,
EndTime = WeekEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = WeekendStartTime,
EndTime = WeekendEndTime
}
};
string strPolicyType = (dr["A16"] != DBNull.Value ? dr["A16"].ToString() : "B2B");
pc.PolicyType = (strPolicyType == "B2B") ? PolicyType.B2B : PolicyType.BSP;
//是否包含换编码
pc.Remark = dr["A17"] != DBNull.Value ? dr["A17"].ToString() : "";
DateTime VoidWeekTimeStartTime = System.DateTime.Now;
DateTime VoidWeekTimeEndTime = System.DateTime.Now;
if (dr["A19"] != DBNull.Value)
{
string[] strArrTime = dr["A19"].ToString().Split('|');
if (strArrTime.Length == 2)
{
VoidWeekTimeStartTime = DateTime.Parse(VoidWeekTimeStartTime.ToString("yyyy-MM-dd") + " " + strArrTime[0] + ":00");
VoidWeekTimeEndTime = DateTime.Parse(VoidWeekTimeEndTime.ToString("yyyy-MM-dd") + " " + strArrTime[1] + ":00");
}
}
DateTime VoidWeekendStartTime = System.DateTime.Now;
DateTime VoidWeekendEndTime = System.DateTime.Now;
if (dr["A20"] != DBNull.Value)
{
string[] strArrTime = dr["A20"].ToString().Split('|');
if (strArrTime.Length == 2)
{
VoidWeekendStartTime = DateTime.Parse(VoidWeekendStartTime.ToString("yyyy-MM-dd") + " " + strArrTime[0] + ":00");
VoidWeekendEndTime = DateTime.Parse(VoidWeekendEndTime.ToString("yyyy-MM-dd") + " " + strArrTime[1] + ":00");
}
}
pc.TFGTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = VoidWeekTimeStartTime,
EndTime = VoidWeekTimeEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = VoidWeekendStartTime,
EndTime = VoidWeekendEndTime
}
};
string[] strDayOfWeek = (dr["A21"] != DBNull.Value ? dr["A21"].ToString() : "").ToUpper().Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
List<DayOfWeek> daylist = new List<DayOfWeek>();
foreach (string item in strDayOfWeek)
{
switch (item)
{
case "1":
daylist.Add(DayOfWeek.Monday);
break;
case "2":
daylist.Add(DayOfWeek.Tuesday);
break;
case "3":
daylist.Add(DayOfWeek.Wednesday);
break;
case "4":
daylist.Add(DayOfWeek.Thursday);
break;
case "5":
daylist.Add(DayOfWeek.Friday);
break;
case "6":
daylist.Add(DayOfWeek.Saturday);
break;
case "0":
daylist.Add(DayOfWeek.Sunday);
break;
default: break;
}
}
pc.SuitableWeek = daylist.ToArray();
pc.CacheDate = System.DateTime.Now;
return pc;
}
private PolicyCache _51BookDrToPolicyCache(PolicyCache pc, DataRow dr)
{
pc.PolicyId = dr["Id"] != DBNull.Value ? dr["Id"].ToString() : "";
pc.CarrierCode = dr["airlineCode"] != DBNull.Value ? dr["airlineCode"].ToString() : "";
decimal strPoint = 0m;
decimal.TryParse(dr["Commission"] != DBNull.Value ? dr["Commission"].ToString() : "0", out strPoint);
pc.Point = strPoint;
pc.CabinSeatCode = (dr["seatClass"] != DBNull.Value ? dr["seatClass"].ToString() : "").Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
//航线
string[] strFlightCourse = (dr["flightCourse"] != DBNull.Value ? dr["flightCourse"].ToString() : "").Split('-');
if (strFlightCourse != null && strFlightCourse.Length == 2)
{
pc.FromCityCode = strFlightCourse[0];
pc.MidCityCode = "";
pc.ToCityCode = strFlightCourse[1];
}
string strPolicyType = (dr["policyType"] != DBNull.Value ? dr["policyType"].ToString() : "B2B");
pc.PolicyType = (strPolicyType == "B2B") ? PolicyType.B2B : PolicyType.BSP;
pc.Remark = dr["comment"] != DBNull.Value ? dr["comment"].ToString() : "";
//单程 单程/往返 往返 中转
string strTravelType = dr["routeType"] != DBNull.Value ? dr["routeType"].ToString() : "";
pc.TravelType = strTravelType == "OW" ? TravelType.Oneway : (strTravelType == "RT" ? TravelType.Twoway : TravelType.Connway);
//用","隔开
string[] strflightNoIncluding = (dr["flightNoIncluding"] != DBNull.Value ? dr["flightNoIncluding"].ToString() : "").Split(new string[] { "/", ",", "," }, StringSplitOptions.RemoveEmptyEntries);
pc.SuitableFlightNo = strflightNoIncluding;
string[] strflightNoExclude = (dr["flightNoExclude"] != DBNull.Value ? dr["flightNoExclude"].ToString() : "").Split(new string[] { "/", ",", "," }, StringSplitOptions.RemoveEmptyEntries);
pc.ExceptedFlightNo = strflightNoExclude;
//适用班期
string[] strDayOfWeek = (dr["flightCycle"] != DBNull.Value ? dr["flightCycle"].ToString() : "").Split(new string[] { "/", ",", "," }, StringSplitOptions.RemoveEmptyEntries); ;
List<DayOfWeek> daylist = new List<DayOfWeek>();
foreach (string item in strDayOfWeek)
{
switch (item)
{
case "1":
daylist.Add(DayOfWeek.Monday);
break;
case "2":
daylist.Add(DayOfWeek.Tuesday);
break;
case "3":
daylist.Add(DayOfWeek.Wednesday);
break;
case "4":
daylist.Add(DayOfWeek.Thursday);
break;
case "5":
daylist.Add(DayOfWeek.Friday);
break;
case "6":
daylist.Add(DayOfWeek.Saturday);
break;
case "0":
daylist.Add(DayOfWeek.Sunday);
break;
default: break;
}
}
pc.SuitableWeek = daylist.ToArray();
//时间
DateTime FromTime = System.DateTime.Now;
DateTime EndTime = System.DateTime.Now;
if (dr["startDate"] != DBNull.Value)
{
FromTime = DateTime.Parse(dr["startDate"].ToString());
}
if (dr["expiredDate"] != DBNull.Value)
{
EndTime = DateTime.Parse(dr["expiredDate"].ToString());
}
pc.CheckinTime = new TimePeriod()
{
FromTime = FromTime,
EndTime = EndTime
};
FromTime = System.DateTime.Now;
EndTime = System.DateTime.Now;
if (dr["printTicketStartDate"] != DBNull.Value)
{
FromTime = DateTime.Parse(dr["printTicketStartDate"].ToString());
}
if (dr["printTicketExpiredDate"] != DBNull.Value)
{
EndTime = DateTime.Parse(dr["printTicketExpiredDate"].ToString());
}
pc.IssueTime = new TimePeriod()
{
FromTime = FromTime,
EndTime = EndTime
};
DateTime WeekStartTime = System.DateTime.Now;
DateTime WeekEndTime = System.DateTime.Now;
if (dr["workTime"] != DBNull.Value)
{
string[] strArrTime = dr["workTime"].ToString().Split('-');
if (strArrTime.Length == 2)
{
WeekStartTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strArrTime[0] + ":00");
WeekEndTime = DateTime.Parse(WeekEndTime.ToString("yyyy-MM-dd") + " " + strArrTime[1] + ":00");
}
}
DateTime WeekendStartTime = System.DateTime.Now;
DateTime WeekendEndTime = System.DateTime.Now;
if (dr["workTime"] != DBNull.Value)
{
string[] strArrTime = dr["workTime"].ToString().Split('-');
if (strArrTime.Length == 2)
{
WeekendStartTime = DateTime.Parse(WeekendStartTime.ToString("yyyy-MM-dd") + " " + strArrTime[0] + ":00");
WeekendEndTime = DateTime.Parse(WeekendEndTime.ToString("yyyy-MM-dd") + " " + strArrTime[1] + ":00");
}
}
pc.ServiceTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = WeekStartTime,
EndTime = WeekEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = WeekendStartTime,
EndTime = WeekendEndTime
}
};
DateTime VoidWeekTimeStartTime = System.DateTime.Now;
DateTime VoidWeekTimeEndTime = System.DateTime.Now;
if (dr["chooseOutWorkTime"] != DBNull.Value)
{
string[] strArrTime = dr["chooseOutWorkTime"].ToString().Split('-');
if (strArrTime.Length == 2)
{
VoidWeekTimeStartTime = DateTime.Parse(VoidWeekTimeStartTime.ToString("yyyy-MM-dd") + " " + strArrTime[0] + ":00");
VoidWeekTimeEndTime = DateTime.Parse(VoidWeekTimeEndTime.ToString("yyyy-MM-dd") + " " + strArrTime[1] + ":00");
}
}
DateTime VoidWeekendStartTime = System.DateTime.Now;
DateTime VoidWeekendEndTime = System.DateTime.Now;
if (dr["chooseOutWorkTime"] != DBNull.Value)
{
string[] strArrTime = dr["chooseOutWorkTime"].ToString().Split('-');
if (strArrTime.Length == 2)
{
VoidWeekendStartTime = DateTime.Parse(VoidWeekendStartTime.ToString("yyyy-MM-dd") + " " + strArrTime[0] + ":00");
VoidWeekendEndTime = DateTime.Parse(VoidWeekendEndTime.ToString("yyyy-MM-dd") + " " + strArrTime[1] + ":00");
}
}
pc.TFGTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = VoidWeekTimeStartTime,
EndTime = VoidWeekTimeEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = VoidWeekendStartTime,
EndTime = VoidWeekendEndTime
}
};
return pc;
}
private PolicyCache _TodayDrToPolicyCache(PolicyCache pc, DataRow dr)
{
pc.PolicyId = dr["PolicyId"] != DBNull.Value ? dr["PolicyId"].ToString() : "";
pc.CarrierCode = pnrMode != null && pnrMode._LegList.Count > 0 ? pnrMode._LegList[0].AirCode : "";
decimal strPoint = 0m;
decimal.TryParse(dr["Discounts"] != DBNull.Value ? dr["Discounts"].ToString() : "0", out strPoint);
pc.Point = strPoint;
pc.CabinSeatCode = (dr["Cabin"] != DBNull.Value ? dr["Cabin"].ToString() : "").Split(new string[] { "/", "|" }, StringSplitOptions.RemoveEmptyEntries);
pc.FromCityCode = string.Join("/", (dr["ScityE"] != DBNull.Value ? dr["ScityE"].ToString() : "").Split(new string[] { "/", "|" }, StringSplitOptions.RemoveEmptyEntries));
pc.MidCityCode = "";
pc.ToCityCode = string.Join("/", (dr["EcityE"] != DBNull.Value ? dr["EcityE"].ToString() : "").Split(new string[] { "/", "|" }, StringSplitOptions.RemoveEmptyEntries));
pc.PolicyType = string.Compare(dr["RateType"].ToString().Trim(), "B2P", true) == 0 ? PolicyType.BSP : PolicyType.B2B;
pc.Remark = dr["Remark"] != DBNull.Value ? dr["Remark"].ToString() : "";
string strTravelType = pnrMode != null ? pnrMode.TravelType.ToString() : "1";
//单程 单程/往返 往返 中转
pc.TravelType = strTravelType == "1" ? TravelType.Oneway : (strTravelType == "2" ? TravelType.Twoway : TravelType.Connway);
//时间
DateTime FromTime = System.DateTime.Now;
DateTime EndTime = System.DateTime.Now;
if (dr["Sdate"] != DBNull.Value)
{
FromTime = DateTime.Parse(dr["Sdate"].ToString());
}
if (dr["Edate"] != DBNull.Value)
{
EndTime = DateTime.Parse(dr["Edate"].ToString());
}
pc.CheckinTime = new TimePeriod()
{
FromTime = FromTime,
EndTime = EndTime
};
pc.IssueTime = new TimePeriod()
{
FromTime = FromTime,
EndTime = EndTime
};
DateTime WeekStartTime = System.DateTime.Now;
DateTime WeekEndTime = System.DateTime.Now;
if (dr["WorkTimeBegin"] != DBNull.Value)
{
string strStartTime = dr["WorkTimeBegin"].ToString();
if (strStartTime.Contains(":"))
{
WeekStartTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
}
}
if (dr["WorkTimeEnd"] != DBNull.Value)
{
string strEndTime = dr["WorkTimeEnd"].ToString();
if (strEndTime.Contains(":"))
{
WeekEndTime = DateTime.Parse(WeekEndTime.ToString("yyyy-MM-dd") + " " + strEndTime + ":00");
}
}
DateTime WeekendStartTime = WeekStartTime;
DateTime WeekendEndTime = WeekEndTime;
pc.ServiceTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = WeekStartTime,
EndTime = WeekEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = WeekendStartTime,
EndTime = WeekendEndTime
}
};
DateTime VoidWeekTimeStartTime = System.DateTime.Now;
DateTime VoidWeekTimeEndTime = System.DateTime.Now;
if (dr["RefundTimeBegin"] != DBNull.Value)
{
string strStartTime = dr["RefundTimeBegin"].ToString();
if (strStartTime.Contains(":"))
{
VoidWeekTimeStartTime = DateTime.Parse(VoidWeekTimeStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
}
}
if (dr["RefundTimeEnd"] != DBNull.Value)
{
string strEndTime = dr["RefundTimeEnd"].ToString();
if (strEndTime.Contains(":"))
{
VoidWeekTimeEndTime = DateTime.Parse(VoidWeekTimeEndTime.ToString("yyyy-MM-dd") + " " + strEndTime + ":00");
}
}
DateTime VoidWeekendStartTime = VoidWeekTimeStartTime;
DateTime VoidWeekendEndTime = VoidWeekTimeEndTime;
pc.TFGTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = VoidWeekTimeStartTime,
EndTime = VoidWeekTimeEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = VoidWeekendStartTime,
EndTime = VoidWeekendEndTime
}
};
return pc;
}
private PolicyCache _PiaoMengDrToPolicyCache(PolicyCache pc, DataRow dr)
{
pc.PolicyId = dr["id"] != DBNull.Value ? dr["id"].ToString() : "";
pc.CarrierCode = pnrMode != null && pnrMode._LegList.Count > 0 ? pnrMode._LegList[0].AirCode : "";
decimal strPoint = 0m;
decimal.TryParse(dr["rate"] != DBNull.Value ? dr["rate"].ToString() : "0", out strPoint);
pc.Point = strPoint;
pc.CabinSeatCode = (dr["applyclass"] != DBNull.Value ? dr["applyclass"].ToString() : "").Split(new string[] { "/", ",", "," }, StringSplitOptions.RemoveEmptyEntries);
pc.FromCityCode = pnrMode != null && pnrMode._LegList.Count > 0 ? pnrMode._LegList[0].FromCode : "";
pc.MidCityCode = "";
pc.ToCityCode = pnrMode != null && pnrMode._LegList.Count > 0 ? pnrMode._LegList[0].ToCode : "";
string strPolicyType = dr["policytype"] != DBNull.Value ? (dr["policytype"].ToString().ToUpper().Contains("B2P") ? "1" : "2") : "2";
pc.PolicyType = (strPolicyType == "1") ? PolicyType.BSP : PolicyType.B2B;
pc.Remark = dr["note"] != DBNull.Value ? dr["note"].ToString() : "";
string strTravelType = pnrMode != null ? pnrMode.TravelType.ToString() : "1";
//单程 单程/往返 往返 中转
pc.TravelType = strTravelType == "1" ? TravelType.Oneway : (strTravelType == "2" ? TravelType.Twoway : TravelType.Connway);
DateTime WeekStartTime = System.DateTime.Now;
DateTime WeekEndTime = System.DateTime.Now;
if (dr["worktime"] != DBNull.Value && dr["worktime"].ToString().Split('-').Length == 2)
{
string strStartTime = dr["worktime"].ToString().Split('-')[0];
string strEndTime = dr["worktime"].ToString().Split('-')[1];
if (!strStartTime.Contains(":"))
{
strStartTime = strStartTime.Insert(2, ":");
}
if (!strEndTime.Contains(":"))
{
strEndTime = strEndTime.Insert(2, ":");
}
WeekStartTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
WeekEndTime = DateTime.Parse(WeekEndTime.ToString("yyyy-MM-dd") + " " + strEndTime + ":00");
}
DateTime WeekendStartTime = WeekStartTime;
DateTime WeekendEndTime = WeekEndTime;
pc.ServiceTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = WeekStartTime,
EndTime = WeekEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = WeekendStartTime,
EndTime = WeekendEndTime
}
};
DateTime VoidWeekTimeStartTime = System.DateTime.Now;
DateTime VoidWeekTimeEndTime = System.DateTime.Now;
if (dr["RefundWorkTimeTo"] != DBNull.Value && dr["RefundWorkTimeTo"].ToString().Length > 2)
{
string strRefound = dr["RefundWorkTimeTo"].ToString();
strRefound = strRefound.Insert(2, ":");
VoidWeekTimeStartTime = WeekStartTime;
VoidWeekTimeEndTime = DateTime.Parse(VoidWeekTimeEndTime.ToString("yyyy-MM-dd") + " " + strRefound + ":00");
}
pc.TFGTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = VoidWeekTimeStartTime,
EndTime = VoidWeekTimeEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = VoidWeekTimeStartTime,
EndTime = VoidWeekTimeEndTime
}
};
return pc;
}
private PolicyCache _BaiTuoDrToPolicyCache(PolicyCache pc, DataRow dr)
{
pc.PolicyId = dr["Id"] != DBNull.Value ? dr["Id"].ToString() : "";
pc.CarrierCode = pnrMode != null && pnrMode._LegList.Count > 0 ? pnrMode._LegList[0].AirCode : "";
decimal strPoint = 0m;
decimal.TryParse(dr["Rate"] != DBNull.Value ? dr["Rate"].ToString() : "0", out strPoint);
pc.Point = strPoint * 100;
List<string> cabinList = new List<string>();
if (pnrMode != null && pnrMode._LegList.Count > 0)
{
foreach (PnrAnalysis.Model.LegInfo leg in pnrMode._LegList)
{
cabinList.Add(leg.Seat);
}
}
pc.CabinSeatCode = cabinList.ToArray();
pc.FromCityCode = pnrMode != null && pnrMode._LegList.Count > 0 ? pnrMode._LegList[0].FromCode : "";
pc.MidCityCode = "";
pc.ToCityCode = pnrMode != null && pnrMode._LegList.Count > 0 ? pnrMode._LegList[0].ToCode : "";
string strPolicyType = (dr["PolicyType"] != DBNull.Value ? dr["PolicyType"].ToString() : "B2B");
pc.PolicyType = (strPolicyType == "1") ? PolicyType.B2B : PolicyType.BSP;
pc.Remark = dr["Remark"] != DBNull.Value ? dr["Remark"].ToString() : "";
string strTravelType = pnrMode != null ? pnrMode.TravelType.ToString() : "1";
//单程 单程/往返 往返 中转
pc.TravelType = strTravelType == "1" ? TravelType.Oneway : (strTravelType == "2" ? TravelType.Twoway : TravelType.Connway);
//时间
DateTime FromTime = System.DateTime.Now;
DateTime EndTime = System.DateTime.Now;
if (dr["Effdate"] != DBNull.Value)
{
FromTime = DateTime.Parse(dr["Effdate"].ToString());
}
if (dr["Expdate"] != DBNull.Value)
{
EndTime = DateTime.Parse(dr["Expdate"].ToString());
}
pc.CheckinTime = new TimePeriod()
{
FromTime = FromTime,
EndTime = EndTime
};
pc.IssueTime = new TimePeriod()
{
FromTime = FromTime,
EndTime = EndTime
};
DateTime WeekStartTime = System.DateTime.Now;
DateTime WeekEndTime = System.DateTime.Now;
if (pnrMode._LegList.Count > 0)
{
string[] strTimeArr = null;
string strStartTime = "00:00", strEndTime = "00:00";
int Index = 0;
DayOfWeek dayOfWeek = DateTime.Parse(pnrMode._LegList[0].FlyDate1).DayOfWeek;
switch (dayOfWeek)
{
case DayOfWeek.Monday:
Index = 0;
break;
case DayOfWeek.Tuesday:
Index = 1;
break;
case DayOfWeek.Wednesday:
Index = 2;
break;
case DayOfWeek.Thursday:
Index = 3;
break;
case DayOfWeek.Friday:
Index = 4;
break;
case DayOfWeek.Saturday:
Index = 5;
break;
case DayOfWeek.Sunday:
Index = 6;
break;
default:
break;
}
if (dr["ProviderWorkTime"].ToString().Split(',').Length == 7 && Index > -1 && Index < 7)
{
strTimeArr = dr["ProviderWorkTime"].ToString().Split(',');
if (strTimeArr[Index].Split('-').Length == 2)
{
strStartTime = strTimeArr[Index].Split('-')[0];
strEndTime = strTimeArr[Index].Split('-')[1];
WeekStartTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
WeekEndTime = DateTime.Parse(WeekEndTime.ToString("yyyy-MM-dd") + " " + strEndTime + ":00");
}
}
DateTime WeekendStartTime = WeekStartTime;
DateTime WeekendEndTime = WeekEndTime;
pc.ServiceTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = WeekStartTime,
EndTime = WeekEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = WeekendStartTime,
EndTime = WeekendEndTime
}
};
DateTime VoidWeekTimeStartTime = System.DateTime.Now;
DateTime VoidWeekTimeEndTime = System.DateTime.Now;
if (dr["VoidWorkTime"] != DBNull.Value)
{
string[] strArrTime = dr["VoidWorkTime"].ToString().Split(',');
if (strTimeArr[Index].Split('-').Length == 2)
{
strStartTime = strTimeArr[Index].Split('-')[0];
strEndTime = strTimeArr[Index].Split('-')[1];
VoidWeekTimeStartTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
VoidWeekTimeEndTime = DateTime.Parse(WeekEndTime.ToString("yyyy-MM-dd") + " " + strEndTime + ":00");
}
}
DateTime VoidWeekendStartTime = VoidWeekTimeStartTime;
DateTime VoidWeekendEndTime = VoidWeekTimeEndTime;
pc.TFGTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = VoidWeekTimeStartTime,
EndTime = VoidWeekTimeEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = VoidWeekendStartTime,
EndTime = VoidWeekendEndTime
}
};
}
return pc;
}
private PolicyCache _YeeXingDrToPolicyCache(PolicyCache pc, DataRow dr)
{
pc.PolicyId = dr["plcid"] != DBNull.Value ? dr["plcid"].ToString() : "";
pc.CarrierCode = dr["airComp"] != DBNull.Value ? dr["airComp"].ToString() : "";
decimal strPoint = 0m;
decimal.TryParse(dr["disc"] != DBNull.Value ? dr["disc"].ToString() : "0", out strPoint);
pc.Point = strPoint;
List<string> cabinList = new List<string>();
if (pnrMode != null && pnrMode._LegList.Count > 0)
{
foreach (PnrAnalysis.Model.LegInfo leg in pnrMode._LegList)
{
cabinList.Add(leg.Seat);
}
}
pc.CabinSeatCode = cabinList.ToArray();
pc.FromCityCode = pnrMode != null && pnrMode._LegList.Count > 0 ? pnrMode._LegList[0].FromCode : "";
pc.MidCityCode = "";
pc.ToCityCode = pnrMode != null && pnrMode._LegList.Count > 0 ? pnrMode._LegList[0].ToCode : "";
string strPolicyType = (dr["tickType"] != DBNull.Value ? dr["tickType"].ToString() : "1");
pc.PolicyType = (strPolicyType == "1") ? PolicyType.B2B : PolicyType.BSP;
pc.Remark = dr["memo"] != DBNull.Value ? dr["memo"].ToString() : "";
string strTravelType = pnrMode != null ? pnrMode.TravelType.ToString() : "1";
//单程 单程/往返 往返 中转
pc.TravelType = strTravelType == "1" ? TravelType.Oneway : (strTravelType == "2" ? TravelType.Twoway : TravelType.Connway);
//时间
DayOfWeek dayOfWeek = DateTime.Parse(pnrMode._LegList[0].FlyDate1).DayOfWeek;
string strStartTime = "00:00";
string strEndTime = "00:00";
DateTime WeekStartTime = System.DateTime.Now;
DateTime WeekEndTime = System.DateTime.Now;
DateTime WeekendStartTime = System.DateTime.Now;
DateTime WeekendEndTime = System.DateTime.Now;
DateTime VoidWeekTimeStartTime = System.DateTime.Now;
DateTime VoidWeekTimeEndTime = System.DateTime.Now;
DateTime VoidWeekendTimeStartTime = System.DateTime.Now;
DateTime VoidWeekendTimeEndTime = System.DateTime.Now;
if (dayOfWeek != DayOfWeek.Saturday && dayOfWeek != DayOfWeek.Sunday)
{
//周一到周五
if (dr["workTime"].ToString().Split('-').Length == 2)
{
strStartTime = dr["workTime"].ToString().Split('-')[0];
strEndTime = dr["workTime"].ToString().Split('-')[1];
}
WeekStartTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
WeekEndTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
if (dr["workReturnTime"].ToString().Split('-').Length == 2)
{
strStartTime = dr["workReturnTime"].ToString().Split('-')[0];
strEndTime = dr["workReturnTime"].ToString().Split('-')[1];
}
VoidWeekTimeStartTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
VoidWeekTimeEndTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
}
else
{
//周末
if (dr["restWorkTime"].ToString().Split('-').Length == 2)
{
strStartTime = dr["restWorkTime"].ToString().Split('-')[0];
strEndTime = dr["restWorkTime"].ToString().Split('-')[1];
}
WeekendStartTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
WeekendEndTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
if (dr["restReturnTime"].ToString().Split('-').Length == 2)
{
strStartTime = dr["restReturnTime"].ToString().Split('-')[0];
strEndTime = dr["restReturnTime"].ToString().Split('-')[1];
}
VoidWeekendTimeStartTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
VoidWeekendTimeEndTime = DateTime.Parse(WeekStartTime.ToString("yyyy-MM-dd") + " " + strStartTime + ":00");
}
pc.ServiceTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = WeekStartTime,
EndTime = WeekEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = WeekendStartTime,
EndTime = WeekendEndTime
}
};
pc.TFGTime = new WorkTime()
{
WeekTime = new TimePeriod()
{
FromTime = VoidWeekTimeStartTime,
EndTime = VoidWeekTimeEndTime
},
WeekendTime = new TimePeriod()
{
FromTime = VoidWeekendTimeStartTime,
EndTime = VoidWeekendTimeEndTime
}
};
return pc;
}
}
}
|
namespace Model
{
/// <summary>
/// Interface utilizada para definir el Id como atributo numerico
/// autoincremental.
/// </summary>
public interface IEntity<T>
{
/// <summary>
/// Identificador Unico de cada instancia de clase. Propiedad Generica
/// para facilitar a todas las clases la obtención de una llave
/// primaria ya sea numerica o cadena de caracteres.
/// </summary>
T Id { get; set; }
}
}
|
using System;
using GeneticSharp.Extensions.Stretch;
using NUnit.Framework;
namespace GeneticSharp.Extensions.UnitTests.Stretch
{
[TestFixture]
[Category("Extensions")]
public class StretchParserTest
{
[Test]
public void ParseText()
{
Assert.That(StretchParser.Rows("a\n8\nb"), Is.EqualTo(new string[] { "a", "8", "b" }));
}
[Test]
public void IgnoreEmptyRows()
{
Assert.That(StretchParser.Rows("a\n\n8\nb\n"), Is.EqualTo(new string[] { "a", "8", "b" }));
}
[Test]
public void ParseRow()
{
Assert.That(StretchParser.Tokens("a 8 b 3 c"), Is.EqualTo(new string[] { "a", "8", "b", "3", "c" }));
}
[Test]
public void ParseRowWithMultipleSeparators()
{
Assert.That(
StretchParser.Tokens("a\t2;3,0 b \tc,;8\t\td"),
Is.EqualTo(new string[] { "a", "2", "3", "0", "b", "c", "8", "d" })
);
}
}
}
|
using System;
using System.IO;
using System.Linq;
namespace TreeStore.PsModule
{
public static class FrameworkExtensions
{
public static bool EnsureValidName(this string name) => !name
.ToCharArray()
.Any(c => Path.GetInvalidFileNameChars().Contains(c));
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using Newtonsoft.Json;
namespace Nexmo.Api
{
public static class ApiRequest
{
public static Uri GetBaseUriFor(Type component, string url = null)
{
var baseUri = typeof (NumberVerify) == component ? new Uri(ConfigurationManager.AppSettings["Nexmo.Url.Api"]) : new Uri(ConfigurationManager.AppSettings["Nexmo.Url.Rest"]);
return string.IsNullOrEmpty(url) ? baseUri : new Uri(baseUri, url);
}
public static string DoRequest(Uri uri, Dictionary<string, string> parameters)
{
var sb = new StringBuilder();
parameters.Add("api_key", ConfigurationManager.AppSettings["Nexmo.api_key"]);
parameters.Add("api_secret", ConfigurationManager.AppSettings["Nexmo.api_secret"]);
foreach (var key in parameters.Keys)
{
sb.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(parameters[key]));
}
return DoRequest(new Uri(uri, "?" + sb));
}
public static string DoRequest(Uri uri, object parameters)
{
var sb = new StringBuilder();
Dictionary<string, string> Dic = new Dictionary<string, string>();
foreach (System.Reflection.PropertyInfo var in parameters.GetType().GetProperties())
{
string jsonPropertyName = null;
if (var.GetCustomAttributes(typeof(JsonPropertyAttribute), false).Length > 0)
{
jsonPropertyName= ((JsonPropertyAttribute)var.GetCustomAttributes(typeof(JsonPropertyAttribute), false)[0]).PropertyName;
}
if (parameters.GetType().GetProperty(var.Name).GetValue(parameters, null) != null)
{
if (string.IsNullOrEmpty(jsonPropertyName))
{
Dic.Add(var.Name, parameters.GetType().GetProperty(var.Name).GetValue(parameters, null).ToString());
}
else
{
Dic.Add(jsonPropertyName, parameters.GetType().GetProperty(var.Name).GetValue(parameters, null).ToString());
}
}
}
Dic.Add("api_key", ConfigurationManager.AppSettings["Nexmo.api_key"]);
Dic.Add("api_secret", ConfigurationManager.AppSettings["Nexmo.api_secret"]);
foreach (var key in Dic.Keys)
{
sb.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(Dic[key]));
}
return DoRequest(new Uri(uri, "?" + sb));
}
public static string DoRequest(Uri uri)
{
var req = WebRequest.CreateHttp(uri);
var resp = req.GetResponseAsync().Result;
string json;
using (var sr = new StreamReader(resp.GetResponseStream()))
{
json = sr.ReadToEnd();
}
return json;
}
public static string DoPostRequest(Uri uri, Dictionary<string, string> parameters)
{
var sb = new StringBuilder();
parameters.Add("api_key", ConfigurationManager.AppSettings["Nexmo.api_key"]);
parameters.Add("api_secret", ConfigurationManager.AppSettings["Nexmo.api_secret"]);
foreach (var key in parameters.Keys)
{
sb.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(parameters[key]));
}
var req = WebRequest.CreateHttp(uri);
req.Method = "POST";
var data = Encoding.ASCII.GetBytes(sb.ToString());
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
var requestStream = req.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
var resp = req.GetResponseAsync().Result;
string json;
using (var sr = new StreamReader(resp.GetResponseStream()))
{
json = sr.ReadToEnd();
}
return json;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogUrFace.FaceRec.Models
{
public class FaceTemplate
{
public int Id { get; set; }
public string Label { get; set; }
[MaxLength]
public byte[] Template { get; set; }
[MaxLength]
public byte[] Original { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KarzPlus.Entities;
using KarzPlus.Business;
using KarzPlus.Entities.ExtensionMethods;
using KarzPlus.Base;
namespace KarzPlus.Controls
{
public partial class CarMakeConfiguration : BaseControl
{
public bool EditOption
{
get
{
if (ViewState["EditOption"] == null)
{
ViewState["EditOption"] = false;
}
return (bool)ViewState["EditOption"];
}
set { ViewState["EditOption"] = value; }
}
public int MakeId
{
get
{
if (ViewState["MakeId"] == null)
{
ViewState["MakeId"] = 0;
}
return (int)ViewState["MakeId"];
}
set { ViewState["MakeId"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
public bool SaveControl()
{
bool valid = false;
CarMake modelToSave = new CarMake();
if (EditOption)
{
modelToSave = CarMakeManager.Load(MakeId);
}
modelToSave.Name = txtMakeName.Text;
modelToSave.Manufacturer = txtManufacturer.Text;
string errorMessage;
valid = CarMakeManager.Save(modelToSave, out errorMessage);
return valid;
}
public void ReloadControl()
{
if (EditOption)
{
LoadOnMakeId(MakeId);
}
}
private void LoadOnMakeId(int makeId)
{
CarMake carMake = CarMakeManager.Load(makeId);
txtMakeName.Text = carMake.Name;
txtManufacturer.Text = carMake.Manufacturer;
}
}
} |
//
// 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.Data;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities;
using DotNetNuke.Entities.Modules;
#endregion
namespace DotNetNuke.Services.Localization
{
[Serializable]
public class LanguagePackInfo : BaseEntityInfo, IHydratable
{
#region "Private Members"
private int _DependentPackageID = Null.NullInteger;
private int _LanguageID = Null.NullInteger;
private int _LanguagePackID = Null.NullInteger;
private int _PackageID = Null.NullInteger;
#endregion
#region "Public Properties"
public int LanguagePackID
{
get
{
return _LanguagePackID;
}
set
{
_LanguagePackID = value;
}
}
public int LanguageID
{
get
{
return _LanguageID;
}
set
{
_LanguageID = value;
}
}
public int PackageID
{
get
{
return _PackageID;
}
set
{
_PackageID = value;
}
}
public int DependentPackageID
{
get
{
return _DependentPackageID;
}
set
{
_DependentPackageID = value;
}
}
public LanguagePackType PackageType
{
get
{
if (DependentPackageID == -2)
{
return LanguagePackType.Core;
}
else
{
return LanguagePackType.Extension;
}
}
}
#endregion
#region IHydratable Members
public void Fill(IDataReader dr)
{
LanguagePackID = Null.SetNullInteger(dr["LanguagePackID"]);
LanguageID = Null.SetNullInteger(dr["LanguageID"]);
PackageID = Null.SetNullInteger(dr["PackageID"]);
DependentPackageID = Null.SetNullInteger(dr["DependentPackageID"]);
//Call the base classes fill method to populate base class proeprties
base.FillInternal(dr);
}
public int KeyID
{
get
{
return LanguagePackID;
}
set
{
LanguagePackID = value;
}
}
#endregion
}
}
|
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== //
//
// Notes:
//
// ============================================================================ //
using System;
using UnityEditor;
namespace EnhancedEditor.Editor {
/// <summary>
/// Allows you to add you own menu items on the context menu of a <see cref="SerializedProperty"/>.
/// <para/>
/// The method must accept a <see cref="GenericMenu"/> and a <see cref="SerializedProperty"/> as arguments.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class SerializedPropertyMenuAttribute : Attribute { }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace GroupProjectWebHotel.Models
{
public class Customer
{
[Key, Required]
[DataType(DataType.EmailAddress)]
[EmailAddress]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[RegularExpression(@"[A-Za-z - ']{2,20}$")]
[Display(Name = "Surname")]
public string Surname { get; set; }
[Required]
[RegularExpression(@"[A-Za-z - ']{2,20}$")]
[Display(Name = "Given Name")]
public string GivenName { get; set; }
[Required]
[RegularExpression(@"[0-9]{4}$")]
[Display(Name = "Postcode")]
public string Postcode { get; set; }
public ICollection<Booking> TheBookings { get; set; }
}
} |
using Kit.iOS.Services;
using Kit.Services.Interfaces;
using UIKit;
using Xamarin.Forms;
[assembly: Dependency(typeof(BrightnessService))]
namespace Kit.iOS.Services
{
public class BrightnessService : IBrightnessService
{
public float GetBrightness()
{
return (float)UIScreen.MainScreen.Brightness;
}
public void SetBrightness(float factor)
{
UIScreen.MainScreen.Brightness = factor;
}
}
} |
using UnityEngine;
[ExecuteInEditMode]
public class PlaceTreeOnGround : MonoBehaviour
{
private RaycastHit Hit;
public bool RandomScale;
public bool RandomRotation;
private float ScaleFactor;
private float ScaleAmount;
private void Start()
{
ScaleFactor = transform.localScale.y;
}
void Update()
{
transform.position = new Vector3(transform.position.x, 1000, transform.position.z);
if(Physics.Raycast(transform.position, Vector3.down, out Hit))
{
transform.position = Hit.point;
if(RandomScale)
{
ScaleAmount = Random.Range(-1.2f, 1.2f);
transform.localScale = Vector3.one * (ScaleFactor + ScaleAmount);
}
if(RandomRotation)
{
transform.eulerAngles = new Vector3(transform.eulerAngles.x, Random.Range(0, 360), transform.eulerAngles.z);
}
}
}
} |
using System.Threading.Tasks;
using System.Linq;
using System;
namespace AspNetCore.Api.TenantResolver
{
public class InMemoryTenantStore : ITenantStore<Tenant>
{
private readonly Tenant[] _tenants;
//public InMemoryTenantStore()
//{
// _tenants = new[] { new Tenant { Identifier = "localhost", Id = Guid.NewGuid().ToString() } };
//}
public InMemoryTenantStore(Tenant[] tenants)
{
_tenants = tenants;
}
public Task<Tenant> GetTenantAsync(string identifier)
{
var tenant = _tenants.Where(t => t.Identifier == identifier).FirstOrDefault();
return Task.FromResult(tenant);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using PNPUTools.DataManager;
using System.Data;
using System.IO.Pipes;
using System.Data.SqlClient;
namespace PNPUTools
{
/// <summary>
/// Cette classe static charge les paramètres de l'application et permet aux objets de récupérer les différentes valeurs directement.
/// </summary>
public static class ParamAppli
{
/// <summary>
/// Liste des commandes dont la présence est interdite dans les packs.
/// </summary>
public static List<string> ListeCmdInterdite { get; }
/// <summary>
/// Liste des valeurs inférieures des plages ID_SYNONYM réservées aux clients.
/// </summary>
public static List<int> ListeLimInf { get; }
/// <summary>
/// Liste des valeurs supérieures des plages ID_SYNONYM réservées aux clients.
/// </summary>
public static List<int> ListeLimSup { get; }
/// <summary>
/// Liste des clés des paramètres applicatifs qu'il est interdit de livrer.
/// </summary>
public static List<string> ListeCleInterdite { get; }
/// <summary>
/// Liste des sections des paramètres applicatifs qu'il est interdit de livrer.
/// </summary>
public static List<string> ListeSectionInterdite { get; }
/// <summary>
/// Liste des commandes autorisées dans le packs de type "L".
/// </summary>
public static List<string> ListeCmdL { get; }
/// <summary>
/// Liste des commandes autorisées dans le packs de type "D".
/// </summary>
public static List<string> ListeCmdD { get; }
/// <summary>
/// Liste des commandes autorisées dans le packs de type "F".
/// </summary>
public static List<string> ListeCmdF { get; }
/// <summary>
/// Liste des commandes autorisées dans le packs de type "B".
/// </summary>
public static List<string> ListeCmdB { get; }
/// <summary>
/// Chaine de connexion à la base de référence.
/// </summary>
public static Dictionary<string,string> ConnectionStringBaseRef { get; }
/// <summary>
/// Chaine de connexion à la base de référence SAAS dédié.
/// </summary>
public static string ConnectionStringBaseRefDedie { get; }
/// <summary>
/// Chaine de connexion à la base de référence SAAS mutualisé / désynchro.
/// </summary>
public static string ConnectionStringBaseRefPlateforme { get; }
/// <summary>
/// Chaine de connexion à la base de l'application.
/// </summary>
public static string ConnectionStringBaseAppli { get; }
/// <summary>
/// Chaine de connexion à la base de du support.
/// </summary>
public static string ConnectionStringSupport { get; }
/// <summary>
/// Dossier temporaire utilisé pour l'application.
/// </summary>
public static string DossierTemporaire { get; }
public static Dictionary<string, InfoClient> ListeInfoClient { get; }
public static string GeneratePackPath { get; internal set; }
public const int TypologyDedie = 256;
public const string ConnectionStringAccess = "Driver={Microsoft Access Driver (*.mdb)};Dbq={0};Uid=Admin;Pwd=;";
public const string AnalyseImpactPathResult = "C:\\TEMPO\\AnalyseIpact";
public const string RamdDlPAth = "C:\\Program Files (x86)\\meta4\\M4DevClient\\Bin\\RAMDL.EXE";//"C:\\meta4\\M4DevClient\\Bin\\RamDL.exe";
public const string StatutOk = "CORRECT";
public const string StatutCompleted = "COMPLETED";
public const string StatutError = "ERROR";
public const string StatutWarning = "WARNING";
public const string StatutInfo = "INFORMATION";
public static string LogLevel = "DEBUG";
public const string connectionStringSupport = "server=M4FRDB16;uid=META4_DOCSUPPREAD;pwd=META4_DOCSUPPREAD;database=META4_DOCSUPP;";
public const string connectionTemplate = "server={0};uid={1};pwd={2};database={3};";
public const int ProcessControlePacks = 1;
public const int ProcessInit = 2;
public const int ProcessGestionDependance = 3;
public const int ProcessAnalyseImpact = 4;
public const int ProcessIntegration = 5;
public const int ProcessProcessusCritique = 6;
public const int ProcessTNR = 7;
public const int ProcessLivraison = 8;
public const int ProcessFinished = -1;
public const bool SimpleCotesReport = true;
public static NamedPipeClientStream npcsPipeClient;
public static Dictionary<string, string> TranscoSatut;
public const string templateIniFileAnalyseImpact = "<ORIGIN_CONN>\r\n{0}\r\n<TARGET_CONN>\r\n{1}\r\n<LOG_FILE>\r\n{2}\r\n<USER_CVM>\r\n{3}\r\n<PWD_CVM>\r\n{4}\r\n";//<CLEAR_PREVIOUS_ANALYSIS>\r\nYES\r\n<PACK_ANALYSIS>\r\n{5}\r\n<ANALYSE_RESULTS_FILE>\r\n{6}
public const string templateIniFileGeneratePack = "<ORIGIN_CONN>\r\n{0}\r\n<LOG_FILE>\r\n{1}\r\n<PKGWZ_CONTENT_TYPE>\r\n3\r\n<PKGWZ_CCT_VERSION>\r\n8.1\r\n<PKGWZ_CCT_TASK_LIST>\r\n{2}\r\n<PKGWZ_MDB_ADD_TABLES>\r\n3\r\n<PKGWZ_MDB_PATH>\r\n{3}\r\n<PKGWZ_PACK_NAME>\r\nPNPU_\r\n<PKGWZ_PACK_LOAD_DATA>\r\n1\r\n<PKGWZ_PACK_REFRESH_CHANGES>\r\n0\r\n<PKGWZ_PACK_SAVE_ORDER>\r\n1\r\n<PKGWZ_PACK_SAVE_SCRIPT>\r\n0";
/// <summary>
/// Constructeur de la classe. Il charge toutes les valeurs du paramétrage.
/// </summary>
static ParamAppli()
{
DataSet dsDataSet = null;
DataManagerSQLServer dataManagerSQLServer = new DataManagerSQLServer();
TranscoSatut = new Dictionary<string, string>();
TranscoSatut.Add(StatutOk, "mdi-check-circle");
TranscoSatut.Add(StatutCompleted, "mdi-check-circle");
TranscoSatut.Add(StatutError, "mdi-alert-circle");
TranscoSatut.Add(StatutWarning, "mdi-alert");
npcsPipeClient = null;
ListeInfoClient = new Dictionary<string, InfoClient>();
// A lire dans base de ref
ListeCmdInterdite = new List<string>();
ListeCleInterdite = new List<string>();
ListeSectionInterdite = new List<string>();
ListeCmdL = new List<string>();
ListeCmdD = new List<string>();
ListeCmdF = new List<string>();
ListeCmdB = new List<string>();
ListeLimInf = new List<int>();
ListeLimSup = new List<int>();
try
{
//ConnectionStringBaseAppli = "server=M4FRDB18;uid=CAPITAL_DEV;pwd=Cpldev2017;database=CAPITAL_DEV;";
ConnectionStringBaseAppli = "server=M4FRDB22;uid=PNPU_DEV;pwd=PNPU_DEV;database=PNPU_DEV;";
dsDataSet = dataManagerSQLServer.GetData("SELECT PARAMETER_ID,PARAMETER_VALUE FROM PNPU_PARAMETERS ORDER BY PARAMETER_ID", ConnectionStringBaseAppli);
if ((dsDataSet != null) && (dsDataSet.Tables[0].Rows.Count > 0))
{
foreach (DataRow drRow in dsDataSet.Tables[0].Rows)
{
switch (drRow[0].ToString().Substring(0, 7))
{
case "INTERD_":
ListeCmdInterdite.Add(drRow[1].ToString());
break;
case "PACK_B_":
ListeCmdB.Add(drRow[1].ToString());
break;
case "PACK_D_":
ListeCmdD.Add(drRow[1].ToString());
break;
case "PACK_F_":
ListeCmdF.Add(drRow[1].ToString());
break;
case "PACK_L_":
ListeCmdL.Add(drRow[1].ToString());
break;
case "PARKEY_":
ListeCleInterdite.Add(drRow[1].ToString());
break;
case "PARSEC_":
ListeSectionInterdite.Add(drRow[1].ToString());
break;
case "BASREFD":
ConnectionStringBaseRefDedie = drRow[1].ToString();
break;
case "BASREFP":
ConnectionStringBaseRefPlateforme = drRow[1].ToString();
break;
case "BASESUP":
ConnectionStringSupport = drRow[1].ToString();
break;
case "DOSTEMP":
DossierTemporaire = drRow[1].ToString();
break;
}
}
}
// On valorise en fonction de la typologie
ConnectionStringBaseRef = new Dictionary<string, string>();
ConnectionStringBaseRef.Add("Dédié", ConnectionStringBaseRefDedie);
ConnectionStringBaseRef.Add("Mutualisé", ConnectionStringBaseRefPlateforme);
ConnectionStringBaseRef.Add("Désynchronisé", ConnectionStringBaseRefPlateforme);
// N'existe que sur la base plateforme
if (ConnectionStringBaseRefPlateforme != string.Empty)
{
dsDataSet = dataManagerSQLServer.GetData("SELECT CFR_PLAGE_DEBUT, CFR_PLAGE_FIN FROM M4CFR_PLAGES_ID_SYNONYM WHERE ID_ORGANIZATION ='0000' and CFR_ID_TYPE = 'CLIENT'", ConnectionStringBaseRefPlateforme);
if ((dsDataSet != null) && (dsDataSet.Tables[0].Rows.Count > 0))
{
foreach (DataRow drRow in dsDataSet.Tables[0].Rows)
{
ListeLimInf.Add(Int32.Parse(drRow[0].ToString()));
ListeLimSup.Add(Int32.Parse(drRow[1].ToString()));
}
}
}
//Chargement des infos clients
if (ConnectionStringSupport != string.Empty)
{
dsDataSet = dataManagerSQLServer.GetData("SELECT CLIENT_ID, CLIENT_NAME, SAAS, CODIFICATION_LIBELLE FROM A_CLIENT,A_CODIFICATION WHERE SAAS is not NULL AND SAAS = CODIFICATION_ID", ConnectionStringSupport);
if ((dsDataSet != null) && (dsDataSet.Tables[0].Rows.Count > 0))
{
foreach (DataRow drRow in dsDataSet.Tables[0].Rows)
{
ListeInfoClient.Add(drRow[0].ToString(), new InfoClient(drRow[0].ToString(), drRow[1].ToString(), drRow[2].ToString(), drRow[3].ToString(), string.Empty, string.Empty)) ;
}
}
}
}
catch (Exception ex)
{
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NationalInstruments.DAQmx;
namespace LibEqmtDriver.SCU
{
public class AvSwitchMatrix:iSwitch
{
private Task digitalWriteTaskP00;
private Task digitalWriteTaskP01;
private Task digitalWriteTaskP02;
private Task digitalWriteTaskP03;
private Task digitalWriteTaskP04;
private Task digitalWriteTaskP05;
private Task digitalWriteTaskP09;
private DigitalSingleChannelWriter writerP00;
private DigitalSingleChannelWriter writerP01;
private DigitalSingleChannelWriter writerP02;
private DigitalSingleChannelWriter writerP03;
private DigitalSingleChannelWriter writerP04;
private DigitalSingleChannelWriter writerP05;
private DigitalSingleChannelWriter writerP09;
#region iSwitch Members
void iSwitch.Initialize()
{
try
{
Init();
}
catch (Exception ex)
{
throw new Exception("AvSwitchMatrix: Initialize -> " + ex.Message);
}
}
void iSwitch.SetPath(string val)
{
try
{
SetPortPath(val);
}
catch (Exception ex)
{
throw new Exception("AvSwitchMatrix: SetPath -> " + ex.Message);
}
}
void iSwitch.Reset()
{
try
{
}
catch (Exception ex)
{
throw new Exception("AvSwitchMatrix: Reset -> " + ex.Message);
}
}
#endregion
private int[] ChannelValue = new int[12];
private int Init()
{
try
{
digitalWriteTaskP00 = new Task();
digitalWriteTaskP01 = new Task();
digitalWriteTaskP02 = new Task();
digitalWriteTaskP03 = new Task();
digitalWriteTaskP04 = new Task();
digitalWriteTaskP05 = new Task();
digitalWriteTaskP09 = new Task();
digitalWriteTaskP00.DOChannels.CreateChannel("DIO/port0", "port0",
ChannelLineGrouping.OneChannelForAllLines);
digitalWriteTaskP01.DOChannels.CreateChannel("DIO/port1", "port1",
ChannelLineGrouping.OneChannelForAllLines);
digitalWriteTaskP02.DOChannels.CreateChannel("DIO/port2", "port2",
ChannelLineGrouping.OneChannelForAllLines);
digitalWriteTaskP03.DOChannels.CreateChannel("DIO/port3", "port3",
ChannelLineGrouping.OneChannelForAllLines);
digitalWriteTaskP04.DOChannels.CreateChannel("DIO/port4", "port4",
ChannelLineGrouping.OneChannelForAllLines);
digitalWriteTaskP05.DOChannels.CreateChannel("DIO/port5", "port5",
ChannelLineGrouping.OneChannelForAllLines);
digitalWriteTaskP09.DOChannels.CreateChannel("DIO/port9", "port9",
ChannelLineGrouping.OneChannelForAllLines);
writerP00 = new DigitalSingleChannelWriter(digitalWriteTaskP00.Stream);
writerP01 = new DigitalSingleChannelWriter(digitalWriteTaskP01.Stream);
writerP02 = new DigitalSingleChannelWriter(digitalWriteTaskP02.Stream);
writerP03 = new DigitalSingleChannelWriter(digitalWriteTaskP03.Stream);
writerP04 = new DigitalSingleChannelWriter(digitalWriteTaskP04.Stream);
writerP05 = new DigitalSingleChannelWriter(digitalWriteTaskP05.Stream);
writerP09 = new DigitalSingleChannelWriter(digitalWriteTaskP09.Stream);
writerP00.WriteSingleSamplePort(true, 0);
writerP01.WriteSingleSamplePort(true, 0);
writerP02.WriteSingleSamplePort(true, 0);
writerP03.WriteSingleSamplePort(true, 0);
writerP04.WriteSingleSamplePort(true, 0);
writerP05.WriteSingleSamplePort(true, 0);
writerP09.WriteSingleSamplePort(true, 0);
return 0;
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "Initialize");
return -1;
}
}
private int SetPortPath(string PortPath)
{
try
{
string[] SwitchNoAndStatus = PortPath.Split(' ');
int NoOfSwitch = SwitchNoAndStatus.Length;
int[] SwitchNo = new int[NoOfSwitch];
int[] SwitchStatus = new int[NoOfSwitch];
string[] tempSwitchNoAndStatus = new string[2];
// Generate arrays for switch no and switch on/off status
for (int i = 0; i < NoOfSwitch; i++)
{
tempSwitchNoAndStatus = SwitchNoAndStatus[i].Split(':');
SwitchNo[i] = Convert.ToInt32(tempSwitchNoAndStatus[0]);
SwitchStatus[i] = Convert.ToInt32(tempSwitchNoAndStatus[1]);
}
// Clear the channel write need status
bool[] ChannelWriteNeeded = new bool[12];
int PortNo = 0;
int ChNo = 0;
for (int i = 0; i < NoOfSwitch; i++)
{
if (SwitchNo[i] == 48)
PortNo = 9;
else
{
PortNo = Convert.ToInt32(Math.Truncate(SwitchNo[i] / 8d));
}
ChNo = SwitchNo[i] - PortNo * 8;
int tempChValue = Convert.ToInt32(Math.Pow(2, ChNo));
int tempBitAnd = (ChannelValue[PortNo] & tempChValue);
if ((tempBitAnd == tempChValue) && (SwitchStatus[i] == 1))
{
// Do nothing
}
else if ((tempBitAnd == tempChValue) && (SwitchStatus[i] == 0))
{
ChannelValue[PortNo] -= tempChValue;
ChannelWriteNeeded[PortNo] = true;
}
else if ((tempBitAnd != tempChValue) && (SwitchStatus[i] == 1))
{
ChannelValue[PortNo] += tempChValue;
ChannelWriteNeeded[PortNo] = true;
}
else if ((tempBitAnd != tempChValue) && (SwitchStatus[i] == 0))
{
// Do nothing
}
else
{
MessageBox.Show("Error");
}
}
// Channel Write
if (ChannelWriteNeeded[0])
// writerP10.WriteSingleSamplePort(true, portValue);
writerP00.WriteSingleSamplePort(true, ChannelValue[0]);
if (ChannelWriteNeeded[1])
// writerP10.WriteSingleSamplePort(true, portValue);
writerP01.WriteSingleSamplePort(true, ChannelValue[1]);
if (ChannelWriteNeeded[2])
// writerP10.WriteSingleSamplePort(true, portValue);
writerP02.WriteSingleSamplePort(true, ChannelValue[2]);
if (ChannelWriteNeeded[3])
// writerP10.WriteSingleSamplePort(true, portValue);
writerP03.WriteSingleSamplePort(true, ChannelValue[3]);
if (ChannelWriteNeeded[4])
// writerP10.WriteSingleSamplePort(true, portValue);
writerP04.WriteSingleSamplePort(true, ChannelValue[4]);
if (ChannelWriteNeeded[5])
// writerP10.WriteSingleSamplePort(true, portValue);
writerP05.WriteSingleSamplePort(true, ChannelValue[5]);
if (ChannelWriteNeeded[9])
// writerP10.WriteSingleSamplePort(true, portValue);
writerP09.WriteSingleSamplePort(true, ChannelValue[9]);
return 0;
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "SetPortPath");
return -1;
}
}
}
}
|
using Xamarin.Forms;
using App1.Services;
namespace App1
{
public partial class AdMobViewPage : ContentPage
{
private string sHtml;
public string GetHtml
{
get { return sHtml; }
set
{
sHtml = value;
resultLabel.Text = sHtml;
DisplayAlert("Html", sHtml, "OK");
}
}
public AdMobViewPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
//
}
protected override void OnDisappearing()
{
//
base.OnDisappearing();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Blue_Melee : BaseEnemy
{
#region Editable fields
[SerializeField]
Transform dest = null;
[SerializeField]
GameObject collide = null;
[SerializeField]
Vector2 _knockback = Vector2.zero;
[SerializeField] AudioManager BM = null;
#endregion
#region private
Vector3 Target = Vector2.zero;
Vector3 Home = Vector2.zero;
#endregion
override protected void Start()
{
base.Start();
_rb = GetComponent<Rigidbody2D>();
Target = dest.position;
Home = transform.position;
anim = GetComponent<Animator>();
//Marker.transform.position = Target;
anim.Play("Idle_Melee");
}
void Update()
{
//Marker.transform.position = Target;
if (Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.down + (Vector2.right * .7f)), 5f, groundLayer) && !onPlatform)
{
//if (Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.right), 0.01f, groundLayer))
//{
// Turn();
// Home = transform.position;
//}
Move();
}
}
void SpawnEffect()
{
GameObject _effect = (GameObject)Instantiate(collide, transform.position, transform.rotation, transform);
_effect.GetComponent<melle_collide>().Init();
_effect.GetComponent<melle_collide>().InitAnimation();
}
private void Move()
{
float step = speed * Time.deltaTime;
///////////////////////////////////////////////////////
// If the enemy reached it's target position,
// turn around, and reset target
///////////////////////////////////////////////////////
if (Mathf.Abs(transform.position.x - Target.x) <= 0.01f)
{
TurnOnY();
if (Target == Home)
{
Target = dest.position;
}
else
{
Target = Home;
}
}
//If enemy falls off original platform it will teleport to it's intended destination
if (Mathf.Abs(Target.y - transform.position.y) >= 2f)
{
transform.position = Target;
}
transform.position = Vector2.MoveTowards(transform.position, Target, step);
}
public int RemainingHealth() { return health; }
public override void TakeDamage(int _damage, Vector3 _damageSource)
{
if(_canTakeDamage)
{
health -= _damage;
if (_damage > 0)
{
HitEffect.Play();
Knockback(_knockback, _damageSource);
BM.Play("BM_Damaged");
}
if (health <= 0)
{
BM.Play("Enemy_Death");
_canTakeDamage = false;
anim.SetBool("Dying", true);
}
}
}
void Remove()
{
Destroy(gameObject);
}
private void Knockback(Vector2 knockbackPower, Vector2 contactPos)
{
_rb.velocity = Vector2.zero;
if (contactPos.x > transform.position.x)
{
_rb.AddForce(new Vector2(-knockbackPower.x, knockbackPower.y));
}
else if (contactPos.x < transform.position.x)
{
_rb.AddForce(new Vector2(knockbackPower.x, knockbackPower.y));
}
}
override protected void OnTriggerEnter2D(Collider2D _other)
{
if (_other.CompareTag("Player"))
{
SpawnEffect();
BM.Play("BM_Attack");
_other.GetComponent<PlayerController2D>().TakeDamage(damage);
}
if (_other.gameObject.tag == "MovingPlatform")
{
onPlatform = true;
}
}
}
|
namespace Mosa.External.x86.Drawing
{
public static class MosaLogo
{
//Size in tiles
private const uint _width = 23;
private const uint _height = 7;
public static void Draw(Graphics graphics, uint tileSize)
{
uint positionX = (uint)((graphics.Width / 2) - ((_width * tileSize) / 2));
uint positionY = (uint)((graphics.Height / 2) - ((_height * tileSize) / 2));
//Can't store these as a static fields, they seem to break something
uint[] logo = new uint[] { 0x39E391, 0x44145B, 0x7CE455, 0x450451, 0x450451, 0x451451, 0x44E391 };
uint[] colors = new uint[] { 0xEB2027, 0xF19020, 0x5C903F, 0x226798 }; //Colors for each pixel
for (int ty = 0; ty < _height; ty++)
{
uint data = logo[ty];
for (int tx = 0; tx < _width; tx++)
{
int mask = 1 << tx;
if ((data & mask) == mask)
{
graphics.DrawFilledRectangle(colors[tx / 6], (int)(positionX + (tileSize * tx)), (int)(positionY + (tileSize * ty)), (int)tileSize, (int)tileSize); //Each pixel is aprox 5 tiles in width
}
}
}
}
}
}
|
using FatCat.Nes.OpCodes.AddressingModes;
namespace FatCat.Nes.OpCodes.IO
{
public class PopAccumulatorOffStack : OpCode
{
public override string Name => "PLA";
public PopAccumulatorOffStack(ICpu cpu, IAddressMode addressMode) : base(cpu, addressMode) { }
public override int Execute()
{
cpu.Accumulator = ReadFromStack();
ApplyFlag(CpuFlag.Zero, cpu.Accumulator.IsZero());
ApplyFlag(CpuFlag.Negative, cpu.Accumulator.IsNegative());
return 0;
}
}
} |
using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Windows.Controls;
namespace Kit.WPF.Controls
{
public class ObservableContextMenu : ContextMenu, INotifyPropertyChanged
{
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
///[Obsolete("Use Raise para mejor rendimiento evitando la reflección")]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
{
PropertyChangedEventHandler handler = PropertyChanged;
handler?.Invoke(this, args);
}
#endregion
#region PerfomanceHelpers
public void Raise<T>(Expression<Func<T>> propertyExpression)
{
if (this.PropertyChanged != null)
{
MemberExpression body = propertyExpression.Body as MemberExpression;
if (body == null)
throw new ArgumentException("'propertyExpression' should be a member expression");
ConstantExpression expression = body.Expression as ConstantExpression;
if (expression == null)
throw new ArgumentException("'propertyExpression' body should be a constant expression");
object target = Expression.Lambda(expression).Compile().DynamicInvoke();
PropertyChangedEventArgs e = new PropertyChangedEventArgs(body.Member.Name);
PropertyChanged(target, e);
}
}
public void Raise<T>(params Expression<Func<T>>[] propertyExpressions)
{
foreach (Expression<Func<T>> propertyExpression in propertyExpressions)
{
Raise<T>(propertyExpression);
}
}
#endregion
}
}
|
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using jcTM.UWP.ViewModels;
namespace jcTM.UWP.Views {
public sealed partial class MainPage : Page {
private MainPageModel viewModel => (MainPageModel) DataContext;
public MainPage() {
this.InitializeComponent();
DataContext = new MainPageModel();
}
protected override async void OnNavigatedTo(NavigationEventArgs e) {
while (true) {
var result = await viewModel.LoadData();
await System.Threading.Tasks.Task.Delay(5000);
}
}
}
} |
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FastSQL.App.Events
{
public class ManageIndexLoadingEvent: PubSubEvent<ManageIndexLoadingEventArgument>
{
}
public class ManageIndexLoadingEventArgument
{
public bool Loading { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using ProxyUsingFunctions;
namespace Test
{
public class Class1
{
string[] Users = { "Ivan", "Sergey", "Vladimir", "Pavel", "Andrey" };
Action Proxy = Program.ReadFile;
[Test]
public void CheckAccessAllowed()
{
string userName = "Ivan";
Assert.DoesNotThrow(() => Program.ValidateUserAccess(Users, userName));
}
[Test]
public void CheckAccessDenied()
{
string userName = "ivan";
Assert.Catch(() => Program.ValidateUserAccess(Users, userName));
}
[Test]
public void FileIsNotExist()
{
Assert.Catch(() => Program.ReadFile());
}
[Test]
public void CheckCreateProxyFunction()
{
string userName = "Andrey";
Assert.DoesNotThrow(() => Program.CreateProxy(Proxy, Users, userName));
}
[Test]
public void CheckCreateProxyActionFunction()
{
string userName = "Sergey";
Action proxy = Program.CreateProxy(Proxy, Users, userName);
Assert.DoesNotThrow(() => Program.CreateProxyAction(proxy, Program.ReadFileConsoleLogProxy));
}
}
}
|
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipelines;
using System.Threading;
using System.Threading.Tasks;
namespace Koek
{
/// <summary>
/// Allows us to observe when Complete() is called.
/// </summary>
public sealed class InterceptingPipeWriter : PipeWriter
{
public Task WriterCompleted => _writerCompleted.Task;
private readonly TaskCompletionSource<bool> _writerCompleted = new();
public InterceptingPipeWriter(PipeWriter writer)
{
_writer = writer;
}
private readonly PipeWriter _writer;
public override void Complete(Exception? exception = null)
{
_writer.Complete(exception);
_writerCompleted.SetResult(true);
}
public override async ValueTask CompleteAsync(Exception? exception = null)
{
await _writer.CompleteAsync(exception);
_writerCompleted.SetResult(true);
}
[DebuggerStepThrough]
public override void Advance(int bytes) => _writer.Advance(bytes);
[DebuggerStepThrough]
public override void CancelPendingFlush() => _writer.CancelPendingFlush();
[DebuggerStepThrough]
public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default) => _writer.FlushAsync(cancellationToken);
[DebuggerStepThrough]
public override Memory<byte> GetMemory(int sizeHint = 0) => _writer.GetMemory(sizeHint);
[DebuggerStepThrough]
public override Span<byte> GetSpan(int sizeHint = 0) => _writer.GetSpan(sizeHint);
[DebuggerStepThrough]
public override Stream AsStream(bool leaveOpen = false) => _writer.AsStream(leaveOpen);
[DebuggerStepThrough]
public override ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default) => _writer.WriteAsync(source, cancellationToken);
}
}
|
namespace PRGTrainer.Core.StatisticsCollector
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Threading.Tasks;
using log4net;
/// <summary>
/// Сборщик статистики.
/// </summary>
public class StatisticsCollector : IStatisticsCollector
{
#region Private fields
/// <summary>
/// Таблица с результатами пользователя.
/// </summary>
private const string UserResultTable = @"UserResults";
/// <summary>
/// Таблица с коллекцией вопросов.
/// </summary>
private const string QuestionResultTable = @"QuestionResults";
/// <summary>
/// Строка подключения к бд для статистики пользователя.
/// </summary>
private readonly string _connectionString;
#endregion
/// <summary>
/// Инициализирует экземпляр <see cref="StatisticsCollector"/>
/// </summary>
public StatisticsCollector()
{
_connectionString = ConfigurationManager.ConnectionStrings[@"UserStatistics"].ConnectionString;
Logger = LogManager.GetLogger(typeof(StatisticsCollector));
}
/// <summary>
/// Логгер.
/// </summary>
private ILog Logger { get; }
/// <inheritdoc />
public async Task SaveResult(IEnumerable<string> questions)
{
var query = "DECLARE @val int;\n\r";
foreach (var question in questions)
query += string.Format(@"IF EXISTS (SELECT 1 FROM dbo.{0} WHERE question = '{1}')
BEGIN
SET @val = (SELECT wrongcount FROM dbo.{0} WHERE question = '{1}') + 1;
UPDATE dbo.{0} SET wrongcount = @val WHERE question = '{1}';
END
ELSE
BEGIN
INSERT INTO dbo.{0} (question, wrongcount) VALUES ('{1}', 1);
END{2}{2}", QuestionResultTable, question, Environment.NewLine);
var connection = new SqlConnection(_connectionString);
try
{
await connection.OpenAsync().ConfigureAwait(false);
using (var command = new SqlCommand(query, connection))
{
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
if(Logger.IsErrorEnabled)
Logger.Error(@"Не удалось записать вопросы, на которые был дал неверный ответ!", exception);
}
finally
{
connection.Close();
}
}
/// <inheritdoc />
public async Task SaveUserResult(int id, string user, int successRate)
{
var connection = new SqlConnection(_connectionString);
try
{
await connection.OpenAsync().ConfigureAwait(false);
var query = string.IsNullOrWhiteSpace(user)
? $"INSERT INTO dbo.{UserResultTable} (identifier, result, finishtime) VALUES ({id}, {successRate}, {GetDataTime()});"
: $"INSERT INTO dbo.{UserResultTable} (identifier, username, result, finishtime) VALUES ({id}, '{user}', {successRate}, {GetDataTime()});";
using (var command = new SqlCommand(query, connection))
{
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
if (Logger.IsErrorEnabled)
Logger.Error(@"Не удалось записать результат пользователя!", exception);
}
finally
{
connection.Close();
}
}
/// <summary>
/// Получает время и дату для SQL
/// </summary>
/// <returns>Текущее дата и время.</returns>
private string GetDataTime()
{
var dateTime = DateTime.Now;
return string.Format(
@"convert(datetime2, '{0}-{1}-{2} {3}:{4}:{5}')",
dateTime.Year,
ConvertLessToTenValues(dateTime.Month),
ConvertLessToTenValues(dateTime.Day),
ConvertLessToTenValues(dateTime.Hour),
ConvertLessToTenValues(dateTime.Minute),
ConvertLessToTenValues(dateTime.Second));
}
/// <summary>
/// Добавляет значениям меньше, чем 10 ноль
/// </summary>
/// <param name="value">Значение.</param>
/// <returns>Откорректированное значение.</returns>
private string ConvertLessToTenValues(int value)
{
return value < 10 ? $"0{value}" : value.ToString();
}
}
} |
namespace FatCat.Nes.OpCodes.AddressingModes
{
public class IndirectYMode : AddressMode
{
private byte highAddress;
private byte lowAddress;
public override string Name => "(Indirect),Y";
private bool HasPaged
{
get
{
var highPart = cpu.AbsoluteAddress & 0xff00;
return highPart != highAddress << 8;
}
}
public IndirectYMode(ICpu cpu) : base(cpu) { }
public override int Run()
{
var readValue = ReadProgramCounter();
lowAddress = cpu.Read((ushort)(readValue & 0x00ff));
highAddress = cpu.Read((ushort)((readValue + 1) & 0x00ff));
SetAbsoluteAddress(highAddress, lowAddress);
cpu.AbsoluteAddress += cpu.YRegister;
return HasPaged ? 1 : 0;
}
}
} |
namespace WebApplication.Api.Models
{
public class BasketModel
{
public int Id { get; set; }
public int LaptopId { get; set; }
public LaptopsModel Laptop { get; set; }
}
} |
namespace SGDE.DataEFCoreSQL.Repositories
{
#region Using
using System.Collections.Generic;
using System.Linq;
using Domain.Entities;
using Domain.Repositories;
using Microsoft.EntityFrameworkCore;
using System;
#endregion
public class UserDocumentRepository : IUserDocumentRepository, IDisposable
{
private readonly EFContextSQL _context;
public UserDocumentRepository(EFContextSQL context)
{
_context = context;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
}
private bool UserDocumentExists(int id)
{
return GetById(id) != null;
}
public List<UserDocument> GetAll(int userId)
{
if (userId != 0)
{
return _context.UserDocument
.Include(x => x.TypeDocument)
.Include(x => x.User)
.Where(x => x.UserId == userId)
.ToList();
}
return _context.UserDocument
.Include(x => x.TypeDocument)
.Include(x => x.User)
.ToList();
}
public UserDocument GetById(int id)
{
return _context.UserDocument
.Include(x => x.TypeDocument)
.Include(x => x.User)
.FirstOrDefault(x => x.Id == id);
}
public UserDocument Add(UserDocument newUserDocument)
{
_context.UserDocument.Add(newUserDocument);
_context.SaveChanges();
return newUserDocument;
}
public bool Update(UserDocument userDocument)
{
if (!UserDocumentExists(userDocument.Id))
return false;
_context.UserDocument.Update(userDocument);
_context.SaveChanges();
return true;
}
public bool Delete(int id)
{
if (!UserDocumentExists(id))
return false;
var toRemove = _context.UserDocument.Find(id);
_context.UserDocument.Remove(toRemove);
_context.SaveChanges();
return true;
}
}
}
|
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.IdGenerators;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace AlquilerVideo.Models
{
public class Transaccion
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
[BsonRepresentation(BsonType.ObjectId)]
public string _id { get; set; }
public DateTime fechaTransaccion { get; set; }
[Required]
[DisplayName("Fecha Alquiler")]
public DateTime? fechaRegreso { get; set; }
[Required]
[DisplayName("Tipo Movimiento")]
public string tipoMovimiento { get; set; }
public UsuarioRegistra usuarioRegistra { get; set; }
public List<Pelicula> detallePelicula { get; set; }
public Cliente cliente { get; set; }
public string tempPelicula { get; set; }
public string tempCliente { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Voronov.Nsudotnet.BuildingCompanyIS.Entities;
using Voronov.Nsudotnet.BuildingCompanyIS.Entities.RelationTables;
using Voronov.Nsudotnet.BuildingCompanyIS.Logic.DataStructures;
using Voronov.Nsudotnet.BuildingCompanyIS.Logic.DbInterfaces;
using Voronov.Nsudotnet.BuildingCompanyIS.Logic.Exceptions;
namespace Voronov.Nsudotnet.BuildingCompanyIS.Logic.Impl.DbImpl
{
public class SqlOrganizationUnitsService : CrudServiceBase<OrganizationUnit>, IOrganizationUnitsService
{
public SqlOrganizationUnitsService(DatabaseModel context) : base(context)
{
}
public IQueryable<OrganizationUnit> GetOrganizationUnitsWithManager()
{
return
BaseSet
.Include(e => e.OrganizationUnitManager.Engineer);
}
}
} |
using Microsoft.AspNetCore.Mvc;
using Oppgave3.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Oppgave3.DAL
{
public interface IFAQRepository
{
Task<List<Kategori>> HentKategorier();
Task<List<FAQ>> HentFAQer();
Task<bool> EndreFAQ([FromBody] FAQ faq);
Task<List<Forslag>> HentForslag();
Task<int> LagreForslag([FromBody] Forslag forslag);
}
} |
using PuddingWolfLoader.Framework.Container;
using PuddingWolfLoader.Framework.Events;
using PuddingWolfLoader.Framework.ViewModel;
using PuddingWolfLoader.SDK;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using XQSimulator.Model;
namespace PuddingWolfLoader.Framework.Util
{
public class PluginLoader
{
static LogContainer logContainer;
static PluginLoader()
{
logContainer = LogContainer.CreateInstance<PluginLoader>();
LogCore.RegLogContainer(logContainer);
}
public delegate int Initialize(int authCode);//dll的初始化函数
public delegate IntPtr AppInfo();//dll的获取信息函数
public delegate IntPtr _eventPrivateMsg(int subType, int msgId, long userId, string msg, int font);//dll的群消息函数
public delegate IntPtr _eventGroupMsg(int subType, int msgId, long group, long userId, string fromAnonymous,
string msg, int font);//dll的私聊消息函数_eventGroupMsg
public static void LoadPlugins()
{
Process process = new Process();
var dir = Directory.GetCurrentDirectory() + "\\plugins";
var tempdirinfo = new DirectoryInfo(Directory.GetCurrentDirectory() + "\\plugins\\temp");
if (tempdirinfo.Exists)
{
tempdirinfo.Delete(true);
}
tempdirinfo.Create();
//copy
var plugindir = new DirectoryInfo(dir);//Real Plugin Dir
plugindir.GetFiles("*.dll").ToList().ForEach(f =>
{
f.CopyTo(Path.Combine(tempdirinfo.FullName, f.Name));
});
//copy finish
foreach (var file in tempdirinfo.GetFiles("*.dll"))
{
logContainer.Info("正在加载" + file.Name);
try
{
LoadPlugin(file.FullName);
}
catch (Exception ex)
{
logContainer.Error(ex.Message + "," + new Plugin() { PluginName = file.Name });
}
}
}
public static void ReLoadPlugins()
{
ModulesViewModel.Instance.Plugins.ToList().ForEach(p => Kernel32.FreeLibrary(p.ProcessPtr.ToInt32()));
GC.Collect();
ModulesViewModel.Instance.Plugins.Clear();//Clear Plugin List
LoadPlugins();
}
public static void LoadPlugin(string path)
{
var dllptr = Kernel32.LoadLibraryA(path);
if (dllptr.ToInt32() == 0)
{
throw new Exception("DLL句柄为0");
}
var address_Initialize = Kernel32.GetProcAddress(dllptr, "Initialize");
var address_AppInfo = Kernel32.GetProcAddress(dllptr, "AppInfo");
var InitializeMethod = Marshal.GetDelegateForFunctionPointer<Initialize>(address_Initialize);
var AppInfoMethod = Marshal.GetDelegateForFunctionPointer<AppInfo>(address_AppInfo);
//一个json
/*
{
"id": 0,
"loggerAddr": 0,
"getInstalledApps": 0,
"downLoad": 0,
"sdkFuncs": 0
}
*/
string init_json;
using (var stream = new MemoryStream())
{
using (var writer = new Utf8JsonWriter(stream))
{
writer.WriteStartObject();
writer.WriteString("id", "i.dont.down");
writer.WriteNumber("loggerAddr", 0);
writer.WriteNumber("downLoad", 0);
writer.WriteNumber("getInstalledApps", 0);
writer.WriteNumber("sdkFuncs", GetSdkFuncs.GetSdkFuncsPtr.ToInt64());
writer.WriteEndObject();
}
init_json = Encoding.UTF8.GetString(stream.ToArray());
}
InitializeMethod.Invoke(Marshal.StringToHGlobalAnsi(init_json).ToInt32());
var json = Marshal.PtrToStringAnsi(AppInfoMethod.Invoke());
var jc = JsonDocument.Parse(json);
var plug = new Plugin()
{
PluginName = jc.RootElement.GetProperty("id").GetString(),
PluginVersion = jc.RootElement.GetProperty("version").GetString(),
PluginAuthor = jc.RootElement.GetProperty("author").GetString(),
PluginDesc = jc.RootElement.GetProperty("description").GetString(),
ProcessPtr = dllptr
};
ModulesViewModel.Instance.Plugins.Add(plug);
logContainer.Info("成功加载");
}
public static void GroupMsgEvent(long group,long user,string msg)
{
ModulesViewModel.Instance.Plugins.ToList().ForEach(x =>
{
var address_GroupMsg = Kernel32.GetProcAddress(x.ProcessPtr, "_eventGroupMsg");
var _eventGroupMsgMethod = Marshal.GetDelegateForFunctionPointer<_eventGroupMsg>(address_GroupMsg);
_eventGroupMsgMethod.Invoke(0,0,group,user,"",msg,0);
});
}
}
}
|
using System;
using Assignment1.Math;
namespace Assignment1
{
public class Man
{
public int age;
}
class MainClass
{
public static void Main(string[] args)
{
var sajid = new Person();
sajid.FirstName = "Sajid";
sajid.LastName = "khan";
sajid.Introduce();
Console.WriteLine();
//calculator class
//var cal = new Calculator();
// *** static implementation ***
var result = Calculator.add(1, 2);
Console.WriteLine(result);
//Array
Console.WriteLine();
int[] number = new int[3];
number[0] = 1;
Console.WriteLine(number[0]);
Console.WriteLine(number[1]);
Console.WriteLine(number[2]);
Console.WriteLine();
var flags = new bool[3];
flags[0] = true;
Console.WriteLine(flags[0]);
Console.WriteLine(flags[1]);
Console.WriteLine(flags[2]);
// *** String ***
var firstName = "sajid";
var lastName = "Khan";
var fullName = string.Format("My name is {0}{1}", firstName, lastName);
var names = new string[3] { "chand", "Sultana", "siddiqua"};
var combainedName = string.Join(" ", names);
Console.WriteLine(fullName);
Console.WriteLine("Spouse Name: {0}",combainedName);
var text = "Hi there!\nPlz follow this path\nC:\\folder1\\folder2";
Console.WriteLine(text);
var text2 = @"Hi there!
Plz follow this path
C:\folder2\folder3";
Console.WriteLine(text2);
// *** Value types and Reference type example ***
// *** Value types example1 ***
var a = 10;
var b = a;
b++;
Console.WriteLine("a :{0}, b:{1}",a,b);
// *** Reference type example1 ***
var array1 = new int[3] { 1, 2, 3 };
var array2 = array1;
Console.WriteLine("Before :: array1[0] :{0} , array1[1] :{1}", array1[0], array2[0]);
array2[0] = 0;
Console.WriteLine("After :: array1[0] :{0} , array1[1] :{1}", array1[0],array2[0]);
// *** Value types example2 ***
var num = 1;
// Increament methods argument 'num' is different from var 'num'
Increment(num);
// after value incremented by 10 the argument 'num' is immediately destroyed
Console.WriteLine(num);// 1
// *** Reference type example2 ***
var m = new Man() { age=20};
//Here agrument 'man' obejct is references same object 'man' in Heap
MakeOld(m);
Console.WriteLine(m.age);
void Increment(int n)
{
n += 10;
}
void MakeOld(Man man)
{
man.age += 10;
}
}
}
}
|
using System.Collections.Generic;
using ChesterDevs.Core.Aspnet.App.RemoteData.EventData;
using ChesterDevs.Core.Aspnet.App.RemoteData.YouTube;
namespace ChesterDevs.Core.Aspnet.Models.ViewModels
{
public class HomeViewModel
{
public List<EventItem> EventItems { get; set; }
public List<YouTubeVideo> YouTubeVideos { get; set; }
}
} |
using strange.extensions.mediation.impl;
using UnityEngine;
using syscrawl.Common.Extensions;
namespace syscrawl.Game.Views.Levels
{
public class LevelSceneView : View
{
internal GameObject previousNodes;
internal GameObject currentNodes;
internal GameObject activeNodes;
internal GameObject furtherAheadNodes;
internal void Init()
{
activeNodes =
gameObject.CreateChildObject("Active Nodes", Vector3.zero);
previousNodes =
gameObject.CreateChildObject("Previous Nodes", Vector3.zero);
currentNodes =
gameObject.CreateChildObject("Current Nodes", Vector3.zero);
furtherAheadNodes =
gameObject.CreateChildObject("FurtherAhead Nodes", Vector3.zero);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TheTaleOfU.Enums;
namespace TheTaleOfU
{
public class Scenario
{
public int Id { get; set; }
public string ScenarioDescription { get; set; }
public PlayerType AllowedPlayerTypes { get; set; }
public List<Option> Options { get; set; }
public bool IsEndOfScenarioRoute { get; set; }
public string EndOfEventMethodName { get; set; }
[NotMapped]
public bool HasEvent => !string.IsNullOrEmpty(EndOfEventMethodName);
[NotMapped]
private Player CurrentPlayer { get; set; }
/// <summary>
/// The linked item is either an item that can be gained from this scenario or an item that can be used in this scenario
/// </summary>
public virtual ScenarioEvent Event { get; set; }
public void RunScenario(Player player)
{
CurrentPlayer = player;
Console.WriteLine(ScenarioDescription);
if (IsEndOfScenarioRoute || HasEvent)
{
Event = new TheTaleOfUContext().Events.FirstOrDefault(a => a.OriginScenarioId == Id);
if(Event!=null)
CallEventFromString(EndOfEventMethodName);
}
if (Options == null)
Options = new TheTaleOfUContext().Options.Where(a => a.OriginScenarioId == Id).ToList();
Console.ReadKey();
foreach (var o in Options)
{
Console.WriteLine($"{o.OptionIdentifier} : {o.Text}");
}
string option = "";
var wasValidOption = false;
while (!wasValidOption)
{
option = Console.ReadLine();
wasValidOption = ProcessOption(option);
if (!wasValidOption)
Console.WriteLine("Please enter a valid option number");
}
var numericOption = Convert.ToInt32(option);
var nextOption = Options.FirstOrDefault(a => a.OptionIdentifier == numericOption);
var scenario = new TheTaleOfUContext().Scenarios.FirstOrDefault(a => a.Id == nextOption.NextScenarioId);
nextOption.NextScenario = scenario;
if (nextOption.NextScenario == null)
return;
nextOption.NextScenario.RunScenario(player);
}
public bool ProcessOption(string selectedOption)
{
var strippedOption = selectedOption.Trim();
if (!Options.Any(a => a.OptionIdentifier == Convert.ToInt32(strippedOption)))
{
return false;
}
return true;
}
public void CallEventFromString(string eventName)
{
MethodInfo mi = this.GetType().GetMethod(eventName);
if (mi != null)
mi.Invoke(this, null);
}
public void UseShrinkRay()
{
}
public void UseAnItem()
{
if (CurrentPlayer.ActiveItem.Durability > 0)
{
CurrentPlayer.ActiveItem.Durability--;
}
if (CurrentPlayer.ActiveItem.Durability == 0)
CurrentPlayer.Inventory.Remove(CurrentPlayer.ActiveItem);
}
public void GainItem()
{
CurrentPlayer.Inventory.Add(Event.LinkedItem);
}
public void TakeDamage()
{
CurrentPlayer.Health -= Event.LinkedItem.Value;
}
public void HealthGain()
{
CurrentPlayer.Health += Event.LinkedItem.Value;
Console.WriteLine($"Congratulations {CurrentPlayer.Name} you have gained {Event.LinkedItem.Value} health for using a {Event.LinkedItem.Name}");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;
namespace CourseLibrary.API.Helpers.Extensions
{
public static class ObjectExtensions
{
public static ExpandoObject ShapeData<TSource>(this TSource source, string fields = null)
{
if (source == null) throw new ArgumentNullException(nameof(source));
var propertyInfoList = ReflectionHelper.GetPropertyInfoListByFields<TSource>(fields);
return GetDataShappedObject(source, propertyInfoList);
}
private static ExpandoObject GetDataShappedObject<TSource>( TSource source, List<PropertyInfo> propertyInfoList)
{
var dataShapedObject = new ExpandoObject();
foreach (var propertyInfo in propertyInfoList)
{
var propertyValue = propertyInfo.GetValue(source);
((IDictionary<string, object>) dataShapedObject).Add(propertyInfo.Name, propertyValue);
}
return dataShapedObject;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Blog.Domain.BlogExceptions;
namespace Blog.Domain.Model
{
public class Blog
{
private readonly List<Post> _posts = new List<Post>();
public Blog(Guid id)
{
Id = id;
}
public Guid Id { get; }
public IEnumerable<Post> Posts => _posts;
public void AddPost(Post post)
{
_posts.Add(post);
Validate();
}
private void Validate()
{
// Max 10 posts
if (_posts.Count > 10)
throw new MaxPostLimitExceeded(
$"Maximum postings limit exceeded. You already has {_posts.Count} postings");
}
public void DeletePost(Guid postId)
{
var toDelete = _posts.FirstOrDefault(a => a.Id == postId);
_posts.Remove(toDelete);
Validate();
}
}
} |
using LuaInterface;
using RO;
using SLua;
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
public class Lua_RO_ResourceID : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int CheckFileIsRecorded_s(IntPtr l)
{
int result;
try
{
string file;
LuaObject.checkType(l, 1, out file);
bool b = ResourceID.CheckFileIsRecorded(file);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, b);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ReMap_s(IntPtr l)
{
int result;
try
{
string config;
LuaObject.checkType(l, 1, out config);
bool force;
LuaObject.checkType(l, 2, out force);
ResourceID.ReMap(config, force);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int MakeAndReadFromResource_s(IntPtr l)
{
int result;
try
{
XmlSerializer serializer;
LuaObject.checkType<XmlSerializer>(l, 1, out serializer);
ResourceID.MakeAndReadFromResource(serializer);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_ResFolder(IntPtr l)
{
int result;
try
{
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, "Assets/Resources/");
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_LuaFolder(IntPtr l)
{
int result;
try
{
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, "Script/");
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_parts(IntPtr l)
{
int result;
try
{
ResourceID resourceID = (ResourceID)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, resourceID.parts);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_parts(IntPtr l)
{
int result;
try
{
ResourceID resourceID = (ResourceID)LuaObject.checkSelf(l);
List<object> parts;
LuaObject.checkType<List<object>>(l, 2, out parts);
resourceID.parts = parts;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_IDStr(IntPtr l)
{
int result;
try
{
ResourceID resourceID = (ResourceID)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, resourceID.IDStr);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_pathData(IntPtr l)
{
int result;
try
{
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, ResourceID.pathData);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "RO.ResourceID");
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_ResourceID.CheckFileIsRecorded_s));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_ResourceID.ReMap_s));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_ResourceID.MakeAndReadFromResource_s));
LuaObject.addMember(l, "ResFolder", new LuaCSFunction(Lua_RO_ResourceID.get_ResFolder), null, false);
LuaObject.addMember(l, "LuaFolder", new LuaCSFunction(Lua_RO_ResourceID.get_LuaFolder), null, false);
LuaObject.addMember(l, "parts", new LuaCSFunction(Lua_RO_ResourceID.get_parts), new LuaCSFunction(Lua_RO_ResourceID.set_parts), true);
LuaObject.addMember(l, "IDStr", new LuaCSFunction(Lua_RO_ResourceID.get_IDStr), null, true);
LuaObject.addMember(l, "pathData", new LuaCSFunction(Lua_RO_ResourceID.get_pathData), null, false);
LuaObject.createTypeMetatable(l, null, typeof(ResourceID));
}
}
|
using AnimationEditor.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace AnimationEditor
{
/// <summary>
/// Interaction logic for Hitbox3Window.xaml
/// </summary>
public partial class Hitbox3Window : Window
{
public HitboxV3EditorViewModel ViewModel => DataContext as HitboxV3EditorViewModel;
public Hitbox3Window(MainViewModel vm)
{
InitializeComponent();
DataContext = new HitboxV3EditorViewModel(vm);
}
private void ButtonAdd_Click(object sender, RoutedEventArgs e)
{
ViewModel.AddHitboxEntry();
}
private void ButtonRemove_Click(object sender, RoutedEventArgs e)
{
ViewModel.RemoveHitboxEntry();
}
}
}
|
namespace UserVoiceSystem.Data.Models
{
using System.ComponentModel.DataAnnotations;
using Common.Models;
public class Comment : BaseModel<int>
{
[Required]
[MaxLength(10000)]
[MinLength(5)]
public string Content { get; set; }
[Required]
[MaxLength(16)]
public string AuthorIp { get; set; }
[MaxLength(500)]
[RegularExpression(@"^(?("")("".+?(?<!\\)""@)|(([0-9A-Za-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9A-Za-z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9A-Za-z][-\w]*[0-9A-Za-z]*\.)+[A-Za-z0-9][\-a-zA-Z0-9]{0,22}[A-Za-z0-9]))$", ErrorMessage = "Invalid Email address !")]
public string AuthorEmail { get; set; }
public int IdeaId { get; set; }
public virtual Idea Idea { get; set; }
}
}
|
using System.Linq;
using CppSharp.AST;
using CppSharp.AST.Extensions;
namespace CppSharp.Passes
{
public class ParamTypeToInterfacePass : TranslationUnitPass
{
public ParamTypeToInterfacePass()
{
VisitOptions.VisitClassBases = false;
VisitOptions.VisitClassFields = false;
VisitOptions.VisitEventParameters = false;
VisitOptions.VisitNamespaceEnums = false;
VisitOptions.VisitNamespaceEvents = false;
VisitOptions.VisitTemplateArguments = false;
}
public override bool VisitFunctionDecl(Function function)
{
if (!base.VisitFunctionDecl(function))
return false;
if (!function.IsOperator || function.Parameters.Count > 1)
{
var originalReturnType = function.OriginalReturnType;
ChangeToInterfaceType(ref originalReturnType);
function.OriginalReturnType = originalReturnType;
}
if (function.OperatorKind != CXXOperatorKind.Conversion &&
function.OperatorKind != CXXOperatorKind.ExplicitConversion)
foreach (var parameter in function.Parameters.Where(
p => p.Kind != ParameterKind.OperatorParameter))
{
var qualifiedType = parameter.QualifiedType;
ChangeToInterfaceType(ref qualifiedType);
parameter.QualifiedType = qualifiedType;
}
return true;
}
public override bool VisitProperty(Property property)
{
if (!base.VisitProperty(property))
return false;
var type = property.QualifiedType;
ChangeToInterfaceType(ref type);
property.QualifiedType = type;
return true;
}
private static void ChangeToInterfaceType(ref QualifiedType type)
{
var finalType = (type.Type.GetFinalPointee() ?? type.Type).Desugar();
Class @class;
if (!finalType.TryGetClass(out @class))
return;
Class @interface = @class.GetInterface();
if (@interface == null)
return;
type.Type = (Type) type.Type.Clone();
finalType = (type.Type.GetFinalPointee() ?? type.Type).Desugar();
finalType.TryGetClass(out @class, @interface);
}
}
}
|
using System.Text;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Drawing;
using System.Collections.ObjectModel;
using System.Xml;
using System.ComponentModel;
using System.Reflection;
namespace LinnworksAPI
{
public class CountryRegion
{
public Int32 pkRegionRowId;
public String RegionCode;
public String RegionName;
public Double? TaxRate;
public Guid fkCountryId;
public CountryRegionReplaceWith ReplaceWith;
public Boolean IsHomeRegion;
public Int32 TagsCount;
}
} |
namespace Triton.Game.Abstraction
{
using System;
using System.Runtime.CompilerServices;
using Triton.Game.Mapping;
public class EntityDef
{
[CompilerGenerated]
private Triton.Game.Mapping.EntityDef entityDef_0;
[CompilerGenerated]
private int int_0;
[CompilerGenerated]
private int int_1;
[CompilerGenerated]
private int int_2;
[CompilerGenerated]
private int int_3;
[CompilerGenerated]
private int int_4;
[CompilerGenerated]
private int int_5;
[CompilerGenerated]
private int int_6;
[CompilerGenerated]
private string string_0;
[CompilerGenerated]
private string string_1;
[CompilerGenerated]
private string string_2;
[CompilerGenerated]
private string string_3;
[CompilerGenerated]
private TAG_CARDTYPE tag_CARDTYPE_0;
[CompilerGenerated]
private TAG_CLASS tag_CLASS_0;
[CompilerGenerated]
private TAG_RACE tag_RACE_0;
[CompilerGenerated]
private TAG_RARITY tag_RARITY_0;
public EntityDef(Triton.Game.Mapping.EntityDef backingObject)
{
this.EntityDef_0 = backingObject;
this.CardId = this.EntityDef_0.GetCardId();
this.Class = this.EntityDef_0.GetClass();
this.Race = this.EntityDef_0.GetRace();
this.Rarity = this.EntityDef_0.GetRarity();
this.Name = this.EntityDef_0.GetName();
this.FlavorText = this.EntityDef_0.GetFlavorText();
this.CardType = this.EntityDef_0.GetCardType();
this.Cost = this.EntityDef_0.GetTag(GAME_TAG.COST);
this.Attack = this.EntityDef_0.GetTag(GAME_TAG.ATK);
this.Health = this.EntityDef_0.GetTag(GAME_TAG.HEALTH);
this.Charge = this.EntityDef_0.GetTag(GAME_TAG.CHARGE);
this.Silence = this.EntityDef_0.GetTag(GAME_TAG.SILENCE);
this.Taunt = this.EntityDef_0.GetTag(GAME_TAG.TAUNT);
this.Battlecry = this.EntityDef_0.GetTag(GAME_TAG.BATTLECRY);
this.CardText = this.EntityDef_0.GetStringTag(GAME_TAG.CARDTEXT_INHAND);
}
public int Attack
{
[CompilerGenerated]
get
{
return this.int_1;
}
[CompilerGenerated]
private set
{
this.int_1 = value;
}
}
public int Battlecry
{
[CompilerGenerated]
get
{
return this.int_6;
}
[CompilerGenerated]
private set
{
this.int_6 = value;
}
}
public string CardId
{
[CompilerGenerated]
get
{
return this.string_0;
}
[CompilerGenerated]
private set
{
this.string_0 = value;
}
}
public string CardText
{
[CompilerGenerated]
get
{
return this.string_3;
}
[CompilerGenerated]
private set
{
this.string_3 = value;
}
}
public TAG_CARDTYPE CardType
{
[CompilerGenerated]
get
{
return this.tag_CARDTYPE_0;
}
[CompilerGenerated]
private set
{
this.tag_CARDTYPE_0 = value;
}
}
public int Charge
{
[CompilerGenerated]
get
{
return this.int_3;
}
[CompilerGenerated]
private set
{
this.int_3 = value;
}
}
public TAG_CLASS Class
{
[CompilerGenerated]
get
{
return this.tag_CLASS_0;
}
[CompilerGenerated]
private set
{
this.tag_CLASS_0 = value;
}
}
public int Cost
{
[CompilerGenerated]
get
{
return this.int_0;
}
[CompilerGenerated]
private set
{
this.int_0 = value;
}
}
internal Triton.Game.Mapping.EntityDef EntityDef_0
{
[CompilerGenerated]
get
{
return this.entityDef_0;
}
[CompilerGenerated]
set
{
this.entityDef_0 = value;
}
}
public string FlavorText
{
[CompilerGenerated]
get
{
return this.string_2;
}
[CompilerGenerated]
private set
{
this.string_2 = value;
}
}
public int Health
{
[CompilerGenerated]
get
{
return this.int_2;
}
[CompilerGenerated]
private set
{
this.int_2 = value;
}
}
public string Name
{
[CompilerGenerated]
get
{
return this.string_1;
}
[CompilerGenerated]
private set
{
this.string_1 = value;
}
}
public TAG_RACE Race
{
[CompilerGenerated]
get
{
return this.tag_RACE_0;
}
[CompilerGenerated]
private set
{
this.tag_RACE_0 = value;
}
}
public TAG_RARITY Rarity
{
[CompilerGenerated]
get
{
return this.tag_RARITY_0;
}
[CompilerGenerated]
private set
{
this.tag_RARITY_0 = value;
}
}
public int Silence
{
[CompilerGenerated]
get
{
return this.int_4;
}
[CompilerGenerated]
private set
{
this.int_4 = value;
}
}
public int Taunt
{
[CompilerGenerated]
get
{
return this.int_5;
}
[CompilerGenerated]
private set
{
this.int_5 = value;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
namespace BlackJackApp
{
public partial class Board : System.Web.UI.Page
{
//CardDealer theBadGuy;
//CardPlayer[] cardPlayers;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//System.Collections.ArrayList deck;
//string s = Server.MapPath("~/Images/75/");
//string[] paths = System.IO.Directory.GetFiles(s);
//string temp = null;
//deck = new System.Collections.ArrayList();
//foreach (string r in paths)
//{
// temp = System.IO.Path.GetFileName(r);
// if (!temp.StartsWith("back"))
// {
// deck.Add(temp);
// }
//}
//int players = string.IsNullOrEmpty(Session["SelectedPlayers"].ToString()) ? -1 : int.Parse(Session["SelectedPlayers"].ToString());
//for (int r = 0; r<players;r++)
//{
// cardPlayers[r] = BuildPlayer("Player :"+(r+1)); //Player table setup
//}
//theBadGuy = BuildDealer(deck); // Give imported image adresses as a deck to dealer and setup tables
//startGame();
}
}
//public CardDealer BuildDealer(ArrayList deck)
//{
// TableCell cellCards = new TableCell(), cellStats = new TableCell();
// Table table = new Table();
// TableRow row = new TableRow();
// table.HorizontalAlign = HorizontalAlign.Center;
// row.Cells.AddAt(0, cellCards);
// row.Cells.AddAt(1, cellStats);
// table.Rows.Add(row);
// dealersBoard.Controls.Add(table);
// return new CardDealer(cellCards, cellStats, deck);
//}
// public CardPlayer BuildPlayer(string name)
// {
// TableCell cellCards = new TableCell(), cellStats = new TableCell();
// Table table = new Table();
// TableRow row = new TableRow();
// table.Rows.Add(row);
// row.Controls.Add(cellCards);
// row.Controls.Add(cellStats);
// playersBoard.Controls.Add(table);
// return new CardPlayer(cellCards,cellStats,name);
// }
// public class CardPlayer
// {
// private TableCell cellCards { set; get; }
// private TableCell cellStats{set;get;}
// private string name;
// public CardPlayer(TableCell cellCards, TableCell cellStats, string playerName)
// {
// this.cellCards = cellCards;
// this.cellStats = cellStats;
// name = playerName;
// }
// public void recieveCard(string imagepath)
// {
// Image img = new Image();
// img.ImageUrl = imagepath;
// cellCards.Controls.Add(img);
// }
// }
// public class CardDealer
// {
// private TableCell cellCards, cellStats;
// private ArrayList deck;
// private Random randomGen;
// public CardDealer(TableCell cellCards, TableCell cellStats, ArrayList deck)
// {
// this.cellCards = cellCards;
// this.cellStats = cellStats;
// this.deck = deck;
// }
// public string drawCard()
// {
// if (deck.Count > 0)
// {
// int pick = randomGen.Next(deck.Count - 1);
// string ret = deck[pick].ToString();
// deck.RemoveAt(pick);
// return ret;
// }
// else return "empty";
// }
// }
//}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Alword.Algoexpert.Tier1
{
public class MoveElementToEndTask
{
public static List<int> MoveElementToEnd(List<int> array, int toMove)
{
int left = 0;
int right = array.Count - 1;
while (left < right)
{
while (array[right] == toMove && right > left)
right--;
while (array[left] != toMove && right > left)
left++;
var temp = array[left];
array[left] = array[right];
array[right] = temp;
}
return array;
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
using Quartz;
namespace Peppy.Quartz
{
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseQuartzAutostartJob<TJob>(this IApplicationBuilder applicationBuilder)
where TJob : IJob
{
var applicationLifetime = applicationBuilder.ApplicationServices.GetRequiredService<IApplicationLifetime>();
var quartzJobManager = applicationBuilder.ApplicationServices.GetRequiredService<IQuartzJobManager>();
applicationLifetime.ApplicationStarted.Register(async () => await quartzJobManager.RunJobAsync<TJob>());
applicationLifetime.ApplicationStopping.Register(async () => await quartzJobManager.DeleteJobAsync<TJob>());
return applicationBuilder;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Maydear.Extensions.Security
{
/// <summary>
/// 密码模式
/// </summary>
public enum CipherMode
{
ECB,
NONE,
CBC,
CCM,
CFB,
CTR,
CTS,
EAX,
GCM,
GOFB,
OCB,
OFB,
OPENPGPCFB,
SIC
}
}
|
using ShopOnline.Models.EVShop20;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ShopOnline.Controllers
{
public class ProductController : Controller
{
EVShop20 db = new EVShop20();
// GET: Product
public ActionResult List(String SupplierId = "", int CategoryId = 0, String Keywords = "")
{
if (SupplierId != "")
{
var model = db.Products
.Where(p => p.SupplierId == SupplierId);
return View(model);
}
else if (CategoryId != 0)
{
var model = db.Products
.Where(p => p.CategoryId == CategoryId);
return View(model);
}
else if (Keywords != "")
{
var model = db.Products
.Where(p => p.Name.Contains(Keywords));
return View(model);
}
return View(db.Products);
}
public ActionResult Detail(int Id)
{
var model = db.Products.Find(Id);
model.Views++;//tang so lan xem
var views = Request.Cookies["views"];//lay cookie
if(views==null)
{
views = new HttpCookie("views");
}
views.Values[Id.ToString()] = Id.ToString();//bo sung hang da xem
views.Expires = DateTime.Now.AddMonths(1);//dat thoi han
Response.Cookies.Add(views);
var keys = views.Values.AllKeys.Select(k => int.Parse(k)).ToList();//lay list<int> chua ma hang da xem tu cookie
ViewBag.Views = db.Products.Where(p => keys.Contains(p.Id));
return View(model);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Volatile;
using NetCode;
using NetcodeTest.Util;
using NetcodeTest.Events;
namespace NetcodeTest.Entities
{
[EnumerateSyncEntity]
public class Asteroid : Physical
{
[Synchronisable(SyncFlags.HalfPrecision)]
public float Size { get; protected set; }
public const float MinimumSize = 8f;
public const float EjectionVelocity = 3f;
public const float EjectionRotation = 0.2f;
public static Color Color = new Color(0.7f, 0.7f, 0.7f);
public Asteroid()
{
}
public Asteroid( Vector2 position, Vector2 velocity, float size, float angle, float angleV)
{
Position = position;
Size = size;
Velocity = velocity;
Angle = angle;
AngularVelocity = angleV;
Hitpoints = size * size / 12.0;
}
public override void Draw(SpriteBatch batch)
{
Drawing.DrawSquare(batch, Position, new Vector2(Size, Size), Angle, Color);
}
protected override Vector2[] GetHitbox()
{
float half = Size / 2;
return new Vector2[]
{
new Vector2(half, half),
new Vector2(half, -half),
new Vector2(-half, -half),
new Vector2(-half, half),
};
}
public override void OnDestroy()
{
float subsize = Size / 2;
if (subsize > MinimumSize)
{
Vector2 ecc = Fmath.Rotate(new Vector2(Size/4, Size/4), Angle);
// Hack to pull the pending forces out of the collision system and applying them immediately.
Velocity += (CollisionBody.Force / 60f) * CollisionBody.InvMass;
for (int i = 0; i < 4; i++)
{
ecc = Fmath.RotatePos(ecc);
Asteroid subasteroid = new Asteroid(
Position + ecc,
Velocity + ecc * EjectionVelocity / Size,
subsize,
Angle,
AngularVelocity + EjectionRotation - Fmath.RandF(2 * EjectionRotation)
);
Context.AddEntity(subasteroid);
}
}
else
{
Context.AddEvent(new Explosion(Position, Size * 1.5f, 1f, Color.White));
}
base.OnDestroy();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ERP_Palmeiras_LA.Models;
using ERP_Palmeiras_LA.Models.Facade;
namespace ERP_Palmeiras_LA.Controllers
{
public class MateriaisController : Controller
{
//
// GET: /Materiais/
LogisticaAbastecimento facade = LogisticaAbastecimento.GetInstance();
public ActionResult Index()
{
IEnumerable<Material> materiais = facade.BuscarMateriais();
IEnumerable<Fabricante> fabricantes = facade.BuscarFabricantes();
ViewBag.materiais = materiais;
ViewBag.fabricantes = fabricantes;
return View();
}
public ActionResult Criar()
{
IEnumerable<Fabricante> fabricantes = facade.BuscarFabricantes();
ViewBag.fabricantes = fabricantes;
return View();
}
[HttpPost]
public ActionResult Cadastrar(String codigo, String nome, Int32 fabricante, String descricao)
{
if (!String.IsNullOrEmpty(codigo))
{
Material material = new Material();
material.Codigo = codigo;
material.Nome = nome;
material.FabricanteId = fabricante;
material.Descricao = descricao;
facade.InserirMaterial(material);
return RedirectToAction("Index");
}
IEnumerable<Fabricante> fabricantes = facade.BuscarFabricantes();
ViewBag.fabricantes = fabricantes;
return RedirectToAction("Criar");
}
public ActionResult Editar(Int32 materialID)
{
IEnumerable<Fabricante> fabricantes = facade.BuscarFabricantes();
Material mat = facade.BuscarMaterial(materialID);
ViewBag.fabricantes = fabricantes;
ViewBag.mat = mat;
return View();
}
[HttpPost]
public ActionResult Alterar(Int32 materialID, String codigo, String nome, String descricao, Int32 fabricante)
{
Material mat = facade.BuscarMaterial(materialID);
mat.Codigo = codigo;
mat.Nome = nome;
mat.Descricao = descricao;
mat.FabricanteId = fabricante;
facade.AlterarMaterial(mat);
return RedirectToAction("Index");
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using BomTreeView.Importer.Bom;
using System.Collections.Generic;
using BomTreeView.Importer.Combiner;
using BomTreeView.Importer.Part;
using BomTreeView.Database;
using BomTreeView;
namespace BomTreeViewTest
{
[TestClass]
public class BomDbEntryListTest
{
[TestMethod]
public void ConvertingImportedBomDbEntryListToBomDisplayEntryListShouldReturnBomDisplayEntryListWithOneTopLevelEntry()
{
BomImporter bomImporter = new BomImporter();
PartImporter partImporter = new PartImporter();
BomImportResult bomImportResult
= bomImporter.ImportBomFile();
PartImportResult partImportResult
= partImporter.ImportPartFile();
BomAndPartCombiner bomAndPartCombiner = new BomAndPartCombiner(
bomImportResult,
partImportResult
);
BomDbEntries bomDbEntryList
= bomAndPartCombiner.CombineBomAndPartImportResults();
BomDisplayEntries bomDisplayEntryList
= bomDbEntryList.ToBomDisplayEntryList();
List<BomDisplayEntry> topLevelEntries
= bomDisplayEntryList.BomEntryList;
Assert.AreEqual(1, topLevelEntries.Count);
}
[TestMethod]
public void ConvertingImportedBomDbEntryListToBomDisplayEntryListShouldReturnBomDisplayEntryListWithCorrectEntryCount()
{
BomImporter bomImporter = new BomImporter();
PartImporter partImporter = new PartImporter();
BomImportResult bomImportResult
= bomImporter.ImportBomFile();
PartImportResult partImportResult
= partImporter.ImportPartFile();
BomAndPartCombiner bomAndPartCombiner = new BomAndPartCombiner(
bomImportResult,
partImportResult
);
BomDbEntries bomDbEntryList
= bomAndPartCombiner.CombineBomAndPartImportResults();
BomDisplayEntries bomDisplayEntryList
= bomDbEntryList.ToBomDisplayEntryList();
List<BomDisplayEntry> allEntries
= bomDisplayEntryList.GetFlattenedBomEntryList();
Assert.AreEqual(196, allEntries.Count);
}
}
}
|
using System;
namespace _1047
{
class Program
{
static void Main(string[] args)
{
string n = Console.ReadLine();
string[] values = n.Split(' ');
int ht, mt, somaMin,
hi = int.Parse(values[0]),
mi = int.Parse(values[1]),
hf = int.Parse(values[2]),
mf = int.Parse(values[3]);
somaMin = ((hf * 60) + mf) - ((hi * 60) + mi);
if (somaMin <= 0)
{
somaMin += 24 * 60;
}
ht = somaMin / 60;
mt = somaMin % 60;
Console.WriteLine($"O JOGO DUROU {ht} HORA(S) E {mt} MINUTO(S)");
}
}
}
|
using EmployeeStorage.DataAccess.Configuration;
using EmployeeStorage.DataAccess.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection.Metadata.Ecma335;
namespace EmployeeStorage.DataAccess.Repositories
{
public abstract class Repository<TEntity> where TEntity : class, new()
{
private readonly EmployeeStorageContext context;
private readonly DbSet<TEntity> dbSet;
protected Repository(EmployeeStorageContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
protected DbSet<Employee> Employees => context.Employees;
public virtual void Create(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Update(TEntity entity)
{
dbSet.Attach(entity);
context.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(TEntity entity)
{
dbSet.Remove(entity);
}
public virtual TEntity GetById(int id)
{
return dbSet.Find(id);
}
public virtual IEnumerable<TEntity> GetAll()
{
return dbSet.ToList();
}
public virtual IEnumerable<TEntity> GetMany(Expression<Func<TEntity, bool>> where)
{
return dbSet.Where(where).ToList();
}
}
} |
// ------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Microsoft.PSharp.TestingServices.Scheduling
{
/// <summary>
/// Contains information about an asynchronous operation that can be scheduled.
/// </summary>
internal sealed class AsyncOperation : IAsyncOperation
{
/// <summary>
/// Unique id of the source of this operation.
/// </summary>
public ulong SourceId { get; private set; }
/// <summary>
/// Unique name of the source of this operation.
/// </summary>
public string SourceName { get; private set; }
/// <summary>
/// The task that performs this operation.
/// </summary>
internal Task Task;
/// <summary>
/// The type of the operation.
/// </summary>
public AsyncOperationType Type { get; private set; }
/// <summary>
/// The target of the operation.
/// </summary>
public AsyncOperationTarget Target { get; private set; }
/// <summary>
/// Unique id of the target of the operation.
/// </summary>
public ulong TargetId { get; private set; }
/// <summary>
/// Set of operations that must complete before this operation can resume.
/// </summary>
private readonly HashSet<IAsyncOperation> Dependencies;
/// <summary>
/// True if the task that performs this operation is enabled, else false.
/// </summary>
public bool IsEnabled { get; set; }
/// <summary>
/// Is the source of the operation active.
/// </summary>
internal bool IsActive;
/// <summary>
/// Is the source of the operation waiting to receive an event.
/// </summary>
internal bool IsWaitingToReceive;
/// <summary>
/// Is the inbox handler of the source of the operation running.
/// </summary>
internal bool IsInboxHandlerRunning;
/// <summary>
/// True if it should skip the next receive scheduling point,
/// because it was already called in the end of the previous
/// event handler.
/// </summary>
internal bool SkipNextReceiveSchedulingPoint;
/// <summary>
/// If the next operation is <see cref="AsyncOperationType.Receive"/>, then this value
/// gives the step index of the corresponding <see cref="AsyncOperationType.Send"/>.
/// </summary>
public ulong MatchingSendIndex { get; internal set; }
/// <summary>
/// Initializes a new instance of the <see cref="AsyncOperation"/> class.
/// </summary>
internal AsyncOperation(MachineId id)
{
this.SourceId = id.Value;
this.SourceName = id.Name;
this.Type = AsyncOperationType.Start;
this.Target = AsyncOperationTarget.Task;
this.TargetId = id.Value;
this.Dependencies = new HashSet<IAsyncOperation>();
this.IsEnabled = false;
this.IsActive = false;
this.IsWaitingToReceive = false;
this.IsInboxHandlerRunning = false;
this.SkipNextReceiveSchedulingPoint = false;
}
/// <summary>
/// Sets the next operation to schedule.
/// </summary>
internal void SetNextOperation(AsyncOperationType operationType, AsyncOperationTarget target, ulong targetId)
{
this.Type = operationType;
this.Target = target;
this.TargetId = targetId;
}
/// <summary>
/// Notify that the operation has been created and will run on the specified task.
/// </summary>
/// <param name="task">The task that performs this operation.</param>
/// <param name="sendIndex">The index of the send that caused the event handler to be restarted, or 0 if this does not apply.</param>
internal void NotifyCreated(Task task, int sendIndex)
{
this.Task = task;
this.IsEnabled = true;
this.IsActive = false;
this.IsWaitingToReceive = false;
this.IsInboxHandlerRunning = false;
this.MatchingSendIndex = (ulong)sendIndex;
}
/// <summary>
/// Notify that the operation has completed.
/// </summary>
internal void NotifyCompleted()
{
this.IsEnabled = false;
this.IsInboxHandlerRunning = false;
this.SkipNextReceiveSchedulingPoint = true;
this.MatchingSendIndex = 0;
}
}
}
|
//
// 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.Linq;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Profile;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Exceptions;
#endregion
namespace DotNetNuke.Modules.Admin.Users
{
public partial class ViewProfile : UserModuleBase
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
UserId = Null.NullInteger;
if (Context.Request.QueryString["userticket"] != null)
{
UserId = Int32.Parse(UrlUtils.DecryptParameter(Context.Request.QueryString["userticket"]));
}
ctlProfile.ID = "Profile";
ctlProfile.UserId = UserId;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
try
{
if (ctlProfile.UserProfile == null)
{
lblNoProperties.Visible = true;
return;
}
ctlProfile.DataBind();
if (ctlProfile.UserProfile.ProfileProperties.Cast<ProfilePropertyDefinition>().Count(profProperty => profProperty.Visible) == 0)
{
lblNoProperties.Visible = true;
}
}
catch (Exception exc)
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Dragon_HP_Body : MonoBehaviour
{
Slider dragon_HP_slider;
Image sliderImage;
//オブジェクト参照
public GameObject Slider; //胸についてるスライダー
private GameObject Parent; //Animatorが入ってる本体
//private GameObject HPbarPrefab;
// Start is called before the first frame update
void Start()
{
dragon_HP_slider = Slider.GetComponent<Slider>();
//親オブジェクトの取得
Parent = transform.root.gameObject;
//スライダーの最大値を設定
dragon_HP_slider.maxValue = Parent.gameObject.GetComponent<Dragon>().dragonHP;
//HPbarPrefab = GameObject.Find("Lift/Canvas/HPbar");
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.B))
{
Parent.gameObject.GetComponent<Dragon>().dragonHP -= 5;
dragon_HP_slider.value = Parent.gameObject.GetComponent<Dragon>().dragonHP;
}
//体力が0になったら本体のDie関数を呼ぶ
if (Parent.gameObject.GetComponent<Dragon>().dragonHP <= 0)
{
//HPbarPrefab.gameObject.GetComponent<HPbar>().Set_WinPanel();
Parent.gameObject.GetComponent<Dragon>().Die();
Parent.gameObject.GetComponent<Dragon>().enabled = false;
}
}
private void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Sword")
{
//ダメージ処理
float damagePoint = Sword_Player.Get_SwordPower();
Parent.gameObject.GetComponent<Dragon>().dragonHP -= damagePoint;
dragon_HP_slider.value = Parent.gameObject.GetComponent<Dragon>().dragonHP;
if (Parent.gameObject.GetComponent<Dragon>().magicAttack_flg == true)
{
Parent.gameObject.GetComponent<Dragon>().magicAttackCancel -= damagePoint;
if (Parent.gameObject.GetComponent<Dragon>().magicAttackCancel <= 0)
{
//キャンセルダメージを受けたアニメーションを再生
Parent.gameObject.GetComponent<Dragon>().CancelTakeDamage();
}
}
else
{
//ダメージを受けたアニメーションを再生
Parent.gameObject.GetComponent<Dragon>().TakeDamage();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
using System.Collections;
using System.Text;
using System.IO;
namespace SKT.MES.Web.Help
{
public partial class ImportHelp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 上传Excel,并生成html文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
#region 上传文件
HttpPostedFile fileObj = this.flupload.PostedFile;
if (fileObj.FileName == "")
{
this.lblMessage.Text = "请选择Excel文件上传!";
return;
}
if (fileObj.ContentLength <= 0)
{
this.lblMessage.Text = "所选文件是空文件!";
return;
}
string allowExt = ".xls|.xlsx";
string fileExt = fileObj.FileName.Substring(fileObj.FileName.LastIndexOf("."));
if (allowExt.IndexOf(fileExt) < 0)
{
this.lblMessage.Text = "文件格式不正确!";
return;
}
string oldFileName = fileObj.FileName.ToString();
string newFileName = DateTime.Now.Ticks.ToString() + fileExt;
string savePath = Server.MapPath("~/Help/Excel/");
string dataSource = savePath + newFileName;
this.flupload.PostedFile.SaveAs(dataSource);
#endregion
#region 读取并操作Excel
//创建OLEDB连接字符串
string oleStrConn = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + dataSource + ";Extended Properties='Excel 8.0;HDR=NO;'";
OleDbConnection oleConn = null;
try
{
//创建连接
oleConn = new OleDbConnection(oleStrConn);
//打开数据库连接
oleConn.Open();
//获取所有Sheet
DataTable dt = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string s = "";
DataSet ds = null;
//循环读取所有表单的内容
foreach (DataRow row in dt.Rows)
{
string sheetName = row["TABLE_NAME"].ToString();
ds = ExcelSheetToDataSet(sheetName, oleStrConn);
DataTable _dt = ds.Tables[0];
int flag = -1;
bool isField = true;
//html 文件的基本参数
string _html_filename = sheetName.Replace("$", "") + ".htm";
string _html_datafield_row = "";
string _html_fun_desc = "";
string _html_fun_detail = "";
string _html_fun_img = "";
//循环读取每个表单内容,从第四行开始
for (int i = 4; i < _dt.Rows.Count; i++)
{
if (_dt.Rows[i][0].ToString() != "" && _dt.Rows[i][0].ToString() != "功能描述")
{
//读取字段
if (isField)
{
_html_datafield_row += String.Format("<tr><td>{0}</td><td>{1}</td></tr>", _dt.Rows[i][0], _dt.Rows[i][1].ToString().Replace("\n","<br/>"));
}
}
else if (_dt.Rows[i][0].ToString() == "功能描述")
{
flag = i;
isField = false;
}
if (i > flag && i == flag + 1 && i > 4 && flag != -1)
{
_html_fun_desc = _dt.Rows[i][0].ToString();
}
if (i > 4 && i > flag + 2 && flag != -1)
{
_html_fun_img = _dt.Rows[i][5].ToString();
string[] arr;
arr = _html_fun_img.Split(';');
string imgList = "";
foreach (string img in arr)
{
imgList += "<div><img src='images/" + img.Replace("//", "/") + "' alt=''/></div>";
}
_html_fun_detail += "<div>";
_html_fun_detail += "<div class='list-title'>" + _dt.Rows[i][0].ToString() + "</div>";
_html_fun_detail += "<div class='clear10'></div>";
_html_fun_detail += "<div class='list-detail'>" + _dt.Rows[i][1].ToString().Replace("\n", "<br/>") + "</div>";
_html_fun_detail += "<div class='clear10'></div>";
_html_fun_detail += "<div class='list-img'>";
_html_fun_detail += imgList;
_html_fun_detail += "</div>";
_html_fun_detail += "</div>";
_html_fun_detail += "<div class='clear10'></div>";
}
}
//生成html文件
s = GenerateHtml(sheetName.Replace("$", ""), "", _html_datafield_row, "", _html_fun_desc, _html_fun_detail, _html_filename);
}
this.lblMessage.Text = s;
//关闭OLEDB连接
oleConn.Close();
if (s == "")
{
Response.Redirect("~/Help/Help.htm");
}
}
catch (Exception ex)
{
this.lblMessage.Text = ex.Message.ToString();
}
#endregion
}
/// <summary>
/// 查询Excel数据到DataSet
/// </summary>
/// <param name="sheetName"></param>
/// <param name="strConn"></param>
/// <returns></returns>
private DataSet ExcelSheetToDataSet(string sheetName, string strConn)
{
DataSet ds = null;
OleDbDataAdapter ada = null;
string cmdText = "";
cmdText = "SELECT * FROM [" + sheetName + "]";
ada = new OleDbDataAdapter(cmdText, strConn);
ds = new DataSet();
ada.Fill(ds, sheetName);
return ds;
}
/// <summary>
/// 生成HTML文件
/// </summary>
/// <param name="HTMLPageTitle">页面名字,从资源文件中取得</param>
/// <param name="HTMLFieldDescTitle">"字段描述"</param>
/// <param name="HTMLFieldTableRows">字段</param>
/// <param name="HTMLFunTitle">"功能描述"</param>
/// <param name="HTMLFunDesc">功能简介</param>
/// <param name="HTMLFunDetailList">详细功能描述</param>
private string GenerateHtml(string HTMLPageTitle, string HTMLFieldDescTitle, string HTMLFieldTableRows, string HTMLFunTitle, string HTMLFunDesc, string HTMLFunDetailList, string HTMLFileName)
{
HTMLFieldDescTitle = "字段描述";
HTMLFunTitle = "功能描述";
#region 读取模板内容
StringBuilder templateContent = new StringBuilder();
//模板页面路径
string templatePath = Server.MapPath("~/Help/Template/Template.htm");
if (!File.Exists(templatePath))
{
return "模板文件丢失或不存在!";
}
try
{
using (StreamReader sr = new StreamReader(templatePath))
{
string line = "";
while ((line = sr.ReadLine()) != null)
{
templateContent.Append(line);
}
sr.Close();
}
}
catch (Exception ex)
{
return ex.Message.ToString();
}
#endregion
#region 替换模板标签
templateContent.Replace("{Title}", (String)this.GetGlobalResourceObject("Pages", HTMLPageTitle));
templateContent.Replace("{HTMLPageTitle}", (String)this.GetGlobalResourceObject("Pages", HTMLPageTitle));
templateContent.Replace("{HTMLFieldDescTitle}", HTMLFieldDescTitle);
templateContent.Replace("{HTMLDataFieldName}", "字段名");
templateContent.Replace("{HTMLDataFieldDesc}", "描述");
templateContent.Replace("{HTMLFieldTableRows}", HTMLFieldTableRows);
templateContent.Replace("{HTMLFunTitle}", HTMLFunTitle);
templateContent.Replace("{HTMLFunDesc}", HTMLFunDesc);
templateContent.Replace("{HTMLFunDetailList}", HTMLFunDetailList);
#endregion
string genHtmlPath = Server.MapPath("~/Help/Documents/");
#region 生成HTML文件
try
{
using (StreamWriter sw = new StreamWriter(genHtmlPath + HTMLFileName, false, System.Text.Encoding.GetEncoding("GB2312")))
{
sw.WriteLine(templateContent);
sw.Flush();
sw.Close();
}
}
catch (Exception ex)
{
return ex.Message.ToString();
}
#endregion
return "";
}
}
} |
using System.Collections.Generic;
using UnityEngine;
using static EventManager;
/// <summary>
/// Abstract class responsible of the Checking Phase
/// </summary>
/// <remarks>
/// The class contains the methods guaranteeing the flow of the activity (start and end of checking phase)
/// and the abstract method to be overrided in order to implement a specific checking phases
/// </remarks>
public abstract class CheckingPhaseManager : MonoBehaviour {
/// <summary>
/// Contains the scene objects (the dynamic objects loaded from JSON)
/// </summary>
protected List<string> SceneObjects;
protected AbstractSceneManager sceneManager;
/// <summary>
/// Configure the class setting the references with the AbstractSceneManager
/// from both sides.
/// </summary>
public void Setup() {
sceneManager = GetComponent<AbstractSceneManager>();
sceneManager.CheckingPhaseManager = this;
SceneObjects = sceneManager.GetObjects();
}
/// <summary>
/// Trigger the checking phase start.
/// </summary>
public void StartCheckingPhase() {
CheckingPhase();
}
/// <summary>
/// Stop listening to events and triggers the new phase
/// </summary>
protected void End() {
StopListening(Triggers.CheckingPhaseStart, StartCheckingPhase);
TriggerEvent(Triggers.CheckingPhaseEnd);
Destroy(GameObject.Find("SceneSelected"));
Destroy(GameObject.Find("SpatialMapping"));
Destroy(GameObject.Find("SpatialProcessing"));
}
// ------------------------------------ ABSTRACT ----------------------------------
/// <summary>
/// Override to implement the checking phase
/// </summary>
protected abstract void CheckingPhase();
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Runtime.Remoting.Messaging;
namespace sayHi.Model
{
public class GetDBContext
{
public static sayHiEntities CreateDbContext()
{
//强转
sayHiEntities dbContext = (sayHiEntities)CallContext.GetData("dbContext");
//如果对象是空的
if (dbContext == null)
{
//则new一个
dbContext = new sayHiEntities();
//存储
CallContext.SetData("dbContext", dbContext);
}
//没有为空则直接返回
return dbContext;
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ConfirmCharacterSelect : MonoBehaviour {
private GameObject[] players;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public bool AllPlayersReady(){
players = GameObject.FindGameObjectsWithTag("Player");
//If no active player, return false
if(players.Length == 0) return false;
//Determine if active players are ready
bool ready = true;
foreach(GameObject player in players){
if(!player.GetComponent<CharacterSelectController>().IsReady()){
ready = false;
}
}
return ready;
}
public List<int> GetActivePlayers(){
players = GameObject.FindGameObjectsWithTag("Player");
List<int> playerNumbers = new List<int>();
//If no active player, return empty
if(players.Length == 0) return playerNumbers;
//Determine if active players are ready
foreach(GameObject player in players){
playerNumbers.Add(player.GetComponent<CharacterSelectController>().playerNumber);
}
return playerNumbers;
}
public bool NoActivePlayers(){
players = GameObject.FindGameObjectsWithTag("Player");
return players.Length == 0;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Infnet.EngSoft.SistemaBancario.Modelo
{
public class Fisica : Cliente
{
public decimal Renda { set; get; }
public int CPF { get; set; }
}
}
|
namespace HacktoberfestProject.Web.Data.Configuration
{
public class TableConfiguration
{
public string ConnectionString { get; set; }
public string TableName { get; set; }
}
}
|
using DiegoG.Utilities.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Threading.Tasks;
namespace D_API.Exceptions
{
public static class Report
{
public class ExceptionReport
{
public string? Message { get; init; }
public string? StackTrace { get; init; }
public string Type { get; init; }
public System.Collections.IDictionary Data { get; init; }
public Exception Exception { get; init; }
public ExceptionReport(Exception exception)
{
Exception = exception;
Message = exception.Message;
StackTrace = exception.StackTrace;
Type = exception.GetType().Name;
Data = exception.Data;
}
public static implicit operator ExceptionReport(Exception exc) => new(exc);
}
public record ReportData(DateTime CreatedAt, ExceptionReport Exception, object? Data = null, params KeyValuePair<string, object>[] OtherData)
{
public string StackTrace { get; } = Environment.StackTrace;
}
public record ControllerReportData : ReportData
{
public ControllerReportData
(DateTime createdAt, Exception exception, ControllerBase controller, object? data = null, params KeyValuePair<string, object>[] otherData)
: base(
createdAt,
exception,
new
{
Controller = new
{
Request = new
{
controller.Request.Protocol,
controller.Request.Headers,
controller.Request.Scheme,
controller.Request.Host,
controller.Request.Path,
controller.Request.Method,
controller.Request.ContentLength,
controller.Request.QueryString
},
controller.User,
controller.RouteData,
controller.ModelState
},
Data = data
},
otherData)
{ }
}
/// <summary>
/// Writes the report and returns the reported Exception for throwing
/// </summary>
/// <param name="report"></param>
/// <param name="category"></param>
/// <param name="subcategory"></param>
/// <param name="caller"></param>
/// <returns></returns>
public static async Task<Exception> WriteReport(ReportData report, string category, string? subcategory = null, [CallerMemberName]string? caller = null)
{
Log.Error($"An error ocurred in {caller}; {category}{(subcategory is not null ? $", {subcategory}" : "")}");
await WriteToFile(report, category, subcategory, caller);
return report.Exception.Exception;
}
public static Task<Exception> WriteControllerReport
(ControllerReportData report, string category, string? subcategory = null, [CallerMemberName] string? caller = null)
=> WriteReport(report, category, subcategory, caller);
private static async Task WriteToFile(ReportData report, string category, string? subcategory = null, string? caller = null)
{
string dir = Directories.InLogs("Reports", category, subcategory ?? "");
Directory.CreateDirectory(dir);
await Serialization.Serialize.JsonAsync(report, dir, $"{caller ?? "Unknown"}@{DateTime.UtcNow:yyyy MMMM dd(ddd) hh(HH).mm.ss tt}");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LCode.Models
{
public class Livros
{
public int Livros_id { get; set; }
public string Livros_nome { get; set; }
public string Livros_descricao { get; set; }
public string Livros_link { get; set; }
public int Livros_status { get; set; }
public int Livros_curso { get; set; }
}
} |
namespace UsingSqlCompactEditionDataBase
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
class User
{
public int UserId { get; set; }
public string UserName { get; set; }
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.