text stringlengths 13 6.01M |
|---|
using HV_tech.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using static HV_tech.Model.Enums;
namespace HV_tech.Domain
{
public class Order
{
#region Properties
private string _initialOrder;
private List<Dish> _items;
private string _message;
#endregion
#region Constructor
public Order(string value)
{
_initialOrder = value;
_message = string.Empty;
}
#endregion
#region Public Methods
public string GetOrderText()
{
return _message;
}
public void CreateOrder()
{
try
{
var order = _initialOrder.Split(',');
if (isValidInput(order))
{
DishType dishType = GetDishType(order[0]);
var orderListed = BuildOrder(order);
_items = GetDishListByOrder(orderListed, dishType);
CheckRepeatedValues();
}
}
catch (Exception ex)
{
_message += "error";
}
}
#endregion
#region Private Methods
private static DishType GetDishType(string order)
{
return (DishType)Enum.Parse(typeof(DishType), order, true);
}
private List<Dish> GetDishListByOrder(List<int> lstOrder, DishType type)
{
var result = new List<Dish>();
var lstDish = Dish.GetDisherByType(type);
lstOrder.ForEach(x => result.Add(lstDish.SingleOrDefault(d => d.Id == x)));
return result;
}
private string GetDishTextByList(List<int> lstOrder, DishType type)
{
var dishesList = Dish.GetDisherByType(type);
var namesList = new List<string>();
foreach (var item in lstOrder)
{
if (dishesList.SingleOrDefault(x => x.Id == item) != null)
namesList.Add(dishesList.SingleOrDefault(x => x.Id == item).Name);
else
namesList.Add("error");
}
return String.Join(",", namesList);
}
private List<int> BuildOrder(string[] order)
{
var lstItens = new List<int>();
for (int i = 1; i < order.Length; i++)
{
if (int.TryParse(order[i], out int id))
lstItens.Add(id);
}
lstItens.Sort();
return lstItens;
}
private bool isValidInput(string[] order)
{
if (order.Length < 2)
{
_message = "Invalid input. Please, redo your order.";
return false;
}
return Enum.IsDefined(typeof(DishType), order[0]);
}
private void CheckRepeatedValues()
{
var dishesCount = new Dictionary<Dish, int>();
foreach (var item in _items)
{
if (item == null)
{
dishesCount.Add(new Dish(), 0);
break;
}
if (dishesCount.ContainsKey(item))
dishesCount[item]++;
else
dishesCount.Add(item, 1);
}
var aux = new List<string>();
foreach (var item in dishesCount)
{
if (item.Value == 0)
{
aux.Add("error");
break;
}
if (item.Value > 1)
{
if (item.Key.IsAbleMultipleTimes)
aux.Add(item.Key.Name + "(x" + item.Value + ")");
else
{
aux.Add(item.Key.Name);
aux.Add("error");
break;
}
}
else
aux.Add(item.Key.Name);
}
_message = String.Join(", ", aux);
}
#endregion
}
}
|
using System;//Biblioteca por defeito
using System.Windows.Forms;//Biblioteca por defeito
using System.Net;//Biblioteca para efectuar o login
using System.Net.Mail;
using System.IO;
using System.Net.NetworkInformation;
namespace Login
{
public partial class frmemail : Form
{
SmtpClient Client;//Cliente smtp
MailMessage Msg;//Mensagem do E-mail
Attachment Anexo;//Ficheiro anexado
frmError fe = new frmError();
public static string de;
public static string para;
public static string titulo;
public static string conteudo;
public static string file_caminho;
public frmemail()//Construção do Form
{
InitializeComponent();
}
public void btnEnviar_Click(object sender, EventArgs e)//Método para o botão 'Enviar'
{
if (txtMail.Text == string.Empty || txtTitulo.Text == string.Empty || rtbTexto.Text == string.Empty)
MessageBox.Show("Existem campos para preencher!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Stop);
else
{
de = txtUser.Text;
para = txtMail.Text;
titulo = txtTitulo.Text;
conteudo = rtbTexto.Text;
file_caminho = path_fileLbl.Text;
fe.Show();
this.Enabled = false;
timer_espera.Start();
}
}
private void Enviar()
{
try
{
Client = new SmtpClient("smtp.gmail.com", 587);//Declaração de um cliente SMTP (Simple Mail Transfer Protocol
Msg = new MailMessage("gropuchat467@gmail.com", frmemail.para, frmemail.titulo, "====Chat em grupo====\r\nDe: " + frmemail.de + "\r\n\r\n" + frmemail.conteudo);//Declaração de uma variavel para a mensagem
if (frmemail.file_caminho != "...")//Se o caminho do ficheiro anexado for diferente de "..." então
{
MessageBox.Show("O envio pode demorar devido ao ficheiro anexado.\nPor favor aguarde...", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);//Aviso
Anexo = new Attachment(frmemail.file_caminho);//Vai buscar o ficheiro pelo caminho indicado na path_filelbl
Msg.Attachments.Add(Anexo);//Coloca o ficheiro dentro do attachment
}
Client.Credentials = new NetworkCredential("groupchat467@gmail.com", "HristiyanStefanov");//Efectua a autenticação com o nome de utilizador e password indicados nas textbox
Client.EnableSsl = true;//SSL (Secure Sockts Layer) passa para activo
Client.Send(Msg);//Coloca o conteúdo da mensagem para o cliente, ou seja, faz o envio deste
Msg.Dispose();//Limpa restos da memória que podem ter ficado durante o envio
fe.Hide();
string prompt = string.Format("e-mail enviado com sucesso para '{0}'", frmemail.para);//Declaração de uma String com um aviso
MessageBox.Show(prompt, "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);//Visualização de um aviso
txtMail.Clear();
txtTitulo.Clear();
txtUser.Clear();
rtbTexto.Clear();
path_fileLbl.Text = "...";
this.Enabled = true;
this.Close();
}
catch //Se algo correr mal então
{
MessageBox.Show("Ocorreu um erro por favor verifique a sua\nligação a internet e os dados inseridos!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Stop);
fe.Hide();
this.Enabled = true;
}
}
private void frmemail_Load(object sender, EventArgs e)
{
txtUser.Text = FrmLogin.UserName;
txtMail.Focus();
Ping ping = new Ping();//variavel do tipo ping
try//tenta
{
PingReply reply;//variavel de resposta
reply = ping.Send("www.gmail.com");//faz ping no chatgroup...
if (reply.Status == IPStatus.TimedOut)//se exceder o tempo limite de espera então
{
MessageBox.Show("Erro ao ligar ao servidor de e-mail predefinido!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
}
catch//se ocorrer um erro então
{
MessageBox.Show("Erro ao ligar ao servidor de e-mail predefinido!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
}
private void linkAnexar_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e)
{
OpenFileDialog open = new OpenFileDialog();//Declaração de uma variavel para a janela de pesquisa do ficheiro
if (open.ShowDialog() == DialogResult.OK)//Se o resultado da pesquisa for OK então
{
path_fileLbl.Text = open.FileName;//Insere o caminho no Path_FileLbl
}
}
private void timer_numerCaracter_Tick(object sender, EventArgs e)//MEtodo para fazer o calculo de quantos caracteres disponiveis o utilizador possui
{
lblNumerLines.Text = rtbTexto.Text.Length.ToString();
int a;
string b;
a = rtbTexto.MaxLength - Convert.ToInt32(lblNumerLines.Text);//Numero maximo de caracteres - numero de caracteres utiliazdos
b = Convert.ToString(a);
lblNumerLines.Text = b;
}
public void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();//Mostra o local onde o utilizador pertende guardar a conversa
saveDlg.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";//Extensão do ficheiro a guardar
saveDlg.CheckPathExists = true;//Caso o caminho não seja correcto avisa o utilizador
saveDlg.OverwritePrompt = true;//Se existir um ficheiro com o mesmo nome avisa o utilizador
saveDlg.FileName = "E-Mail [ "+FrmLogin.UserName+" ]";//O nome do ficheiro vai ser igual ao nome da janela do Cliente
if (saveDlg.ShowDialog() == DialogResult.OK)//Se o resutado for OK então
{
StreamWriter sw = new StreamWriter(saveDlg.FileName);
if (path_fileLbl.Text=="...")
sw.Write("De: " + txtUser.Text + "\r\nPara: " + txtMail.Text + "\r\nTitulo: " + txtTitulo.Text+"\r\n\r\n"+rtbTexto.Text);
else
sw.Write("De: " + txtUser.Text + "\r\nPara: " + txtMail.Text + "\r\nTitulo: " + txtTitulo.Text +"\r\nAnexo: "+path_fileLbl.Text +"\r\n\r\n" + rtbTexto.Text);
sw.Flush();
sw.Close();
MessageBox.Show("E-mail guardado com sucesso!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);//Aviso
}
}
private void rtbTexto_KeyPress(object sender, KeyPressEventArgs e)
{
timer_numerCaracter.Start();
}
private void timer_espera_Tick(object sender, EventArgs e)
{
timer_espera.Stop();
Enviar();
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
namespace SPA.Models
{
public static class EnqueteDAO
{
public static Enquete GetEnquete(string id)
{
Enquete enquete = new Enquete();
try
{
using (SqlConnection conn = new SqlConnection(Variables.connectionSql))
{
//retrieve the SQL Server instance version
string query = @"SELECT * FROM Enquete WHERE Id = @Id";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Id", id);
//open connection
conn.Open();
//execute the SQLCommand
SqlDataReader dr = cmd.ExecuteReader();
//check if there are records
if (dr.HasRows)
{
while (dr.Read())
{
//display retrieved record (first column only/string value)
enquete.Id = dr.GetString(0);
enquete.Titulaire_enquete = Personne.GetPersonneById(dr.GetInt32(1));
enquete.Delegue_enqueteur = Personne.GetPersonneById(dr.GetInt32(2));
enquete.Infracteur = Personne.GetPersonneById(dr.GetInt32(3));
enquete.Plaignant = Personne.GetPersonneById(dr.GetInt32(4));
enquete.Avis = dr.GetString(5);
enquete.Etat = dr.GetInt32(6);
enquete.OuvertParLeSiege = IntToBool(dr.GetInt32(7));
enquete.Motif = dr.GetString(8);
enquete.Animaux = Animaux_enquete.GetAnimaux_EnquetesBdd(enquete.Id);
enquete.Document = Document.GetListDocument(enquete.Id);
enquete.Commentaire = Commentaire.GetListCommentaire(enquete.Id);
enquete.Visite_enquete = Visite_enquete.GetVisiteEnquete(enquete.Id);
enquete.Appel = Appel.GetListAppel(enquete.Id);
}
}
else
{
Console.WriteLine("No data found.");
}
dr.Close();
}
return enquete;
}
catch (Exception ex)
{
throw;
}
}
public static List<Enquete> GetAllEnquete()
{
List<Enquete> listEnquetes = new List<Enquete>();
try
{
using (SqlConnection conn = new SqlConnection(Variables.connectionSql))
{
string query = @"SELECT * FROM Enquete";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Enquete enquete = new Enquete();
//display retrieved record (first column only/string value)
enquete.Id = dr.GetString(0);
enquete.Titulaire_enquete = Personne.GetPersonneById(dr.GetInt32(1));
enquete.Delegue_enqueteur = Personne.GetPersonneById(dr.GetInt32(2));
enquete.Infracteur = Personne.GetPersonneById(dr.GetInt32(3));
enquete.Plaignant = Personne.GetPersonneById(dr.GetInt32(4));
enquete.Avis = dr.GetString(5);
enquete.Etat = dr.GetInt32(6);
enquete.OuvertParLeSiege = IntToBool(dr.GetInt32(7));
enquete.Motif = dr.GetString(8);
enquete.Animaux = Animaux_enquete.GetAnimaux_EnquetesBdd(enquete.Id);
enquete.Document = Document.GetListDocument(enquete.Id);
enquete.Commentaire = Commentaire.GetListCommentaire(enquete.Id);
enquete.Visite_enquete = Visite_enquete.GetVisiteEnquete(enquete.Id);
enquete.Appel = Appel.GetListAppel(enquete.Id);
listEnquetes.Add(enquete);
}
}
else
{
Console.WriteLine("No data found.");
}
dr.Close();
}
return listEnquetes;
}
catch (Exception ex)
{
throw;
}
}
public static bool AddEnquete(Enquete enquete)
{
bool res = false;
try
{
using (SqlConnection conn = new SqlConnection(Variables.connectionSql))
{
//retrieve the SQL Server instance version
string query = @"INSERT INTO Enquete (Id, Titulaire_enquete, Delegue_enqueteur, Infracteur, Plaignant, Etat, Avis, OuvertParLeSiege, Motif) VALUES (@Id, @Titulaire_enquete, @Delegue_enquete, @Infracteur, @Plaignant, 0, '', @Siege, @Motif);";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Id", enquete.Id);
cmd.Parameters.AddWithValue("@Titulaire_enquete", enquete.Titulaire_enquete.Id);
cmd.Parameters.AddWithValue("@Delegue_enquete", enquete.Delegue_enqueteur.Id);
cmd.Parameters.AddWithValue("@Infracteur", enquete.Infracteur.Id);
cmd.Parameters.AddWithValue("@Plaignant", enquete.Plaignant.Id);
cmd.Parameters.AddWithValue("@Siege", BoolToInt(enquete.OuvertParLeSiege));
cmd.Parameters.AddWithValue("@Motif", enquete.Motif);
//open connection
conn.Open();
//execute the SQLCommand
SqlDataReader dr = cmd.ExecuteReader();
//check if there are records
if (dr.HasRows)
{
res = true;
}
dr.Close();
}
return res;
}
catch (Exception ex)
{
throw;
}
}
public static bool UpdateEnquete(Enquete enquete)
{
bool res = false;
try
{
using (SqlConnection conn = new SqlConnection(Variables.connectionSql))
{
//retrieve the SQL Server instance version
string query = @"UPDATE Enquete SET Titulaire_enquete = @Titulaire_enquete, Delegue_enqueteur = @Delegue_enqueteur, Infracteur = @Infracteur, Plaignant = @Plaignant, Etat = @Etat, Avis = @Avis, Motif = @Motif WHERE Id = @Id;";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Id", enquete.Id);
cmd.Parameters.AddWithValue("@Titulaire_enquete", enquete.Titulaire_enquete.Id);
cmd.Parameters.AddWithValue("@Delegue_enqueteur", enquete.Delegue_enqueteur.Id);
cmd.Parameters.AddWithValue("@Infracteur", enquete.Infracteur.Id);
cmd.Parameters.AddWithValue("@Plaignant", enquete.Plaignant.Id);
cmd.Parameters.AddWithValue("@Etat", enquete.Etat);
cmd.Parameters.AddWithValue("@Avis", enquete.Avis);
cmd.Parameters.AddWithValue("@Siege", BoolToInt(enquete.OuvertParLeSiege));
cmd.Parameters.AddWithValue("@Motif", enquete.Motif);
//open connection
conn.Open();
//execute the SQLCommand
SqlDataReader dr = cmd.ExecuteReader();
//check if there are records
if (dr.HasRows)
{
res = true;
}
dr.Close();
}
return res;
}
catch (Exception ex)
{
throw;
}
}
public static string GenerateId(string departement, string mois, string annee)
{
try
{
using (SqlConnection conn = new SqlConnection(Variables.connectionSql))
{
//retrieve the SQL Server instance version
string query = @"select MAX(id)
from (
select SUBSTRING(E.Id, 1, 2) as departement, SUBSTRING(E.Id, CHARINDEX('/', E.Id)+1, 2) as annee, SUBSTRING(E.Id, CHARINDEX('/', E.Id, CHARINDEX('/', E.Id) + 1)+1, 2) as mois, RIGHT(E.Id, 3) as id
from Enquete E
) t1
where departement = @departement
and annee = @annee
and mois = @mois";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@departement", departement);
cmd.Parameters.AddWithValue("@annee", annee);
cmd.Parameters.AddWithValue("@mois", mois);
//open connection
conn.Open();
//execute the SQLCommand
SqlDataReader dr = cmd.ExecuteReader();
//check if there are records
if (dr.HasRows)
{
if (dr.Read())
{
if (dr.IsDBNull(0))
return "000";
else
{
int id = Int32.Parse(dr.GetString(0)) + 1;
return id.ToString("000");
}
}
}
dr.Close();
}
return "000";
}
catch (Exception ex)
{
throw;
}
}
public static bool DeleteEnquete(Enquete enquete)
{
bool res = false;
try
{
using (SqlConnection conn = new SqlConnection(Variables.connectionSql))
{
//retrieve the SQL Server instance version
string query = @"DELETE FROM Enquete WHERE Id = @Id";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Id", enquete.Id);
//open connection
conn.Open();
//execute the SQLCommand
SqlDataReader dr = cmd.ExecuteReader();
//check if there are records
if (dr.HasRows)
{
res = true;
}
dr.Close();
}
return res;
}
catch (Exception ex)
{
throw;
}
}
private static bool IntToBool(int entier)
{
if (entier == 1)
return true;
else
return false;
}
private static int BoolToInt(bool booleen)
{
if (booleen)
return 1;
return 0;
}
}
}
|
using Microsoft.Win32;
using Ookii.Dialogs.Wpf;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
namespace SpriteBook
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
}
private bool RequirePowerOfTwo => this.chkRequirePowerOfTwo.IsChecked.HasValue && this.chkRequirePowerOfTwo.IsChecked.Value;
private bool RequireSameSizeImages => this.chkRequireSameSizeImages.IsChecked.HasValue && this.chkRequireSameSizeImages.IsChecked.Value;
private bool RestrictTo2048X2048 => this.chkRestrictTo2048x2048.IsChecked.HasValue && this.chkRestrictTo2048x2048.IsChecked.Value;
private void AddFolder_Click(object sender, RoutedEventArgs e)
{
try
{
var openFolderDialog = new VistaFolderBrowserDialog();
var result = openFolderDialog.ShowDialog();
if (!result.HasValue || !result.Value)
return;
var folderPath = openFolderDialog.SelectedPath + "\\";
var files = this.GetFiles(folderPath);
foreach (var file in files)
this._imageList.Items.Add(file);
}
catch
{
MessageBox.Show("An error was encountered trying to open the specified folder.");
}
}
private void AddImages_Click(object sender, RoutedEventArgs e)
{
// Restrict the input types to Text, Data, and Log files
var openFileDialog = new OpenFileDialog()
{
Multiselect = true,
Filter = "PNG Image (*.png)|*.png|All files (*.*)|*.*"
};
var result = openFileDialog.ShowDialog();
if (!result.HasValue || !result.Value)
return;
foreach (var filepath in openFileDialog.FileNames)
this._imageList.Items.Add(filepath);
}
private void ClearList_Click(object sender, RoutedEventArgs e)
{
this._imageList.Items.Clear();
}
private void Exit_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private IEnumerable<string> GetFiles(string folder)
{
var filePaths = new List<string>();
// Add this folder's files
var files = Directory.GetFiles(folder, "*.png");
foreach (string file in files)
filePaths.Add(file);
// Add subfolder files
var subfolders = Directory.GetDirectories(folder);
foreach (var subfolder in subfolders)
filePaths.AddRange(this.GetFiles(subfolder));
return filePaths;
}
private void MoveDown_Click(object sender, RoutedEventArgs e)
{
var selectedIndex = this._imageList.SelectedIndex;
if (selectedIndex >= this._imageList.Items.Count - 1)
return;
this._imageList.SelectedIndex = -1;
var lowerPath = this._imageList.Items[selectedIndex + 1] as string;
this._imageList.Items[selectedIndex + 1] = this._imageList.Items[selectedIndex] as string;
this._imageList.Items[selectedIndex] = lowerPath;
this._imageList.SelectedIndex = selectedIndex + 1;
}
private void MoveUp_Click(object sender, RoutedEventArgs e)
{
var selectedIndex = this._imageList.SelectedIndex;
if (selectedIndex <= 0)
return;
this._imageList.SelectedIndex = -1;
var upperPath = this._imageList.Items[selectedIndex - 1] as string;
this._imageList.Items[selectedIndex - 1] = this._imageList.Items[selectedIndex] as string;
this._imageList.Items[selectedIndex] = upperPath;
this._imageList.SelectedIndex = selectedIndex - 1;
}
private void RemoveImage_Click(object sender, RoutedEventArgs e)
{
this._imageList.Items.RemoveAt(this._imageList.SelectedIndex);
}
private void SaveSpriteSheet_Click(object sender, RoutedEventArgs e)
{
// Restrict the input types to Text, Data, and Log files
var saveFileDialog = new SaveFileDialog()
{
Filter = "PNG Image (*.png)|*.png|All files (*.*)|*.*"
};
saveFileDialog.ShowDialog();
if (saveFileDialog.FileName == null)
{
MessageBox.Show("Must provide a valid save path.", "Error");
return;
}
try
{
SpriteGenerator.GenerateSpriteSheet(this._imageList.Items.OfType<string>().ToArray<string>(), saveFileDialog.FileName, 1.0f, RequireSameSizeImages, RequirePowerOfTwo, RestrictTo2048X2048);
}
catch (SpriteSizeException)
{
MessageBox.Show("Image sizes do not match!", "Error");
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterAnimation : MonoBehaviour
{
private Animator anim;
void Awake()
{
anim = GetComponent<Animator>();
}
public void Walk(bool move)
{
anim.SetBool(AnimationTags.MOVEMENT, move);
}
public void Punch_1()
{
anim.SetTrigger(AnimationTags.PUNCH_1_TRIGGER);
}
public void Punch_2()
{
anim.SetTrigger(AnimationTags.PUNCH_2_TRIGGER);
}
public void Punch_3()
{
anim.SetTrigger(AnimationTags.PUNCH_3_TRIGGER);
}
public void Kick_1()
{
anim.SetTrigger(AnimationTags.KICK_1_TRIGGER);
}
public void Kick_2()
{
anim.SetTrigger(AnimationTags.KICK_2_TRIGGER);
}
}
|
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CIPMSBC;
public partial class CamperHolding : System.Web.UI.Page
{
private CamperApplication _objCamperApp;
protected void Page_Load(object sender, EventArgs e)
{
lblMsg.Text = "";
if (!IsPostBack)
{
General objGeneral = new General();
DataSet dsCamps = objGeneral.get_AllCamps(Application["CampYear"].ToString());
ddlCamp.DataSource = dsCamps;
ddlCamp.DataTextField = "Camp";
ddlCamp.DataValueField = "ID";
ddlCamp.DataBind();
ddlCamp.Items.Insert(0, new ListItem("Don't Know Yet", "-1"));
ddlCamp.Items.Insert(0, new ListItem("-- Select --", "0"));
DataSet schoolTypes = objGeneral.GetSchoolType();
ddlSchoolType.DataSource = schoolTypes;
ddlSchoolType.DataBind();
ddlSchoolType.Items.Insert(0, new ListItem("-- Select --", "0"));
txtCamp.Enabled = false;
ddlCamp.Enabled = true;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// 2012-10 It's possible that the potential campers want to register Jwest/JwestLA, but since JWest/JWestLA share zipcodes with other community programs, so the default
// way of getting federation name column in tblCamperHolding is not workable. On the app, when user tris to register JWest/JWestLA when they are still closed, a
// query string variable "fed" will be appended, so this page load can handle it. The store procedure to store the camper holding data will determine if FedName here is
// empty or not
if (ddlSchoolType.SelectedIndex == 0)
{
lblMsg.Text = "You must specify the school type";
return;
}
if (ddlCamp.SelectedIndex == 0 && txtCamp.Text == "")
{
lblMsg.Text = "You must specifiy a camp name";
return;
}
string campName = txtCamp.Text;
if (!chkNoCamp.Checked)
campName = ddlCamp.SelectedItem.Text;
string FedName = "";
if (Request["fed"] != null)
{
FedName = Request["fed"].ToString();
}
_objCamperApp = new CamperApplication();
_objCamperApp.InsertCamperHoldingDetails(txtFirstName.Text, txtLastName.Text, txtEmail.Text, txtZipCode.Text, FedName, campName, chkPJL.Checked, ddlSchoolType.SelectedIndex);
txtFirstName.Text = "";
txtLastName.Text = "";
txtEmail.Text = "";
txtZipCode.Text = "";
lblThankYou.Visible = true;
}
protected void chkNoCamp_CheckedChanged(object sender, EventArgs e)
{
if (chkNoCamp.Checked)
{
txtCamp.Enabled = true;
ddlCamp.Enabled = false;
}
else
{
ddlCamp.Enabled = true;
txtCamp.Enabled = false;
}
}
}
|
using System;
using Divar.Framework.Domain.ValueObjects;
namespace Divar.Core.Domain.Advertisements.ValueObjects
{
public class AdvertisementDescription : BaseValueObject<AdvertisementDescription>
{
public string Value { get; private set; }
public static AdvertisementDescription FromString(string value) => new AdvertisementDescription(value);
private AdvertisementDescription()
{
}
public AdvertisementDescription(string value)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException("برای متن آگهی مقدار لازم است", nameof(value));
}
Value = value;
}
public override int ObjectGetHashCode() => Value.GetHashCode();
public override bool ObjectIsEqual(AdvertisementDescription otherObject) => Value == otherObject.Value;
public static implicit operator string(AdvertisementDescription advertismentText) => advertismentText.Value;
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace EventLite.Streams.StreamManager
{
public interface IStreamManager
{
/// <summary>
/// Add a commi to the stream
/// </summary>
/// <param name="commit"></param>
/// <returns></returns>
Task AddCommit(Commit commit);
/// <summary>
/// Add a snapshot to the stream
/// </summary>
/// <param name="snapshot"></param>
/// <returns></returns>
Task AddSnapshot(Snapshot snapshot);
/// <summary>
/// Update a stream or, if it doesn't exist, insert it
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
Task UpsertStream(EventStream stream);
/// <summary>
/// Get a stream with the supplied unique identifier
/// </summary>
/// <param name="streamId"></param>
/// <returns></returns>
Task<EventStream> GetStream(Guid streamId);
/// <summary>
/// Get a stream's snapshot accordingly with the snapshot revision
/// </summary>
/// <param name="streamId"></param>
/// <param name="snapshotRev"></param>
/// <returns></returns>
Task<Snapshot> GetSnapshot(Guid streamId, int snapshotRev);
/// <summary>
/// Get all snapshots from a stream
/// </summary>
/// <param name="streamId"></param>
/// <returns></returns>
Task<List<Snapshot>> GetSnapshots(Guid streamId);
/// <summary>
/// Get a stream's commit according to the commit revision
/// </summary>
/// <param name="streamId"></param>
/// <param name="commitRev"></param>
/// <returns></returns>
Task<Commit> GetCommit(Guid streamId, int commitRev);
/// <summary>
/// Get all stream's commits that has a revision higher than the minimum revision supplied
/// </summary>
/// <param name="streamId"></param>
/// <param name="minimumRevision"></param>
/// <returns></returns>
Task<List<Commit>> GetCommits(Guid streamId, int minimumRevision = 0);
}
} |
using System;
using System.Text;
using Newtonsoft.Json;
namespace JsonLibrary;
public class Strings
{
public static string getString(byte[] array) => Encoding.UTF8.GetString(array, 0, array.Length).Replace("\0", string.Empty);
public static byte[] getBytes(string text)
{
var newBuffer = new byte[text.Length];
var charsBuffer = Encoding.UTF8.GetBytes(text.ToCharArray());
Buffer.BlockCopy(charsBuffer, 0, newBuffer, 0, text.Length);
return newBuffer;
}
public static byte[] getBytes(string text, int bufferLength)
{
var newBuffer = new byte[bufferLength];
var charsBuffer = Encoding.UTF8.GetBytes(text.ToCharArray());
Buffer.BlockCopy(charsBuffer, 0, newBuffer, 0, text.Length);
return newBuffer;
}
public static dynamic getObject(string json) => JsonConvert.DeserializeObject(json);
} |
namespace Fingo.Auth.Domain.CustomData.ConfigurationClasses
{
public abstract class UserConfiguration : CustomDataConfiguration
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using com.Sconit.Utility;
using com.Sconit.Web.Models.SearchModels.ORD;
using com.Sconit.Web.Models;
using com.Sconit.Entity.ORD;
using System.Text;
using com.Sconit.Service;
using com.Sconit.Web.Models.SearchModels.BIL;
using com.Sconit.Entity.BIL;
namespace com.Sconit.Web.Controllers.SP
{
public class SupplierConsignmentController : WebAppBaseController
{
private static string selectCountStatement = "select count(*) from PlanBill as p";
private static string selectStatement = "select p from PlanBill as p";
//public ISystemMgr systemMgr { get; set; }
//public IGenericMgr genericMgr { get; set; }
#region public
public ActionResult Index()
{
return View();
}
[GridAction]
[SconitAuthorize(Permissions = "Url_Supplier_Consignment")]
public ActionResult List(GridCommand command, PlanBillSearchModel searchModel)
{
TempData["PlanBillSearchModel"] = searchModel;
ViewBag.PageSize = base.ProcessPageSize(command.PageSize);
return View();
}
[GridAction(EnableCustomBinding = false)]
[SconitAuthorize(Permissions = "Url_Supplier_Consignment")]
public ActionResult _AjaxList(GridCommand command, PlanBillSearchModel searchModel)
{
//int pageSize = command.PageSize;
//int page = command.Page;
command.PageSize = int.MaxValue;
command.Page = 1;
SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel);
var gridData = GetAjaxPageData<PlanBill>(searchStatementModel, command);
//command.PageSize = pageSize;
//command.Page = page;
gridData.Data = gridData.Data.GroupBy(p => new
{
p.Party,
p.Item,
p.Uom,
}, (k, g) => new PlanBill
{
Party = k.Party,
Item = k.Item,
ItemDescription = g.First().ItemDescription,
Uom = k.Uom,
CurrentActingQty = g.Sum(q => q.PlanQty) - g.Sum(q => q.ActingQty),
});
return PartialView(gridData);
}
#endregion
#region private
private SearchStatementModel PrepareSearchStatement(GridCommand command, PlanBillSearchModel searchModel)
{
string whereStatement = string.Empty;
IList<object> param = new List<object>();
SecurityHelper.AddBillPermissionStatement(ref whereStatement, "p", "Party", com.Sconit.CodeMaster.BillType.Procurement);
HqlStatementHelper.AddLikeStatement("OrderNo", searchModel.OrderNo, HqlStatementHelper.LikeMatchMode.Start, "p", ref whereStatement, param);
HqlStatementHelper.AddLikeStatement("ReceiptNo", searchModel.ReceiptNo, HqlStatementHelper.LikeMatchMode.Start, "p", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("Item", searchModel.Item, "p", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("Party", searchModel.Party, "p", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("Type", com.Sconit.CodeMaster.BillType.Procurement, "p", ref whereStatement, param);
if (searchModel.CreateDate_start != null & searchModel.CreateDate_End != null)
{
HqlStatementHelper.AddBetweenStatement("CreateDate", searchModel.CreateDate_start, searchModel.CreateDate_End, "p", ref whereStatement, param);
}
else if (searchModel.CreateDate_start != null & searchModel.CreateDate_End == null)
{
HqlStatementHelper.AddGeStatement("CreateDate", searchModel.CreateDate_start, "p", ref whereStatement, param);
}
else if (searchModel.CreateDate_start == null & searchModel.CreateDate_End != null)
{
HqlStatementHelper.AddLeStatement("CreateDate", searchModel.CreateDate_End, "p", ref whereStatement, param);
}
if (whereStatement == string.Empty)
{
whereStatement += " where p.PlanQty>p.ActingQty";
}
else
{
whereStatement += " and p.PlanQty>p.ActingQty";
}
string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
SearchStatementModel searchStatementModel = new SearchStatementModel();
searchStatementModel.SelectCountStatement = selectCountStatement;
searchStatementModel.SelectStatement = selectStatement;
searchStatementModel.WhereStatement = whereStatement;
searchStatementModel.SortingStatement = sortingStatement;
searchStatementModel.Parameters = param.ToArray<object>();
return searchStatementModel;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Serialization.Mappers
{
public interface IPropertyMapper
{
string Name { get; set; }
int Order { get; set; }
bool OrderSpecified { get; set; }
int Length { get; set; }
bool LengthSpecified { get; set; }
bool IsNullable { get; set; }
bool IsNullableSpecified { get; set; }
Type MappedType { get; }
TextMapping TextMapping { get; set; }
}
}
|
using JT808.Protocol.Formatters;
using JT808.Protocol.Interfaces;
using JT808.Protocol.MessagePack;
using JT808.Protocol.Metadata;
using System.Collections.Generic;
namespace JT808.Protocol.MessageBody
{
/// <summary>
/// 存储多媒体数据检索应答
/// 0x0802
/// </summary>
public class JT808_0x0802 : JT808Bodies, IJT808MessagePackFormatter<JT808_0x0802>, IJT808_2019_Version
{
public override ushort MsgId { get; } = 0x0802;
/// <summary>
/// 应答流水号
/// 对应的多媒体数据检索消息的流水号
/// </summary>
public ushort MsgNum { get; set; }
/// <summary>
/// 多媒体数据总项数
/// 满足检索条件的多媒体数据总项数
/// </summary>
public ushort MultimediaItemCount { get; set; }
/// <summary>
/// 检索项集合
/// </summary>
public List<JT808MultimediaSearchProperty> MultimediaSearchItems { get; set; }
public JT808_0x0802 Deserialize(ref JT808MessagePackReader reader, IJT808Config config)
{
JT808_0x0802 JT808_0x0802 = new JT808_0x0802();
JT808_0x0802.MsgNum = reader.ReadUInt16();
JT808_0x0802.MultimediaItemCount = reader.ReadUInt16();
JT808_0x0802.MultimediaSearchItems = new List<JT808MultimediaSearchProperty>();
for (var i = 0; i < JT808_0x0802.MultimediaItemCount; i++)
{
JT808MultimediaSearchProperty jT808MultimediaSearchProperty = new JT808MultimediaSearchProperty();
jT808MultimediaSearchProperty.MultimediaId = reader.ReadUInt32();
jT808MultimediaSearchProperty.MultimediaType = reader.ReadByte();
jT808MultimediaSearchProperty.ChannelId = reader.ReadByte();
jT808MultimediaSearchProperty.EventItemCoding = reader.ReadByte();
JT808MessagePackReader positionReader = new JT808MessagePackReader(reader.ReadArray(28));
jT808MultimediaSearchProperty.Position = config.GetMessagePackFormatter<JT808_0x0200>().Deserialize(ref positionReader, config);
JT808_0x0802.MultimediaSearchItems.Add(jT808MultimediaSearchProperty);
}
return JT808_0x0802;
}
public void Serialize(ref JT808MessagePackWriter writer, JT808_0x0802 value, IJT808Config config)
{
writer.WriteUInt16(value.MsgNum);
writer.WriteUInt16((ushort)value.MultimediaSearchItems.Count);
foreach (var item in value.MultimediaSearchItems)
{
writer.WriteUInt32(item.MultimediaId);
writer.WriteByte(item.MultimediaType);
writer.WriteByte(item.ChannelId);
writer.WriteByte(item.EventItemCoding);
config.GetMessagePackFormatter<JT808_0x0200>().Serialize(ref writer, item.Position, config);
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
namespace Alabo.Datas.UnitOfWorks.PgSql {
/// <summary>
/// 工作单元
/// </summary>
public class PgSqlUnitOfWork : Ef.PgSql.PgSqlUnitOfWork, IUnitOfWork {
/// <summary>
/// 初始化工作单元
/// </summary>
/// <param name="options">配置项</param>
/// <param name="unitOfWorkManager">工作单元服务</param>
public PgSqlUnitOfWork(DbContextOptions options, IUnitOfWorkManager unitOfWorkManager) : base(options,
unitOfWorkManager) {
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Http;
using Models.EFDB;
using ServerApi.OwinMiddleware.Authentication;
using ServerApi.Services.Progress;
using ServerApi.Services.Users;
namespace ServerApi.Controllers
{
[Authorize(Roles = nameof(Roles.RegisteredUser))]
[RoutePrefix("api/progress/tasks")]
public class TaskProgressController : ApiController
{
private readonly TasksProgressService _tasksProgressService = new TasksProgressService();
private readonly GetUsersService _getUsersService = new GetUsersService();
[HttpGet]
[Route("")]
public async Task<IHttpActionResult> GetTaskProgresses([FromUri] long? lastUpdate = null)
{
var claimUser = this.User as ClaimsPrincipal;
var deviceGuid = Guid.Parse(claimUser.FindFirst("DeviceId").Value);
var unitId = (await _getUsersService.GetUserByDeviceAsync(deviceGuid)).UnitId;
IEnumerable<TaskProgress> tProgresses;
if (lastUpdate == null)
{
tProgresses = await _tasksProgressService.GetTasksProgressesByUnitIdAsync(unitId);
}
else
{
var from = new DateTime(lastUpdate.Value);
tProgresses = await _tasksProgressService.GetTasksProgressesByUnitIdAsync(unitId, from);
}
var DTOs = tProgresses.Select(tp => (Models.DTO.TaskProgress)tp);
return Ok(DTOs);
}
[HttpPut]
[Route("{taskProgressId}", Name = "PutTaskProgress")]
public async Task<IHttpActionResult> PutTaskProgress([FromUri] Guid taskProgressId, [FromBody] Models.DTO.TaskProgress taskProgress)
{
await _tasksProgressService.StoreTaskProgressAsync(taskProgress);
return Created(Url.Route("PutTaskProgress", null), taskProgress);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class isoUVAnimaiton : MonoBehaviour
{
public Material _material;
public Vector2 _texOffset;
// Start is called before the first frame update
void Start()
{
_material = this.gameObject.GetComponent<Renderer>().material;
_texOffset = _material.GetTextureOffset("_MainTex");
}
// Update is called once per frame
void Update()
{
_texOffset.y += Time.deltaTime;
if(_texOffset.y >= 1.0f) {
_texOffset.y = 0.0f;
}
_material.SetTextureOffset("_MainTex", _texOffset);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
namespace PixelRobot
{
class ProcessingPipeline
{
ProcessorProperties pp;
public int ppAppType;
public ProcessingPipeline(ProcessorProperties p, int i)
{
pp = p;
ppAppType = i;
}
public bool ProcessFile(string filename, ExifReader r, string sourceFolder, string destinationFolder, bool heirarchyUnderSource, string watermarkText)
{
if (pp.useProcessor == false)
return false;
CheckAuthCode ca = new CheckAuthCode();
if (ca.IsAnyCodeValid(ppAppType) == false)
return false;
// the original filename e.g. c:\pics\folder1\pic1.jpg
string sourceFilename = filename;
// Get the original image
System.Drawing.Image sourceImage = (System.Drawing.Image)r.GetImage().Clone();
// auto rotate from EXIF info if necessary
string or = r.GetOrientation();
if (pp.editAutoRotate)
{
if (or.Equals("Rotate right"))
sourceImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
else if (or.Equals("Rotate left"))
sourceImage.RotateFlip(RotateFlipType.Rotate270FlipNone);
}
// Get the new folder and filename ready
// path to original filename e.g. c:\pics\folder1\
string pathToFilename = sourceFilename.Substring(0, sourceFilename.LastIndexOf('\\') + 1).ToLower();
// partial path, take off the path to the source folder e.g. \folder1\
string partialPath = pathToFilename.Substring(sourceFolder.Length);
string newFolder;
if (pp.targetFolder.Contains("\\\\") || pp.targetFolder.Contains(":")) // target folder is an absolute path
{
// heirarchyUnderSource makes no difference - we are putting everything in the absolute path
string absoluteTarget = pp.targetFolder.TrimEnd('\\');
newFolder = absoluteTarget + partialPath;
}
else // append the target folder to the source, depending on the mode
{
if (heirarchyUnderSource)
{
// add the partial path and target folder to the destination e.g. f:\processed\folder1\thumbs\
newFolder = destinationFolder + partialPath + pp.targetFolder + "\\";
}
else
{
// add the target folder and partial path to the destination e.g. f:\processed\thumbs\folder1\
newFolder = destinationFolder + "\\" + pp.targetFolder + partialPath;
}
}
// then add on the actual filename to get the new filename with full path
string newFilename = newFolder + sourceFilename.Substring(sourceFilename.LastIndexOf('\\') + 1);
if (Directory.Exists(newFolder) == false)
Directory.CreateDirectory(newFolder);
// ********** Image Processing Pipeline ******************
System.Drawing.Image newImage = sourceImage;
// resize it
if (pp.applyResize)
newImage = resizeImage(sourceImage, pp);
if (ppAppType > 10)
{
// edit it - colours
if (pp.editMono)
ApplyMono(newImage);
else if (pp.editSepia)
ApplySepia(newImage);
// edit it - flipflop
if ((pp.editFlip) || (pp.editMirror))
{
if (pp.editFlip == false) // just mirror
newImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
else if (pp.editMirror == false) // just flip
newImage.RotateFlip(RotateFlipType.RotateNoneFlipY);
else
newImage.RotateFlip(RotateFlipType.RotateNoneFlipXY);
}
}
// watermark it with text
if (pp.applyWatermark)
{
ApplyWatermark(newImage, watermarkText);
}
if (ppAppType == 127)
{
// watermark it with an image
if (pp.applyWatermarkImage)
{
ApplyWatermarkImage(newImage, pp);
}
}
if (ppAppType > 10)
{
// add vignette ?
if (pp.applyVignette)
{
ApplyVignette(newImage, pp);
}
// add border ?
if (pp.applyBorder)
{
newImage = ApplyBorder(newImage, pp);
}
}
// save it
Bitmap newBMP = new Bitmap(newImage);
SaveFile(newFilename, newBMP);
newBMP.Dispose();
newImage.Dispose();
return true;
}
private void SaveFile(string path, Bitmap img)
{
// Encoder parameter for image quality
EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, pp.jpegQual);
string newPath = path;
ImageCodecInfo encCodec = null;
switch (pp.outputFormat)
{
case OutputType.GIF:
encCodec = this.getEncoderInfo("image/gif");
newPath = FixupFilename(path, "gif");
break;
case OutputType.Bitmap:
encCodec = this.getEncoderInfo("image/bmp");
newPath = FixupFilename(path, "bmp");
break;
case OutputType.PNG:
encCodec = this.getEncoderInfo("image/png");
newPath = FixupFilename(path, "png");
break;
case OutputType.TIFF:
encCodec = this.getEncoderInfo("image/tiff");
newPath = FixupFilename(path, "tif");
break;
case OutputType.JPEG:
default:
encCodec = this.getEncoderInfo("image/jpeg");
newPath = FixupFilename(path, "jpg");
break;
}
if (encCodec == null)
return;
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
if (File.Exists(newPath))
newPath = GetNewPath(newPath);
img.SetResolution(pp.dpiVal, pp.dpiVal);
img.Save(newPath, encCodec, encoderParams);
}
private string GetNewPath(string oldPath)
{
FileInfo oldFileInfo = new FileInfo(oldPath);
string dirShort = System.IO.Path.GetFullPath(oldPath);
string fileShort = System.IO.Path.GetFileNameWithoutExtension(oldPath);
string fileExt = System.IO.Path.GetExtension(oldPath);
int copyCount = 2;
while (copyCount < 102)
{
string newPath = oldFileInfo.Directory + "\\" + fileShort + " (" + copyCount.ToString() + ")" + fileExt;
if (File.Exists(newPath) == false)
return newPath;
copyCount++;
}
throw new Exception("100 Copies - something must be wrong");
}
private string FixupFilename(string path, string extension)
{
string newPath = System.IO.Path.ChangeExtension(path, extension);
return newPath;
}
private ImageCodecInfo getEncoderInfo(string mimeType)
{
// Get image codecs for all image formats
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// Find the correct image codec
for (int i = 0; i < codecs.Length; i++)
if (codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
private System.Drawing.Image ApplyBorder(System.Drawing.Image imgToBorder, ProcessorProperties pp)
{
if (ppAppType > 10)
{
Bitmap borderedImage = new Bitmap(imgToBorder.Width + (pp.borderWidth * 2), imgToBorder.Height + (pp.borderWidth * 2));
Graphics g = Graphics.FromImage(borderedImage);
SolidBrush borderBrush = new SolidBrush(System.Drawing.Color.FromArgb(pp.borderColour.R, pp.borderColour.G, pp.borderColour.B));
g.FillRectangle(borderBrush, 0, 0, borderedImage.Width, borderedImage.Height);
g.DrawImageUnscaled(imgToBorder, pp.borderWidth, pp.borderWidth);
g.Dispose();
return (System.Drawing.Image)borderedImage;
}
else
return null;
}
private void ApplyMono(System.Drawing.Image imgToEdit)
{
Graphics g = Graphics.FromImage(imgToEdit);
float[][] FloatColorMatrix = {
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
};
System.Drawing.Imaging.ColorMatrix NewColorMatrix = new System.Drawing.Imaging.ColorMatrix(FloatColorMatrix);
System.Drawing.Imaging.ImageAttributes Attributes = new System.Drawing.Imaging.ImageAttributes();
Attributes.SetColorMatrix(NewColorMatrix);
g.DrawImage(imgToEdit, new System.Drawing.Rectangle(0, 0, imgToEdit.Width, imgToEdit.Height), 0, 0, imgToEdit.Width, imgToEdit.Height, System.Drawing.GraphicsUnit.Pixel, Attributes);
g.Dispose();
}
private void ApplySepia(System.Drawing.Image imgToEdit)
{
Graphics g = Graphics.FromImage(imgToEdit);
float[][] FloatColorMatrix = {
new float[] {.4f, .3f, .2f, 0, 0},
new float[] {.69f, .59f, .49f, 0, 0},
new float[] {.21f, .11f, .05f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
};
System.Drawing.Imaging.ColorMatrix NewColorMatrix = new System.Drawing.Imaging.ColorMatrix(FloatColorMatrix);
System.Drawing.Imaging.ImageAttributes Attributes = new System.Drawing.Imaging.ImageAttributes();
Attributes.SetColorMatrix(NewColorMatrix);
g.DrawImage(imgToEdit, new System.Drawing.Rectangle(0, 0, imgToEdit.Width, imgToEdit.Height), 0, 0, imgToEdit.Width, imgToEdit.Height, System.Drawing.GraphicsUnit.Pixel, Attributes);
g.Dispose();
}
private void ApplyWatermark(System.Drawing.Image imgToResize, string watermarkText)
{
Graphics g = Graphics.FromImage(imgToResize);
string localWatermarkText = pp.watermarkText;
if (localWatermarkText == "")
localWatermarkText = watermarkText;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
StringFormat strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Center;
strFormat.LineAlignment = StringAlignment.Center;
double textLength;
double adjustedTextLength;
if (pp.watermarkDiagonal == true)
textLength = Math.Sqrt(Math.Pow(imgToResize.Width, 2) + Math.Pow(imgToResize.Height, 2));
else
textLength = (double)imgToResize.Width;
adjustedTextLength = textLength * 1.2;
int fontH = (int)adjustedTextLength / localWatermarkText.Length;
double textOverlap = textLength - (double)imgToResize.Width;
// free version gets Arial grey, 180 opacity
Font watermarkFont;
SolidBrush foreBrush;
if (ppAppType < 10)
{
watermarkFont = new Font("Arial", fontH);
foreBrush = new SolidBrush(System.Drawing.Color.FromArgb(180, 128, 128, 128));
}
else
{
if (pp.watermarkBold)
{
if (pp.watermarkItalic)
watermarkFont = new Font(pp.watermarkFontFace, fontH, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic);
else
watermarkFont = new Font(pp.watermarkFontFace, fontH, System.Drawing.FontStyle.Bold);
}
else
{
if (pp.watermarkItalic)
watermarkFont = new Font(pp.watermarkFontFace, fontH, System.Drawing.FontStyle.Italic);
else
watermarkFont = new Font(pp.watermarkFontFace, fontH);
}
foreBrush = new SolidBrush(System.Drawing.Color.FromArgb(pp.watermarkOpacity, pp.watermarkColour.R, pp.watermarkColour.G, pp.watermarkColour.B));
}
double rotateAngle = (double)0;
if (pp.watermarkDiagonal == true)
{
rotateAngle = Math.Atan((double)imgToResize.Height / (double)imgToResize.Width) * 180 / Math.PI;
g.TranslateTransform((float)imgToResize.Width / 2, (float)imgToResize.Height / 2);
g.RotateTransform(-(float)rotateAngle);
g.TranslateTransform(-(float)imgToResize.Width / 2, -(float)imgToResize.Height / 2);
}
RectangleF textRect = new RectangleF(-(float)textOverlap / 2, 0, (float)textLength, imgToResize.Height);
RectangleF textRect2 = new RectangleF(-(float)textOverlap / 2 + 2, 2, (float)textLength, imgToResize.Height);
if (pp.watermark3D && (ppAppType > 78))
{
SolidBrush backBrush = new SolidBrush(System.Drawing.Color.FromArgb(pp.watermarkOpacity, 0, 0, 0));
g.DrawString(localWatermarkText, watermarkFont, backBrush, textRect2, strFormat);
backBrush.Dispose();
}
g.DrawString(localWatermarkText, watermarkFont, foreBrush, textRect, strFormat);
if (pp.watermarkDiagonal == true)
{
g.RotateTransform((float)rotateAngle);
}
watermarkFont.Dispose();
foreBrush.Dispose();
g.Dispose();
}
private void ApplyWatermarkImage(System.Drawing.Image imgToResize, ProcessorProperties pp)
{
if (ppAppType < 100)
return;
if (File.Exists(pp.watermarkImageFile) == false)
return;
Graphics g = Graphics.FromImage(imgToResize);
System.Drawing.Image watermarkImage = System.Drawing.Image.FromFile(pp.watermarkImageFile);
int tWid;
int tHei;
int xOff;
int yOff;
if (pp.watermarkImageLocation == 9)
{
tWid = imgToResize.Width;
tHei = tWid * watermarkImage.Height / watermarkImage.Width;
if (tHei > imgToResize.Height)
{
tHei = imgToResize.Height;
tWid = tHei * watermarkImage.Width / watermarkImage.Height;
}
xOff = (imgToResize.Width - tWid) / 2;
yOff = (imgToResize.Height - tHei) / 2;
}
else
{
tWid = imgToResize.Width / 3;
tHei = tWid * watermarkImage.Height / watermarkImage.Width;
if (tHei > imgToResize.Height / 3)
{
tHei = imgToResize.Height / 3;
tWid = tHei * watermarkImage.Width / watermarkImage.Height;
}
xOff = ((imgToResize.Width / 3) - tWid) / 2;
yOff = ((imgToResize.Height / 3) - tHei) / 2;
if ((pp.watermarkImageLocation == 1) ||
(pp.watermarkImageLocation == 4) ||
(pp.watermarkImageLocation == 7))
xOff += (imgToResize.Width / 3);
else if ((pp.watermarkImageLocation == 2) ||
(pp.watermarkImageLocation == 5) ||
(pp.watermarkImageLocation == 8))
xOff += (2 * imgToResize.Width / 3);
if ((pp.watermarkImageLocation == 3) ||
(pp.watermarkImageLocation == 4) ||
(pp.watermarkImageLocation == 5))
yOff += (imgToResize.Height / 3);
else if ((pp.watermarkImageLocation == 6) ||
(pp.watermarkImageLocation == 7) ||
(pp.watermarkImageLocation == 8))
yOff += (2 * imgToResize.Height / 3);
}
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(xOff, yOff, tWid, tHei);
ColorMatrix matrix = new ColorMatrix();
matrix.Matrix33 = (float)pp.watermarkImageOpacity / (float)255; //opacity 0 = completely transparent, 1 = completely opaque
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
g.DrawImage(watermarkImage, rect, 0, 0, watermarkImage.Width, watermarkImage.Height, System.Drawing.GraphicsUnit.Pixel, attributes);
g.Dispose();
}
private void ApplyVignette(System.Drawing.Image imgToResize, ProcessorProperties pp)
{
if (ppAppType > 10)
{
Graphics g = Graphics.FromImage(imgToResize);
System.Drawing.Image watermarkImage;
if (pp.vignetteBlack)
watermarkImage = (System.Drawing.Image)PixelRobot.Properties.Resources.ResourceManager.GetObject("vignette_black");
else
watermarkImage = (System.Drawing.Image)PixelRobot.Properties.Resources.ResourceManager.GetObject("vignette_white");
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, imgToResize.Width, imgToResize.Height);
ColorMatrix matrix = new ColorMatrix();
matrix.Matrix33 = (float)pp.vignetteOpacity / (float)255; //opacity 0 = completely transparent, 1 = completely opaque
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
g.DrawImage(watermarkImage, rect, 0, 0, watermarkImage.Width, watermarkImage.Height, System.Drawing.GraphicsUnit.Pixel, attributes);
g.Dispose();
}
}
private Image resizeImage(System.Drawing.Image imgToResize, ProcessorProperties pp)
{
double xOffset = 0;
double yOffset = 0;
double destWidth;
double destHeight;
int targetWidth = pp.processSizeW;
int targetHeight = pp.processSizeH;
if (ppAppType > 10)
{
if (pp.rotateFit)
{
if (((targetHeight > targetWidth) && (imgToResize.Height < imgToResize.Width)) ||
((targetHeight < targetWidth) && (imgToResize.Height > imgToResize.Width)))
{
targetHeight = pp.processSizeW;
targetWidth = pp.processSizeH;
}
}
if (pp.resizeBy == 2)
{
targetHeight = imgToResize.Height * pp.processSizePercent / 100;
targetWidth = imgToResize.Width * pp.processSizePercent / 100;
}
// if the final size includes the border, reduce it here as we'll add it back later
if ((pp.applyBorder == true) && (pp.sizeIncludesBorder == true) && (pp.borderWidth > 0))
{
targetHeight -= (pp.borderWidth * 2);
targetWidth -= (pp.borderWidth * 2);
}
}
// if we are scaling to FIT, we need to make sure neither dimension exceeds the specified size
if (pp.fillArea == false)
{
// set the destination width, then work out what the height would be
destWidth = targetWidth;
destHeight = destWidth * imgToResize.Height / imgToResize.Width;
// if the height is too big, set the height, then work out the width
if (destHeight > targetHeight)
{
destHeight = targetHeight;
destWidth = destHeight * imgToResize.Width / imgToResize.Height;
}
// in this way, we always scale to fit in the desired area
}
// otherwise, we do it the other way round
else
{
// set the destination width, then work out what the height would be
destWidth = targetWidth;
destHeight = destWidth * imgToResize.Height / imgToResize.Width;
// if the height is too small, set the height, then work out the width
if (destHeight < targetHeight)
{
destHeight = targetHeight;
destWidth = destHeight * imgToResize.Width / imgToResize.Height;
// we've made the width larger than it needs to be, so that we have
// enough height to fill the area, so work out the difference between
// the width we're going to use and the width we need, then divide by 2
// This will give us the offset needed for a centre crop
xOffset = (destWidth - targetWidth) / 2; // (we'll use this later)
}
else
{
// do the same for the height if the width is right
yOffset = (destHeight - targetHeight) / 2; // (or this)
}
// in this way, we always scale to fill the desired area
// (we'll also need to crop it later!)
}
Bitmap b = new Bitmap((int)destWidth, (int)destHeight);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);
switch (pp.resampleQuality)
{
case 2:
g.InterpolationMode = InterpolationMode.Bicubic; break;
case 1:
g.InterpolationMode = InterpolationMode.Bilinear; break;
case 0:
g.InterpolationMode = InterpolationMode.NearestNeighbor; break;
default:
g.InterpolationMode = InterpolationMode.Bilinear; break;
}
g.DrawImage(imgToResize, 0, 0, (int)destWidth, (int)destHeight);
g.Dispose();
// if we're fitting, we've scaled it right, just return it
if (pp.fillArea == false)
return (System.Drawing.Image)b;
// if we get here, we're filling. We've scaled it enough to fill the desired
// size, but this may be too large in one dimension, so we now need to crop it
System.Drawing.Rectangle cropRect = new System.Drawing.Rectangle((int)xOffset, (int)yOffset, targetWidth, targetHeight);
System.Drawing.Image i = cropImage((System.Drawing.Image)b, cropRect);
return i;
}
private System.Drawing.Image cropImage(System.Drawing.Image img, System.Drawing.Rectangle cropArea)
{
Bitmap bmpImage = new Bitmap(img);
Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
return (System.Drawing.Image)(bmpCrop);
}
}
}
|
using System.Threading.Tasks;
using Neon.Cadence;
namespace bug_repro_3_1_15_success.Cadence
{
[Activity(AutoRegister = true)]
public class ExampleActivity : ActivityBase, IExampleActivity
{
public Task<bool> RunExampleActivityAsync()
{
Activity.Logger.LogInfo("RunExampleActivityAsync - Executing");
return Task.FromResult(true);
}
}
[ActivityInterface]
public interface IExampleActivity : IActivity
{
[ActivityMethod]
Task<bool> RunExampleActivityAsync();
}
} |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.Script.Serialization;
using System.Threading;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Drawing;
using YFVIC.DMS.Model.Models.Settings;
using YFVIC.DMS.Model.Models.HR;
using YFVIC.DMS.Model.Models.Common;
using YFVIC.DMS.Model.Models.Document;
using YFVIC.DMS.Model.Models.FileInfo;
namespace YFVIC.DMS.Solution
{
public class WebUploadHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
HttpPostedFile file = context.Request.Files[0];
string url = SPContext.Current.Web.Url;
SPUser user = SPContext.Current.Web.CurrentUser;
SettingsMgr mgr = new SettingsMgr();
DocumentMgr docmgr = new DocumentMgr();
string uniqueid = "";
string filename = context.Request["name"];
string guid = context.Request["guid"];
string loginname = DMSComm.resolveLogon(user.LoginName);
SysUserMgr usermgr=new SysUserMgr();
BigFileMgr bigfilemgr = new BigFileMgr();
string company = usermgr.GetUserCompany(loginname);
SysOrgMgr orgmgr = new SysOrgMgr();
SysOrgEntity org = orgmgr.GetOrgByUser(loginname);
//如果进行了分片
if (context.Request.Form.AllKeys.Any(m => m == "chunk"))
{
//取得chunk和chunks
int chunk = Convert.ToInt32(context.Request.Form["chunk"]);//当前分片在上传分片中的顺序(从0开始)
int chunks = Convert.ToInt32(context.Request.Form["chunks"]);//总分片数
//根据GUID创建用该GUID命名的临时文件夹
string folder = context.Server.MapPath("~/Upload/" + guid+ "/");
string path = folder + chunk;
string root = HttpContext.Current.Server.MapPath("~/Upload/" + company + "/" + org.Id + "/");
string targetPath = Path.Combine(root,filename);//合并后的文件
//建立临时传输文件夹
if (!Directory.Exists(Path.GetDirectoryName(folder)))
{
Directory.CreateDirectory(folder);
}
if (!Directory.Exists(Path.GetDirectoryName(root)))
{
Directory.CreateDirectory(root);
}
FileStream addFile = new FileStream(path, FileMode.Append, FileAccess.Write);
BinaryWriter AddWriter = new BinaryWriter(addFile);
//获得上传的分片数据流
Stream stream = file.InputStream;
BinaryReader TempReader = new BinaryReader(stream);
//将上传的分片追加到临时文件末尾
AddWriter.Write(TempReader.ReadBytes((int)stream.Length));
//关闭BinaryReader文件阅读器
TempReader.Close();
stream.Close();
AddWriter.Close();
addFile.Close();
TempReader.Dispose();
stream.Dispose();
AddWriter.Dispose();
addFile.Dispose();
DirectoryInfo dicInfo = new DirectoryInfo(folder);
System.IO.FileInfo[] files = dicInfo.GetFiles();
if (files.Count() == chunks)
{
if (files.Count() > 20)
{
foreach (System.IO.FileInfo webfile in files.OrderBy(f => int.Parse(f.Name)))
{
FileStream newFile = new FileStream(targetPath, FileMode.Append, FileAccess.Write);
BinaryWriter newWriter = new BinaryWriter(newFile);
//获得上传的分片数据流
Stream newstream = webfile.Open(FileMode.Open);
BinaryReader newTempReader = new BinaryReader(newstream);
//将上传的分片追加到临时文件末尾
newWriter.Write(newTempReader.ReadBytes((int)newstream.Length));
//关闭BinaryReader文件阅读器
newTempReader.Close();
newstream.Close();
newWriter.Close();
newFile.Close();
newTempReader.Dispose();
newstream.Dispose();
newWriter.Dispose();
newFile.Dispose();
}
DeleteFolder(folder);
ReturnResult result = new ReturnResult
{
FileUniqueId = targetPath,
FilePath = targetPath,
FileName = filename,
isError = "false",
FileArea = "本地"
};
// docmgr.AddPermissionForFile(SPContext.Current.Site.Url, sfile.UniqueId.ToString(), loginname);
context.Response.Write(new JavaScriptSerializer().Serialize(result));
}
else
{
int filelength = 0;
foreach (System.IO.FileInfo webfile in files.OrderBy(f => int.Parse(f.Name)))
{
Stream newstream = webfile.Open(FileMode.Open);
filelength = filelength + Convert.ToInt32(newstream.Length);
newstream.Close();
newstream.Dispose();
}
Byte[] filecontext = new Byte[filelength];
int i = 0;
foreach (System.IO.FileInfo webfile in files.OrderBy(f => int.Parse(f.Name)))
{
Stream newstream = webfile.Open(FileMode.Open);
Byte[] buffer = new Byte[newstream.Length];
newstream.Read(buffer, 0, Convert.ToInt32(newstream.Length));
buffer.CopyTo(filecontext, i);
i = i + Convert.ToInt32(newstream.Length);
newstream.Close();
newstream.Dispose();
}
DeleteFolder(folder);
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
string ListName = context.Request.Form["ListName"];
string FolderPath = docmgr.GetPeopleDocument(loginname, url, "file");
web.AllowUnsafeUpdates = true;
SPFolder spfolder = web.GetFolder(new Guid(FolderPath));
SPFile sfile = spfolder.Files.Add(file.FileName, filecontext, true);
web.AllowUnsafeUpdates = false;
uniqueid = sfile.UniqueId.ToString();
ReturnResult result = new ReturnResult
{
FileUniqueId = sfile.UniqueId.ToString(),
FilePath = sfile.Url,
FileName = sfile.Name,
FileArea="Sharepoint"
};
context.Response.Write(new JavaScriptSerializer().Serialize(result));
}
}
});
}
catch (Exception ex)
{
ReturnResult result = new ReturnResult
{
ErrorMessage = ex.ToString(),
isError = "true",
};
context.Response.Write(new JavaScriptSerializer().Serialize(result));
}
}
}
else
{
ReturnResult result = new ReturnResult
{
Chunked = "true",
isError = "false",
FileName = Path.GetExtension(file.FileName),
};
// docmgr.AddPermissionForFile(SPContext.Current.Site.Url, sfile.UniqueId.ToString(), loginname,"Read");
context.Response.Write(new JavaScriptSerializer().Serialize(result));
}
// docmgr.AddPermissionForFile(SPContext.Current.Site.Url, sfile.UniqueId.ToString(), loginname,"Read");
}
else//没有分片直接保存
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
try
{
if (!string.IsNullOrEmpty(context.Request.Form["isForm"]))
{
Byte[] filecontext = new Byte[file.ContentLength];
file.InputStream.Read(filecontext, 0, file.ContentLength);
string folderName = context.Request.Form["ListName"];
web.AllowUnsafeUpdates = true;
string FolderPath = docmgr.GetPeopleDocument(loginname, url, "form");
SPFolder folder = web.GetFolder(new Guid(FolderPath));
SPFile sfile = folder.Files.Add(file.FileName, filecontext, true);
SPFileVersionCollection versions = sfile.Versions;
web.AllowUnsafeUpdates = false;
uniqueid = sfile.UniqueId.ToString();
ReturnResult result = new ReturnResult
{
FileUniqueId = sfile.UniqueId.ToString(),
FilePath = sfile.Url,
FileName = sfile.Name,
FileArea="Sharepoint"
};
// docmgr.AddPermissionForFile(SPContext.Current.Site.Url, sfile.UniqueId.ToString(), loginname);
context.Response.Write(new JavaScriptSerializer().Serialize(result));
}
else
{
Byte[] filecontext = new Byte[file.ContentLength];
file.InputStream.Read(filecontext, 0, file.ContentLength);
string ListName = context.Request.Form["ListName"];
string FolderPath = docmgr.GetPeopleDocument(loginname, url, "file");
web.AllowUnsafeUpdates = true;
SPFolder folder = web.GetFolder(new Guid(FolderPath));
SPFile sfile = folder.Files.Add(file.FileName, filecontext, true);
web.AllowUnsafeUpdates = false;
uniqueid = sfile.UniqueId.ToString();
ReturnResult result = new ReturnResult
{
FileUniqueId = sfile.UniqueId.ToString(),
FilePath = sfile.Url,
FileName = sfile.Name,
FileArea = "Sharepoint"
};
// docmgr.AddPermissionForFile(SPContext.Current.Site.Url, sfile.UniqueId.ToString(), loginname,"Read");
context.Response.Write(new JavaScriptSerializer().Serialize(result));
}
}
catch (Exception ex)
{
if (!string.IsNullOrEmpty(uniqueid))
{
web.AllowUnsafeUpdates = true;
SPFile fileinfo = web.GetFile(new Guid(uniqueid));
fileinfo.Delete();
web.AllowUnsafeUpdates = false;
}
ReturnResult result = new ReturnResult
{
isError = "true",
ErrorMessage = ex.Message
};
context.Response.Write(new JavaScriptSerializer().Serialize(result));
}
}
}
});
}
}
/// <summary>
/// 删除文件夹及其内容
/// </summary>
/// <param name="dir"></param>
private static void DeleteFolder(string strPath)
{
//删除这个目录下的所有子目录
if (Directory.GetDirectories(strPath).Length > 0)
{
foreach (string fl in Directory.GetDirectories(strPath))
{
Directory.Delete(fl, true);
}
}
//删除这个目录下的所有文件
if (Directory.GetFiles(strPath).Length > 0)
{
foreach (string f in Directory.GetFiles(strPath))
{
System.IO.File.Delete(f);
}
}
Directory.Delete(strPath, true);
}
}
} |
using Discord;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrbCore.ContentStructures {
public class DirectMessageContent {
public IMessage MessageInfo { get; private set; }
public string MessageText { get; private set; }
public IUser User { get; private set; }
public IChannel Channel { get; private set; }
internal DirectMessageContent(IMessage messageInfo, string messageText, IUser user, IChannel channel) {
MessageInfo = messageInfo;
MessageText = messageText;
User = user;
Channel = channel;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace ScanINOUTVer2
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
private void frmLogin_Load(object sender, EventArgs e)
{
FileInfo f = new FileInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "//SIO//pwdSIO.txt");
if (!f.Exists)
{
StreamWriter sw = new StreamWriter(f.FullName);
sw.WriteLine("admin");
sw.Close();
sw.Dispose();
sw = null;
}
textBox1.Focus();
}
private void frmLogin_FormClosed(object sender, FormClosedEventArgs e)
{
if (this.Tag != "OK")
{
this.Tag = "close";
}
}
private void button3_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
MessageBox.Show("Please Enter your Password!");
return;
}
StreamReader sr = new StreamReader(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "//SIO//pwdSIO.txt");
string x = sr.ReadToEnd();
sr.Close();
sr.Dispose();
sr = null;
if (textBox1.Text.Trim() == x.Trim())
{
this.Tag = "OK";
this.Close();
}
else
{
MessageBox.Show("Invalid password!","Error",MessageBoxButtons.OK,MessageBoxIcon.Stop);
textBox1.Text = "";
textBox1.Focus();
}
}
}
}
|
using System.Collections.Generic;
namespace Uintra.Infrastructure.Extensions
{
public static class ListExtensions
{
public static List<T> ToListOfOne<T>(this T obj) =>
obj == null ? new List<T>() : new List<T> { obj };
}
} |
using System;
namespace Concrete2
{
public class Service
{
public void Execute()
{
Console.WriteLine("OK");
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI;
using StardewModdingAPI.Utilities;
using StardewValley;
using System;
using System.Diagnostics;
using TwilightShards.Common;
using TwilightShards.Stardew.Common;
using static ClimatesOfFerngillRebuild.Sprites;
namespace ClimatesOfFerngillRebuild
{
/// <summary> This tracks fog details </summary>
internal class FerngillFog : ISDVWeather
{
public event EventHandler<WeatherNotificationArgs> OnUpdateStatus;
public static Rectangle FogSource = new Rectangle(0, 0, 64, 64);
private Color FogColor = Color.White * 1.25f;
internal Icons Sheet;
/// <summary> The Current Fog Type </summary>
internal FogType CurrentFogType { get; set; }
private bool VerboseDebug { get; set; }
public bool BloodMoon { get; set; }
private IMonitor Monitor { get; set; }
/// <summary> The alpha attribute of the fog. </summary>
private float FogAlpha { get; set; }
/// <summary> Fog Position. For drawing. </summary>
private Vector2 FogPosition { get; set; }
/// <summary> Sets the expiration time of the fog </summary>
private SDVTime ExpirTime { get; set; }
private SDVTime BeginTime { get; set; }
public bool IsWeatherVisible => (CurrentFogType != FogType.None);
public string WeatherType => "Fog";
/// <summary> Returns the expiration time of fog. Note that this doesn't sanity check if the fog is even visible. </summary>
public SDVTime WeatherExpirationTime => (ExpirTime ?? new SDVTime(0600));
public SDVTime WeatherBeginTime => (BeginTime ?? new SDVTime(0600));
public bool WeatherInProgress
{
get
{
if (BeginTime is null || ExpirTime is null)
return false;
if (SDVTime.CurrentTime is null)
Console.WriteLine("CURRENT TIME IS NULL.");
if (WeatherBeginTime is null)
Console.WriteLine("WBT is null");
if (WeatherExpirationTime is null)
Console.WriteLine("WET is null");
return (SDVTime.CurrentTime >= WeatherBeginTime && SDVTime.CurrentTime <= WeatherExpirationTime);
}
}
/// <summary> Sets the fog expiration time. </summary>
/// <param name="t">The time for the fog to expire</param>
public void SetWeatherExpirationTime(SDVTime t) => ExpirTime = t;
public void SetWeatherBeginTime(SDVTime t) => BeginTime = t;
public SDVTimePeriods FogTimeSpan { get; set;}
private MersenneTwister Dice { get; set; }
private WeatherConfig ModConfig { get; set; }
private bool FadeOutFog { get; set; }
private bool FadeInFog { get; set; }
private Stopwatch FogElapsed { get; set; }
/// <summary> Default constructor. </summary>
internal FerngillFog(Icons Sheet, bool Verbose, IMonitor Monitor, MersenneTwister Dice, WeatherConfig config, SDVTimePeriods FogPeriod)
{
this.Sheet = Sheet;
CurrentFogType = FogType.None;
ExpirTime = null;
VerboseDebug = Verbose;
this.Monitor = Monitor;
this.BloodMoon = false;
this.Dice = Dice;
this.ModConfig = config;
this.FogTimeSpan = FogPeriod;
FogElapsed = new Stopwatch();
}
/// <summary> This function resets the fog for a new day. </summary>
public void OnNewDay()
{
Reset();
}
/// <summary> This function resets the fog. </summary>
public void Reset()
{
CurrentFogType = FogType.None;
BeginTime = null;
ExpirTime = null;
BloodMoon = false;
FogAlpha = 0f;
FadeOutFog = false;
FadeInFog = false;
FogElapsed.Reset();
}
/// <summary>Returns a string describing the fog type. </summary>
/// <param name="CurrentFogType">The type of the fog being looked at.</param>
/// <returns>The fog type</returns>
internal static string DescFogType(FogType CurrentFogType)
{
switch (CurrentFogType)
{
case FogType.None:
return "None";
case FogType.Blinding:
return "Blinding";
case FogType.Normal:
return "Normal";
default:
return "ERROR";
}
}
public void SecondUpdate()
{
}
/// <summary>This function creates the fog </summary>
public void CreateWeather()
{
this.FogAlpha = 1f;
//First, let's determine the type.
//... I am a dumb foxgirl. A really dumb one.
if (Dice.NextDoublePositive() <= .001)
CurrentFogType = FogType.Blinding;
else
CurrentFogType = FogType.Normal;
if (ModConfig.ShowLighterFog)
{
this.FogAlpha = .6f;
}
//now determine the fog expiration time
double FogChance = Dice.NextDoublePositive();
/*
* So we should rarely have full day fog, and it should on average burn off around 9am.
* So, the strongest odds should be 820 to 930, with sharply falling off odds until 1200. And then
* so, extremely rare odds for until 7pm and even rarer than midnight.
*/
if (FogTimeSpan == SDVTimePeriods.Morning)
{
BeginTime = new SDVTime(0600);
if (FogChance > 0 && FogChance < .25)
this.ExpirTime = new SDVTime(830);
else if (FogChance >= .25 && FogChance < .32)
this.ExpirTime = new SDVTime(900);
else if (FogChance >= .32 && FogChance < .41)
this.ExpirTime = new SDVTime(930);
else if (FogChance >= .41 && FogChance < .55)
this.ExpirTime = new SDVTime(950);
else if (FogChance >= .55 && FogChance < .7)
this.ExpirTime = new SDVTime(1040);
else if (FogChance >= .7 && FogChance < .8)
this.ExpirTime = new SDVTime(1120);
else if (FogChance >= .8 && FogChance < .9)
this.ExpirTime = new SDVTime(1200);
else if (FogChance >= .9 && FogChance < .95)
this.ExpirTime = new SDVTime(1220);
else if (FogChance >= .95 && FogChance < .98)
this.ExpirTime = new SDVTime(1300);
else if (FogChance >= .98 && FogChance < .99)
this.ExpirTime = new SDVTime(1910);
else if (FogChance >= .99)
this.ExpirTime = new SDVTime(2400);
}
else
{
BeginTime = new SDVTime(Game1.getModeratelyDarkTime());
BeginTime.AddTime(Dice.Next(-15, 90));
ExpirTime = new SDVTime(BeginTime);
ExpirTime.AddTime(Dice.Next(120, 310));
BeginTime.ClampToTenMinutes();
ExpirTime.ClampToTenMinutes();
}
if (SDVTime.CurrentTime >= BeginTime)
UpdateStatus(WeatherType, true);
}
public void EndWeather()
{
if (IsWeatherVisible)
{
ExpirTime = new SDVTime(SDVTime.CurrentTime - 10);
CurrentFogType = FogType.None;
UpdateStatus(WeatherType, false);
}
}
public void SetWeatherTime(SDVTime begin, SDVTime end)
{
BeginTime = new SDVTime(begin);
ExpirTime = new SDVTime(end);
}
public override string ToString()
{
return $"Fog Weather from {BeginTime} to {ExpirTime}. Visible: {IsWeatherVisible}. Alpha: {FogAlpha}.";
}
public void UpdateWeather()
{
if (WeatherBeginTime is null || WeatherExpirationTime is null)
return;
if (WeatherInProgress && !IsWeatherVisible)
{
CurrentFogType = FogType.Normal;
FadeInFog = true;
FogElapsed.Start();
UpdateStatus(WeatherType, true);
}
if (WeatherExpirationTime <= SDVTime.CurrentTime && IsWeatherVisible)
{
FadeOutFog = true;
FogElapsed.Start();
UpdateStatus(WeatherType, false);
}
}
internal void SetEveningFog()
{
SDVTime STime, ETime;
STime = new SDVTime(Game1.getStartingToGetDarkTime());
STime.AddTime(Dice.Next(-25, 80));
ETime = new SDVTime(STime);
ETime.AddTime(Dice.Next(120, 310));
STime.ClampToTenMinutes();
ETime.ClampToTenMinutes();
this.SetWeatherTime(STime, ETime);
}
public void DrawWeather()
{
if (IsWeatherVisible)
{
if (CurrentFogType != FogType.Blinding)
{
//Game1.outdoorLight = fogLight;
Texture2D fogTexture = null;
Vector2 position = new Vector2();
float num1 = -64* Game1.pixelZoom + (int)(FogPosition.X % (double)(64 * Game1.pixelZoom));
while (num1 < (double)Game1.graphics.GraphicsDevice.Viewport.Width)
{
float num2 = -64 * Game1.pixelZoom + (int)(FogPosition.Y % (double)(64 * Game1.pixelZoom));
while ((double)num2 < Game1.graphics.GraphicsDevice.Viewport.Height)
{
position.X = (int)num1;
position.Y = (int)num2;
fogTexture = Sheet.FogTexture;
if (Game1.isStartingToGetDarkOut())
{
FogColor = Color.LightBlue;
}
if (BloodMoon)
{
FogColor = Color.DarkRed;
}
Game1.spriteBatch.Draw(fogTexture, position, new Microsoft.Xna.Framework.Rectangle?
(FogSource), FogAlpha > 0.0 ? FogColor * FogAlpha : Color.Black * 0.95f, 0.0f, Vector2.Zero, Game1.pixelZoom + 1f / 1000f, SpriteEffects.None, 1f);
num2 += 64 * Game1.pixelZoom;
}
num1 += 64 * Game1.pixelZoom;
}
}
}
}
public void UpdateStatus(string weather, bool status)
{
if (OnUpdateStatus == null) return;
WeatherNotificationArgs args = new WeatherNotificationArgs(weather, status);
OnUpdateStatus(this, args);
}
public string FogDescription(double fogRoll, double fogChance)
{
return $"With roll {fogRoll.ToString("N3")} against {fogChance}, there will be fog today from {WeatherBeginTime} to {WeatherExpirationTime} with type {CurrentFogType}";
}
public void MoveWeather()
{
float FogFadeTime = 2690f;
if (FadeOutFog)
{
// we want to fade out the fog over 3 or so seconds, so we need to process a fade from 100% to 45%
// So, 3000ms for 55% or 54.45 repeating. But this is super fast....
// let's try 955ms.. or 1345..
// or 2690.. so no longer 3s. :<
FogAlpha = 1 - (FogElapsed.ElapsedMilliseconds / FogFadeTime);
if (FogAlpha <= 0)
{
FogAlpha = 0;
CurrentFogType = FogType.None;
FadeOutFog = false;
FogElapsed.Stop();
FogElapsed.Reset();
}
}
if (FadeInFog)
{
//as above, but the reverse.
FogAlpha = (FogElapsed.ElapsedMilliseconds / FogFadeTime);
if (FogAlpha >= 1)
{
FogAlpha = 1;
FadeInFog = false;
FogElapsed.Stop();
FogElapsed.Reset();
}
}
if (IsWeatherVisible)
{
//Game1.outdoorLight = fogLight;
this.FogPosition = Game1.updateFloatingObjectPositionForMovement(FogPosition,
new Vector2(Game1.viewport.X, Game1.viewport.Y), Game1.previousViewportPosition, -1f);
FogPosition = new Vector2((FogPosition.X + 0.5f) % (64 * Game1.pixelZoom),
(FogPosition.Y + 0.5f) % (64 * Game1.pixelZoom));
}
}
}
} |
using System;
using System.Collections.Generic;
namespace ServiceDeskSVC.DataAccess.Models
{
public partial class AssetManager_AssetStatus
{
public AssetManager_AssetStatus()
{
this.AssetManager_Hardware = new List<AssetManager_Hardware>();
}
public int Id { get; set; }
public string Name { get; set; }
public System.DateTime CreatedDate { get; set; }
public int CreatedById { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public Nullable<int> ModifiedById { get; set; }
public virtual ServiceDesk_Users ServiceDesk_Users { get; set; }
public virtual ServiceDesk_Users ServiceDesk_Users1 { get; set; }
public virtual ICollection<AssetManager_Hardware> AssetManager_Hardware { get; set; }
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using FiiiCoin.Wallet.Win.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FiiiCoin.Wallet.Win.Models
{
public class ReceiveInfo : NotifyBase
{
private string _tag;
public string Tag
{
get { return _tag; }
set { _tag = value; RaisePropertyChanged("Tag"); }
}
private string _comment;
public string Comment
{
get { return _comment; }
set { _comment = value; RaisePropertyChanged("Comment"); }
}
private long _amount;
public long Amount
{
get { return _amount; }
set
{
_amount = value;
_amount_Double = _amount / Math.Pow(10, 8);
RaisePropertyChanged("Amount_Double");
RaisePropertyChanged("Amount");
}
}
private string _account;
public string Account
{
get { return _account; }
set { _account = value; RaisePropertyChanged("Account"); }
}
private double _amount_Double;
public double Amount_Double
{
get { return _amount_Double; }
set
{
if (_amount_Double == value)
return;
_amount_Double = value;
_amount = Convert.ToInt64(_amount_Double * Math.Pow(10, 8));
RaisePropertyChanged("Amount_Double");
RaisePropertyChanged("Amount");
}
}
private string _amount_Str;
public string Amount_Str
{
get { return _amount_Str; }
set
{
if (!string.IsNullOrEmpty(value))
{
Amount_Double = double.Parse(value);
}
else
{
Amount_Double = 0;
}
_amount_Str = value;
RaisePropertyChanged("Amount_Str");
RaisePropertyChanged("Amount_Double");
RaisePropertyChanged("Amount");
}
}
}
public enum ReceiveClearType
{
All,
Tag,
Comment
}
}
|
using System.Collections.Generic;
using System.Linq;
using Entoarox.Framework.Core;
namespace Entoarox.Framework
{
public class EntoaroxFrameworkAPI
{
/*********
** Fields
*********/
private static PlayerModifier Modifier;
private static readonly Dictionary<string, int> RunBoosts = new Dictionary<string, int>();
private static readonly Dictionary<string, int> WalkBoosts = new Dictionary<string, int>();
/*********
** Public methods
*********/
public void AddBoost(string id, int amount, bool forWalking = true, bool forRunning = true)
{
if (forWalking)
EntoaroxFrameworkAPI.WalkBoosts[id] = amount;
if (forRunning)
EntoaroxFrameworkAPI.RunBoosts[id] = amount;
EntoaroxFrameworkAPI.Recalculate();
}
public void RemoveBoost(string id)
{
EntoaroxFrameworkAPI.WalkBoosts.Remove(id);
EntoaroxFrameworkAPI.RunBoosts.Remove(id);
EntoaroxFrameworkAPI.Recalculate();
}
/*********
** Protected methods
*********/
private static void Recalculate()
{
if (EntoaroxFrameworkAPI.Modifier == null)
EntoaroxFrameworkAPI.Modifier = new PlayerModifier();
EntoaroxFrameworkMod.SHelper.Player().Modifiers.Remove(EntoaroxFrameworkAPI.Modifier);
EntoaroxFrameworkAPI.Modifier.WalkSpeedModifier = EntoaroxFrameworkAPI.WalkBoosts.Values.Aggregate((total, next) => total + next);
EntoaroxFrameworkAPI.Modifier.RunSpeedModifier = EntoaroxFrameworkAPI.RunBoosts.Values.Aggregate((total, next) => total + next);
EntoaroxFrameworkMod.SHelper.Player().Modifiers.Add(EntoaroxFrameworkAPI.Modifier);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Realms;
namespace RealmDB
{
class Program
{
static void Main(string[] args)
{
var realm = Realm.GetInstance();
var operations = new CRUD(realm);
var menu = new Menu(realm);
realm.Write( () => realm.RemoveAll());
var p1 = new Player() { Name = "Jan", Surname = "Nowak", BirthYear = 2000, Position = "Bramkarz" };
var p2 = new Player() { Name = "Piotr", Surname = "Kowal", BirthYear = 1999, Position = "Obrońca" };
IList<Player> players = new List<Player> { p1, p2 };
IList<Player> onePlayer = new List<Player> { p2 };
var club1 = new Club() { Id = 1, Name = "Pierwszy klub", Budget = 30000 };
var club2 = new Club() { Id = 2, Name = "Drugi klub", Budget = 10000};
club1.Players.Add(p1);
club1.Players.Add(p2);
club2.Players.Add(p2);
// Update and persist objects with a thread-safe transaction
realm.Write(() =>
{
realm.Add(club1);
realm.Add(club2);
});
menu.Run();
//operations.PrintAllData(realm);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
public class SetVolume : MonoBehaviour {
[SerializeField] AudioMixer mixer;
[SerializeField] string mixerReferenceName;
public void SetLevel (float sliderValue)
{
mixer.SetFloat(mixerReferenceName, Mathf.Log10(sliderValue) * 20);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Cw3.DTO
{
public class LoginResponseDTO
{
public string id;
public string name;
public string role;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PickupKey : MonoBehaviour
{
public KeyAmount Keys;
public GameObject Canvas;
private void Start()
{
Canvas = GameObject.FindGameObjectWithTag("Canvas");
Keys = Canvas.GetComponentInChildren<KeyAmount>();
}
//Activates the AddKey method in the KeyAmount script and destroys the key whenever the player is touching the keys trigger and is pressing e
private void OnTriggerStay2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
Keys.AddKey();
Destroy(gameObject);
}
}
}
|
namespace PizzaMore.Utility
{
using System;
using System.IO;
public static class Logger
{
public static void Log(string text)
{
File.AppendAllText("../PizzaLab/log.txt", text + Environment.NewLine);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace CurrencyCsvParser
{
public class Currency
{
[Key]
public Guid Guid { get; set; }
[Required]
public string CurrencyName { get; set; }
[Required]
public decimal SellPrice { get; set; }
[Required]
public decimal BuyPrice { get; set; }
[Required]
public decimal VolumeBtc { get; set; }
[Required]
public decimal VolumeCurrency { get; set; }
[Required]
public decimal High { get; set; }
[Required]
public decimal Low { get; set; }
[Required]
public DateTime DateTime { get; set; }
}
}
|
using InoDrive.Domain.Contexts;
using InoDrive.Domain.Entities;
using InoDrive.Domain.Helpers;
using InoDrive.Domain.Models;
using InoDrive.Domain.Models.InputModels;
using InoDrive.Domain.Models.OutputModels;
using InoDrive.Domain.Repositories.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InoDrive.Domain.Repositories.Concrete
{
public class BidsRepository : IBidsRepository
{
public BidsRepository(InoDriveContext dataContext)
{
_ctx = dataContext;
}
private InoDriveContext _ctx;
#region Section of requests for updating counters, bids
public Int32 GetCountOfOwnBids(ShortUserModel model)
{
var user = _ctx.Users.FirstOrDefault(u => u.Id == model.UserId);
if (user != null)
{
return user.Bids.Count(b => b.IsAccepted != null && !b.IsWatchedBySender);
}
else
{
throw new Exception(AppConstants.USER_NOT_FOUND);
}
}
public Int32 GetCountOfAssignedBids(ShortUserModel model)
{
var user = _ctx.Users.FirstOrDefault(u => u.Id == model.UserId);
if (user != null)
{
return user.Trips.Where(t => !t.IsDeleted).SelectMany(t => t.Bids).Count(b => b.IsAccepted == null);
}
else
{
throw new Exception(AppConstants.USER_NOT_FOUND);
}
}
public List<OutputMyBidModel> GetUpdatedOwnBids(ShortUserModel model)
{
var user = _ctx.Users.FirstOrDefault(u => u.Id == model.UserId);
if (user != null)
{
var bids = user.Bids.Where(b => b.IsAccepted != null && !b.IsWatchedBySender).Select(n => new OutputMyBidModel
{
BidId = n.BidId,
IsAccepted = n.IsAccepted ?? false
}).ToList<OutputMyBidModel>();
return bids;
}
else
{
throw new Exception(AppConstants.USER_NOT_FOUND);
}
}
public List<OutputBidForMyTripModel> GetUpdatedAssignedBids(InputPageSortModel<Int32> model)
{
var user = _ctx.Users.FirstOrDefault(u => u.Id == model.UserId);
if (user != null)
{
IEnumerable<Bid> bids;
if (model.FromId != 0)
{
bids =
user.
Trips.
SelectMany(b => b.Bids).
OrderByDescending(b => b.CreationDate).
TakeWhile(b => b.BidId != model.FromId);
}
else
{
bids =
user.
Trips.
SelectMany(b => b.Bids).
OrderByDescending(b => b.CreationDate);
}
var result = bids.Select(b => new OutputBidForMyTripModel
{
FirstName = b.User.FirstName,
LastName = b.User.LastName,
BidId = b.BidId,
UserClaimed = new UserModel
{
UserId = b.UserId,
FirstName = b.User.FirstName,
LastName = b.User.LastName
},
TripId = b.TripId,
LeavingDate = b.Trip.LeavingDate,
CreationDate = b.CreationDate,
Pay = b.Trip.Pay,
OriginPlace = new PlaceModel
{
PlaceId = b.Trip.OriginPlaceId,
Name = b.Trip.OriginPlace.Name
},
DestinationPlace = new PlaceModel
{
PlaceId = b.Trip.DestinationPlaceId,
Name = b.Trip.DestinationPlace.Name
},
TotalPlaces = b.Trip.PeopleCount,
FreePlaces = b.Trip.PeopleCount - b.Trip.Bids.Count(bb => bb.IsAccepted == true),
}).ToList<OutputBidForMyTripModel>();
return result;
}
else
{
throw new Exception(AppConstants.USER_NOT_FOUND);
}
}
#endregion
#region Section of main requests for select bids
public OutputList<OutputBidForMyTripModel> GetBidsForMyTrips(InputPageSortModel<Int32> model)
{
var result = new OutputList<OutputBidForMyTripModel>();
var countExcluded = Math.Max(model.CountExcluded, 0);
var user = _ctx.Users.FirstOrDefault(u => u.Id == model.UserId);
if (user != null)
{
var page = Math.Max(model.Page, 1);
IQueryable<Bid> bids;
if (model.FromId != null && model.FromId != 0)
{
bids =
user.
Trips.
Where(t => !t.IsDeleted).
SelectMany(b => b.Bids).
OrderByDescending(b => b.CreationDate).
SkipWhile(b => b.BidId != model.FromId).Where(b => b.IsAccepted == null).AsQueryable();
}
else
{
bids =
user.
Trips.
Where(t => !t.IsDeleted).
SelectMany(b => b.Bids).
Where(b => b.IsAccepted == null).
OrderByDescending(b => b.CreationDate).AsQueryable();
}
var totalCount = bids.Count();
if (totalCount != 0)
{
result.TotalCount = totalCount;
var resultBids = bids.Select(b => new OutputBidForMyTripModel
{
FirstName = b.User.FirstName,
LastName = b.User.LastName,
BidId = b.BidId,
UserClaimed = new UserModel
{
UserId = b.UserId,
FirstName = b.User.FirstName,
LastName = b.User.LastName
},
TripId = b.TripId,
LeavingDate = b.Trip.LeavingDate,
CreationDate = b.CreationDate,
Pay = b.Trip.Pay,
OriginPlace = new PlaceModel
{
PlaceId = b.Trip.OriginPlaceId,
Name = b.Trip.OriginPlace.Name
},
DestinationPlace = new PlaceModel
{
PlaceId = b.Trip.DestinationPlaceId,
Name = b.Trip.DestinationPlace.Name
},
TotalPlaces = b.Trip.PeopleCount,
FreePlaces = b.Trip.PeopleCount - b.Trip.Bids.Count(bb => bb.IsAccepted == true),
})
.Skip(model.PerPage * (page - 1) - countExcluded).Take(model.PerPage)
.ToList<OutputBidForMyTripModel>();
result.Results = resultBids;
}
return result;
}
else
{
throw new Exception(AppConstants.USER_NOT_FOUND);
}
}
public OutputList<OutputMyBidModel> GetMyBids(InputPageSortModel<Int32> model)
{
var result = new OutputList<OutputMyBidModel>();
var user = _ctx.Users.FirstOrDefault(u => u.Id == model.UserId);
if (user != null)
{
var page = Math.Max(model.Page, 1);
List<Bid> waitedBids;
if (model.ShowEnded)
{
waitedBids = user.Bids.ToList<Bid>();
}
else
{
waitedBids = user.Bids.Where(b => b.Trip.EndDate >= DateTimeOffset.Now && !b.Trip.IsDeleted && b.IsAccepted == null).ToList<Bid>();
}
var totalCount = waitedBids.Count();
if (totalCount != 0)
{
result.TotalCount = totalCount;
var resultBids = waitedBids.Select(b => new OutputMyBidModel
{
BidId = b.BidId,
UserOwner = new UserModel
{
UserId = b.Trip.UserId,
FirstName = b.Trip.User.FirstName,
LastName = b.Trip.User.LastName
},
TripId = b.TripId,
LeavingDate = b.Trip.LeavingDate,
CreationDate = b.CreationDate,
OriginPlace = new PlaceModel
{
PlaceId = b.Trip.OriginPlaceId,
Name = b.Trip.OriginPlace.Name
},
DestinationPlace = new PlaceModel
{
PlaceId = b.Trip.DestinationPlaceId,
Name = b.Trip.DestinationPlace.Name
},
TotalPlaces = b.Trip.PeopleCount,
FreePlaces = b.Trip.PeopleCount - b.Trip.Bids.Count(bb => bb.IsAccepted == true),
IsAccepted = b.IsAccepted,
IsWatched = b.IsWatchedBySender,
WasTripDeleted = b.Trip.IsDeleted,
IsEnded = b.Trip.EndDate < DateTimeOffset.Now,
IsDeleted = b.Trip.IsDeleted
})
.OrderByDescending(d => d.CreationDate)
.Skip(model.PerPage * (page - 1)).Take(model.PerPage)
.ToList<OutputMyBidModel>();
result.Results = resultBids;
}
return result;
}
else
{
throw new Exception(AppConstants.USER_NOT_FOUND);
}
}
#endregion
#region Add or update some bids entities
public void AddBid(InputManageBidModel model)
{
var user = _ctx.Users.FirstOrDefault(u => u.Id == model.UserId);
if (user != null)
{
var trip = _ctx.Trips.FirstOrDefault(t => t.TripId == model.TripId);
if (trip != null)
{
if (trip.IsDeleted)
{
throw new Exception("Нельзя подать заявку на эту поездку, т.к. она была удалена!");
}
if (trip.LeavingDate.Date < DateTime.Now.Date)
{
throw new Exception("Нельзя подать заявку на эту поездку, т.к. поездка уже завершена!");
}
if (trip.UserId != model.UserId)
{
var bid = trip.Bids.FirstOrDefault(b => b.UserId == model.UserId);
if (bid == null)
{
bid = new Bid
{
CreationDate = DateTimeOffset.Now,
UserId = model.UserId
};
trip.Bids.Add(bid);
_ctx.SaveChanges();
}
else
{
throw new Exception("Вы уже подали заявку на эту поездку!");
}
}
else
{
throw new Exception("Вы не можете подать заявку на свою же поездку!");
}
}
else
{
throw new Exception(AppConstants.TRIP_NOT_FOUND);
}
}
else
{
throw new Exception(AppConstants.USER_NOT_FOUND);
}
}
public void AcceptBid(InputManageBidModel model)
{
var user = _ctx.Users.FirstOrDefault(u => u.Id == model.UserOwnerId);
if (user != null)
{
var trip = user.Trips.FirstOrDefault(t => t.TripId == model.TripId);
if (trip != null)
{
var bid = trip.Bids.FirstOrDefault(b => b.UserId == model.UserClaimedId);
if (bid != null)
{
var freePlaces = bid.Trip.PeopleCount - bid.Trip.Bids.Count(bb => bb.IsAccepted == true);
if (freePlaces > 0)
{
bid.IsAccepted = true;
_ctx.SaveChanges();
}
else
{
throw new Exception("Вы не можете принять заявку, т.к. уже не осталось свободных мест!");
}
}
else
{
throw new Exception("Вы не можете принять несуществующую заявку!");
}
}
else
{
throw new Exception(AppConstants.TRIP_NOT_FOUND);
}
}
else
{
throw new Exception(AppConstants.USER_NOT_FOUND);
}
}
public void RejectBid(InputManageBidModel model)
{
var user = _ctx.Users.FirstOrDefault(u => u.Id == model.UserOwnerId);
if (user != null)
{
var trip = user.Trips.FirstOrDefault(t => t.TripId == model.TripId);
if (trip != null)
{
var bid = trip.Bids.FirstOrDefault(b => b.UserId == model.UserClaimedId);
if (bid != null)
{
bid.IsAccepted = false;
_ctx.SaveChanges();
}
else
{
throw new Exception("Вы не можете отклонить несуществующую заявку!");
}
}
else
{
throw new Exception(AppConstants.TRIP_NOT_FOUND);
}
}
else
{
throw new Exception(AppConstants.USER_NOT_FOUND);
}
}
public void WatchBid(InputManageBidModel model)
{
var user = _ctx.Users.FirstOrDefault(u => u.Id == model.UserOwnerId);
if (user != null)
{
var bid = user.Bids.FirstOrDefault(b => b.BidId == model.BidId);
if (bid != null)
{
bid.IsWatchedBySender = true;
_ctx.SaveChanges();
}
else
{
throw new Exception("У этого пользователя нет такой заявки!");
}
}
else
{
throw new Exception(AppConstants.USER_NOT_FOUND);
}
}
#endregion
}
}
|
namespace BettingSystem.Application.Identity.Commands.ChangePassword
{
public class ChangePasswordRequestModel
{
public ChangePasswordRequestModel(
string userId,
string currentPassword,
string newPassword)
{
this.UserId = userId;
this.CurrentPassword = currentPassword;
this.NewPassword = newPassword;
}
public string UserId { get; }
public string CurrentPassword { get; }
public string NewPassword { get; }
}
}
|
using System;
using System.Linq;
using System.Runtime.InteropServices;
using WindowsDesktop.Interop;
namespace SylphyHorn.Services
{
public abstract class ImageFormatSupportDetector
{
private bool? _isSupported = null;
public bool IsSupported
{
get
{
if (!this._isSupported.HasValue)
{
this._isSupported = this.GetValue();
}
return this._isSupported.Value;
}
}
public abstract string[] Extensions { get; }
public abstract string FileType { get; }
public abstract bool GetValue();
}
public abstract class ClsidImageFormatSupportDetector : ImageFormatSupportDetector
{
public abstract Guid CLSID { get; }
public override bool GetValue()
{
try
{
var decoderType = Type.GetTypeFromCLSID(this.CLSID);
var decoder = Activator.CreateInstance(decoderType);
return true;
}
catch (COMException ex) when (ex.Match(HResult.REGDB_E_CLASSNOTREG))
{
return false;
}
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using TMPro;
using DG.Tweening;
public class EffectsbarComponent : MonoBehaviour
{
// public Slider slider;
// public int healthMax;
// public int health;
private GameObject panel;
private GameObject condi1;
private GameObject condi1Stack;
private TextMeshProUGUI condi1StackLabel;
private GameObject condi2;
private GameObject condi2Stack;
private TextMeshProUGUI condi2StackLabel;
private GameObject cc1;
private GameObject cc1Stack;
private TextMeshProUGUI cc1StackLabel;
private GameObject cc2;
private GameObject cc2Stack;
private TextMeshProUGUI cc2StackLabel;
private GameObject boon1;
private GameObject boon1Stack;
private TextMeshProUGUI boon1StackLabel;
private GameObject boon2;
private GameObject boon2Stack;
private TextMeshProUGUI boon2StackLabel;
void Start()
{
// slider = gameObject.GetComponent<Slider>();
// slider.wholeNumbers = true;
panel = transform.GetChild(0).gameObject;
// Debug.Log("* got panel " + panel);
// panel.transform.Find("condi-1")
Transform[] allChildren = panel.GetComponentsInChildren<Transform>();
int count = 1;
// assign slot refs
foreach (Transform child in allChildren)
{
// only track slots, not slot children
if (child.GetComponent<EffectSlotComponent>())
{
// Debug.Log("<color=orange>" + count + " / " + child + "</color>");
switch(count)
{
case 1:
condi1 = child.gameObject;
condi1Stack = child.gameObject.transform.GetChild(0).gameObject;
condi1StackLabel = condi1Stack.transform.GetChild(1).gameObject.GetComponent<TextMeshProUGUI>();
break;
case 2:
condi2 = child.gameObject;
condi2Stack = child.gameObject.transform.GetChild(0).gameObject;
condi2StackLabel = condi2Stack.transform.GetChild(1).gameObject.GetComponent<TextMeshProUGUI>();
break;
case 3:
cc1 = child.gameObject;
cc1Stack = child.gameObject.transform.GetChild(0).gameObject;
cc1StackLabel = cc1Stack.transform.GetChild(1).gameObject.GetComponent<TextMeshProUGUI>();
break;
case 4:
cc2 = child.gameObject;
cc2Stack = child.gameObject.transform.GetChild(0).gameObject;
cc2StackLabel = cc2Stack.transform.GetChild(1).gameObject.GetComponent<TextMeshProUGUI>();
break;
case 5:
boon1 = child.gameObject;
boon1Stack = child.gameObject.transform.GetChild(0).gameObject;
boon1StackLabel = boon1Stack.transform.GetChild(1).gameObject.GetComponent<TextMeshProUGUI>();
break;
case 6:
boon2 = child.gameObject;
boon2Stack = child.gameObject.transform.GetChild(0).gameObject;
boon2StackLabel = boon2Stack.transform.GetChild(1).gameObject.GetComponent<TextMeshProUGUI>();
break;
}
count++;
}
}
}
private Sprite GetSpriteByImageString(string image)
{
return GameManager.instance.assetBundleCombat.LoadAsset<Sprite>(image);
}
public GameObject GetSlotByModifier(int slot, int modifier)
{
GameObject go = null;
switch(modifier)
{
case EffectVO.EFFECT_MODIFIER_CONDITION:
if (slot == 1)
go = condi1;
else go = condi2;
break;
case EffectVO.EFFECT_MODIFIER_CC:
if (slot == 1)
go = cc1;
else go = cc2;
break;
case EffectVO.EFFECT_MODIFIER_BOON:
if (slot == 1)
go = boon1;
else go = boon1;
break;
}
return go;
}
public GameObject GetStackByModifier(int slot, int modifier)
{
GameObject go = null;
switch (modifier)
{
case EffectVO.EFFECT_MODIFIER_CONDITION:
if (slot == 1)
go = condi1Stack;
else go = condi2Stack;
break;
case EffectVO.EFFECT_MODIFIER_CC:
if (slot == 1)
go = cc1Stack;
else go = cc2Stack;
break;
case EffectVO.EFFECT_MODIFIER_BOON:
if (slot == 1)
go = boon1Stack;
else go = boon2Stack;
break;
}
return go;
}
public TextMeshProUGUI GetStackLabelByModifier(int slot, int modifier)
{
TextMeshProUGUI go = null;
switch (modifier)
{
case EffectVO.EFFECT_MODIFIER_CONDITION:
if (slot == 1)
go = condi1StackLabel;
else go = condi2StackLabel;
break;
case EffectVO.EFFECT_MODIFIER_CC:
if (slot == 1)
go = cc1StackLabel;
else go = cc2StackLabel;
break;
case EffectVO.EFFECT_MODIFIER_BOON:
if (slot == 1)
go = boon1StackLabel;
else go = boon1StackLabel;
break;
}
return go;
}
public void UpdateEffectsBar(int type, EffectVO vo, List<EffectVO> list)
{
// Debug.Log("<color=orange>== EffectsbarComponent.UpdateEffectsBar ==</color>");
// Debug.Log("<color=orange>type " + type + " / " + list.Count + "</color>");
GameObject slot1 = GetSlotByModifier(1, vo.effectModifier);
GameObject slot2 = GetSlotByModifier(2, vo.effectModifier);
GameObject stack1 = GetStackByModifier(1, vo.effectModifier);
GameObject stack2 = GetStackByModifier(2, vo.effectModifier);
TextMeshProUGUI stack1Label = GetStackLabelByModifier(1, vo.effectModifier);
TextMeshProUGUI stack2Label = GetStackLabelByModifier(2, vo.effectModifier);
EffectSlotComponent effectComponent1 = slot1.GetComponent<EffectSlotComponent>();
EffectSlotComponent effectComponent2 = slot2.GetComponent<EffectSlotComponent>();
Image img1;
Image img2;
GameObject stackView1;
GameObject stackView2;
if (list.Count > 0)
{
img1 = slot1.GetComponent<Image>();
// stackView1 = slot1.transform.GetChild(0);
// if (slot1.GetComponent<Image>().color.a == 0)
effectComponent1.effect = list[0];
switch(type)
{
case EffectVO.EFFECT_UPDATE_TYPE_ADD:
img1.color = new Color(img1.color.r, img1.color.g, img1.color.b, 1f);
img1.sprite = GetSpriteByImageString(list[0].image);
break;
case EffectVO.EFFECT_UPDATE_TYPE_REMOVE:
img1.color = new Color(img1.color.r, img1.color.g, img1.color.b, 0f);
img1.sprite = null;
stack1.SetActive(false);
break;
case EffectVO.EFFECT_UPDATE_TYPE_UPDATE:
break;
}
int activeStacks = list[0].GetNumberOfActiveStacks(true);
Debug.Log("<color=orange>" + list[0].label + " effectStacks.Count " + activeStacks + "</color>");
// if (list[0].effectStacks.Count > 1)
if (activeStacks > 1)
{
stack1.SetActive(true);
// stack1Label.gameObject.SetActive(true);
stack1Label.text = activeStacks.ToString();
}
else
{
stack1.SetActive(false);
// stack1Label.gameObject.SetActive(false);
}
// if only 1 stack, hide stack 2
if (list.Count == 1)
stack2.SetActive(false);
}
if (list.Count == 2)
{
img2 = slot2.GetComponent<Image>();
// if (slot2.GetComponent<Image>().color.a == 0)
img2.color = new Color(img2.color.r, img2.color.g, img2.color.b, 1f);
effectComponent2.effect = list[1];
img2.sprite = GetSpriteByImageString(list[1].image);
if (list[1].effectStacks.Count > 1)
{
stack2.SetActive(true);
// stack2Label.gameObject.SetActive(true);
stack2Label.text = list[1].effectStacks.Count.ToString();
}
else
{
stack2.SetActive(false);
// stack2Label.gameObject.SetActive(false);
}
}
if (list.Count == 0) // hide all stacks
{
stack1.SetActive(false);
stack2.SetActive(false);
}
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using SimpleJSON;
public class LocationManager : MonoBehaviour {
private UIBubblePopupManager UIBPM;
public GameObject map;
public Texture2D forMarker;
//public GameObject spawn;
public double lat=0;
public double lon =0;
public double lastlat =0,lastlon=0;
public GameObject latText;
public GameObject lonText;
public Texture2D[] markerImagelist;
// Use this for initialization
void Start () {
UIBPM = map.GetComponent<UIBubblePopupManager>();
Input.location.Start (); // enable the mobile device GPS
if (Input.location.isEnabledByUser) { // if mobile device GPS is enabled
lat = Input.location.lastData.latitude; //get GPS Data
lon = Input.location.lastData.longitude;
map.GetComponent<OnlineMaps> ().SetPosition(lon,lat);
//map.GetComponent<OnlineMaps> ().centerLocation.longitude = lon;
}
StartCoroutine(GetMarkers());
StartCoroutine(GetMarkers5KM());
}
// Update is called once per frame
void Update () {
// <---------Mobile Device Code----------->
if (Input.location.isEnabledByUser) {
lat = Input.location.lastData.latitude;
lon = Input.location.lastData.longitude;
if (lastlat != lat || lastlon != lon) {
map.GetComponent<OnlineMaps> ().SetPosition(lon,lat);
// map.GetComponent<OnlineMaps> ().centerLocation.longitude = lon;
latText.GetComponent<Text> ().text = "Lat" + lat.ToString ();
lonText.GetComponent<Text> ().text = "Lon" + lon.ToString ();
//spawn.GetComponent<Spawn> ().updateMonstersPosition (lon, lat);
//Add above after you complete spawn part
// map.GetComponent<GoogleMap> ().Refresh ();
// map.GetComponent<GoogleMap>().Mark();
}
lastlat = lat;
lastlon = lon;
}
// <---------Mobile Device Code----------->
// <---------PC Test Code----------->
if (lastlat != lat || lastlon != lon) {
map.GetComponent<OnlineMaps> ().SetPosition(lon,lat);
// map.GetComponent<GoogleMap> ().centerLocation.longitude = lon;
latText.GetComponent<Text> ().text = "Lat" + lat.ToString ();
lonText.GetComponent<Text> ().text = "Lon" + lon.ToString ();
// spawn.GetComponent<Spawn> ().updateMonstersPosition (lon, lat);
// map.GetComponent<GoogleMap> ().Refresh ();
// map.GetComponent<GoogleMap>().Mark();
}
lastlat = lat;
lastlon = lon;
// <---------PC Test Code----------->
}
IEnumerator GetMarkers(){
string url = "http://139.59.100.192/PH/" + "all";
WWWForm form = new WWWForm ();
form.AddField ("ID", PlayerPrefs.GetString ("ID"));
WWW www = new WWW (url, form);
yield return www;
Debug.Log (www.text);
if (www.error == null) {
var jsonString = JSON.Parse (www.text);
int count = int.Parse (jsonString ["count"]);
PlayerPrefs.SetString ("FOR_CONVERTING", jsonString ["code"]);
if (PlayerPrefs.GetString ("FOR_CONVERTING") == "0") {
//Array.Resize (ref GetComponent<GoogleMap> ().markers [0].locations ,count);
//yield return new WaitForSeconds (1f);
for (int x = 0; x < int.Parse (jsonString ["count"]); x++) {
//GetComponent<GoogleMap> ().markers [0].locations [x].address = jsonString["data"][x]["namatempat"];
// GetComponent<GoogleMap> ().markers [0].locations [x].latitude = double.Parse(jsonString["data"][x]["latitude"]);
// GetComponent<GoogleMap> ().markers [0].locations [x].longitude = double.Parse(jsonString["data"][x]["longitude"]);
// abc+="|"+jsonString["data"][x]["latitude"]+","+jsonString["data"][x]["longitude"];
if(jsonString["data"][x]["longitude"]!=null)
{
double longitudef = double.Parse(jsonString["data"][x]["longitude"]);
double latitudef = double.Parse(jsonString["data"][x]["latitude"]);
OnlineMapsMarker marker = OnlineMaps.instance.AddMarker(longitudef, latitudef);
marker.texture = markerImagelist[3];
marker.scale = .7f;
}
}
yield return new WaitForSeconds (.1f);
// StartCoroutine (requesting ());
}
}
}
IEnumerator GetMarkers5KM(){
string url = "http://139.59.100.192/PH/" + "all5KM";
WWWForm form = new WWWForm ();
form.AddField ("PID", PlayerPrefs.GetString ("ID"));
form.AddField ("latitude", lastlat.ToString());
form.AddField ("longitude", lastlon.ToString());
WWW www = new WWW (url, form);
yield return www;
Debug.Log (www.text);
if (www.error == null) {
var jsonString = JSON.Parse (www.text);
int count = int.Parse (jsonString ["count"]);
PlayerPrefs.SetString ("FOR_CONVERTING", jsonString ["code"]);
if (PlayerPrefs.GetString ("FOR_CONVERTING") == "0") {
//Array.Resize (ref GetComponent<GoogleMap> ().markers [0].locations ,count);
//yield return new WaitForSeconds (1f);
for (int x = 0; x < int.Parse (jsonString ["count"]); x++) {
//GetComponent<GoogleMap> ().markers [0].locations [x].address = jsonString["data"][x]["namatempat"];
// GetComponent<GoogleMap> ().markers [0].locations [x].latitude = double.Parse(jsonString["data"][x]["latitude"]);
// GetComponent<GoogleMap> ().markers [0].locations [x].longitude = double.Parse(jsonString["data"][x]["longitude"]);
// abc+="|"+jsonString["data"][x]["latitude"]+","+jsonString["data"][x]["longitude"];
if(jsonString["data"][x]["lot"]!=null)
{
// int codeTexture = int.Parse(jsonString["data"][x]["codetexture"]);
double longitudef = double.Parse(jsonString["data"][x]["lot"]);
double latitudef = double.Parse(jsonString["data"][x]["lat"]);
OnlineMapsMarker marker = OnlineMaps.instance.AddMarker(longitudef, latitudef);
marker.label = jsonString["data"][x]["setGame"];
marker.scale = .7f;
marker.OnClick += UIBPM.OnMarkerClick;
marker.id = double.Parse(jsonString["data"][x]["nodeid"]);
marker.texture = getmarkerTexture(CodeTexture(marker.label));
}
}
yield return new WaitForSeconds (.1f);
// StartCoroutine (requesting ());
}
}
}
private int CodeTexture(string PrizeName)
{
int cupu = 0;
switch (PrizeName)
{
case "Gem":
cupu=6;
break;
case "Roll":
cupu=8;
break;
case "CrystalMarker":
cupu=8;
break;
case "GoldMarker":
cupu=7;
break;
case "Hantu":
cupu=1;
break;
}
return cupu;
}
private Texture2D getmarkerTexture(int codeTexture)
{
return markerImagelist[codeTexture];
}
public double getLon(){
return lon;
}
public double getLat(){
return lat;
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace FeedbackAndSurveyService.SurveyService.Model
{
public class SurveyReportGeneratorItem
{
public string Name { get; }
private IEnumerable<Grade> Responses { get; }
public SurveyReportGeneratorItem(string name, IEnumerable<Grade> responses)
{
Name = name;
Responses = responses;
}
public double GetAverage()
{
return Responses.Select(r => r.Value).Average();
}
public int GetGradeCount(Grade grade)
{
return Responses.Where(r => r.Equals(grade)).Count();
}
}
}
|
/// <summary>
/// Summary description for AddressController
/// </summary>
namespace com.Sconit.Web.Controllers.ISI
{
#region reference
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using com.Sconit.Entity.SYS;
using com.Sconit.Service;
using com.Sconit.Web.Models;
using com.Sconit.Web.Models.SearchModels.ISI;
using Telerik.Web.Mvc;
using com.Sconit.Entity.ISI;
using com.Sconit.Utility;
#endregion
/// <summary>
/// This controller response to control the Address.
/// </summary>
public class TaskSubTypeController : WebAppBaseController
{
/// <summary>
/// hql to get count of the address
/// </summary>
private static string selectCountStatement = "select count(*) from TaskSubType as t";
/// <summary>
/// hql to get all of the address
/// </summary>
private static string selectStatement = "select t from TaskSubType as t";
/// <summary>
/// hql to get count of the address by address's code
/// </summary>
private static string duiplicateVerifyStatement = @"select count(*) from TaskSubType as t where t.Code = ?";
#region public actions
/// <summary>
/// Index action for Address controller
/// </summary>
/// <returns>Index view</returns>
[SconitAuthorize(Permissions = "Url_TaskSubType_View")]
public ActionResult Index()
{
return View();
}
/// <summary>
/// List action
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel">Address Search model</param>
/// <returns>return the result view</returns>
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_TaskSubType_View")]
public ActionResult List(GridCommand command, TaskSubTypeSearchModel searchModel)
{
SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel);
ViewBag.PageSize = base.ProcessPageSize(command.PageSize);
return View();
}
/// <summary>
/// AjaxList action
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel">Address Search Model</param>
/// <returns>return the result action</returns>
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_TaskSubType_View")]
public ActionResult _AjaxList(GridCommand command, TaskSubTypeSearchModel searchModel)
{
SearchStatementModel searchStatementModel = this.PrepareSearchStatement(command, searchModel);
return PartialView(GetAjaxPageData<TaskSubType>(searchStatementModel, command));
}
/// <summary>
/// New action
/// </summary>
/// <returns>New view</returns>
[SconitAuthorize(Permissions = "Url_TaskSubType_Edit")]
public ActionResult New()
{
return View();
}
/// <summary>
/// New action
/// </summary>
/// <param name="address">Address Model</param>
/// <returns>return the result view</returns>
[HttpPost]
[SconitAuthorize(Permissions = "Url_TaskSubType_Edit")]
public ActionResult New(TaskSubType taskSubType)
{
if (ModelState.IsValid)
{
if (base.genericMgr.FindAll<long>(duiplicateVerifyStatement, new object[] { taskSubType.Code })[0] > 0)
{
SaveErrorMessage(Resources.SYS.ErrorMessage.Errors_Existing_Code, taskSubType.Code);
}
else
{
taskSubType.IsActive = true;
base.genericMgr.Create(taskSubType);
SaveSuccessMessage(Resources.ISI.TaskSubType.TaskSubType_SubType_Added);
return RedirectToAction("Edit/" + taskSubType.Code);
}
}
return View(taskSubType);
}
/// <summary>
/// Edit view
/// </summary>
/// <param name="id">address id for edit</param>
/// <returns>return the result view</returns>
[HttpGet]
[SconitAuthorize(Permissions = "Url_TaskSubType_Edit")]
public ActionResult Edit(string id)
{
if (string.IsNullOrEmpty(id))
{
return HttpNotFound();
}
else
{
TaskSubType taskSubType = base.genericMgr.FindById<TaskSubType>(id);
return View(taskSubType);
}
}
/// <summary>
/// Edit view
/// </summary>
/// <param name="address">Address Model</param>
/// <returns>return the result view</returns>
[SconitAuthorize(Permissions = "Url_TaskSubType_Edit")]
public ActionResult Edit(TaskSubType taskSubType)
{
if (ModelState.IsValid)
{
base.genericMgr.Update(taskSubType);
SaveSuccessMessage(Resources.ISI.TaskSubType.TaskSubType_SubType_Updated);
}
return View(taskSubType);
}
/// <summary>
/// Delete action
/// </summary>
/// <param name="id">address id for delete</param>
/// <returns>return to List action</returns>
[SconitAuthorize(Permissions = "Url_TaskSubType_Edit")]
public ActionResult Delete(string code)
{
if (string.IsNullOrEmpty(code))
{
return HttpNotFound();
}
else
{
base.genericMgr.DeleteById<TaskSubType>(code);
SaveSuccessMessage(Resources.ISI.TaskSubType.TaskSubType_SubType_Deleted);
return RedirectToAction("List");
}
}
#endregion
/// <summary>
/// Search Statement
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel">Address Search Model</param>
/// <returns>return address search model</returns>
private SearchStatementModel PrepareSearchStatement(GridCommand command, TaskSubTypeSearchModel searchModel)
{
string whereStatement = string.Empty;
IList<object> param = new List<object>();
HqlStatementHelper.AddLikeStatement("Code", searchModel.Code, HqlStatementHelper.LikeMatchMode.Start, "u", ref whereStatement, param);
HqlStatementHelper.AddLikeStatement("Description", searchModel.Description, HqlStatementHelper.LikeMatchMode.Start, "u", ref whereStatement, param);
if (command.SortDescriptors.Count > 0)
{
if (command.SortDescriptors[0].Member == "AddressTypeDescription")
{
command.SortDescriptors[0].Member = "Type";
}
}
string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
SearchStatementModel searchStatementModel = new SearchStatementModel();
searchStatementModel.SelectCountStatement = selectCountStatement;
searchStatementModel.SelectStatement = selectStatement;
searchStatementModel.WhereStatement = whereStatement;
searchStatementModel.SortingStatement = sortingStatement;
searchStatementModel.Parameters = param.ToArray<object>();
return searchStatementModel;
}
}
}
|
using Sunnie.Models;
using System.Collections.Generic;
namespace Sunnie.Repositories
{
public interface IProductRepository
{
void Add(Product product);
void Delete(int productId);
List<Product> GetAllProducts();
List<Product> GetProductByUser(int userProfileId);
void Update(Product product);
}
} |
namespace SoftUniStore.Services.Contracts
{
using System.Collections.Generic;
using Client.Api.CommonModels.BindingModels.Games;
using Client.Api.CommonModels.ViewModels.Games;
public interface ICatalogService
{
IEnumerable<AdminGameViewModel> GetAllGames();
string AddNewGame(NewGameBindingModel newGameBm);
string EditGame(NewGameBindingModel editGameBm);
EditGameViewModel GetGameById(int gameId);
void DeleteGame(int gameId);
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/// <summary>
/// Código encontrado em um vídeo no Youtube postado po unitycookie
/// </summary>
public class LoadingScreen : MonoBehaviour {
public static GameObject background;
public static GameObject text;
public static GameObject progressBar;
private static int loadProgress = 0;
public static string levelToLoad = "Map1";
public static LoadingScreen instance;
AsyncOperation async;
void Start () {
instance = this;
background = GameObject.Find("Tela/Background");
text = GameObject.Find("Tela/Text");
progressBar = GameObject.Find("Tela/Scrollbar");
background.SetActive(false);
text.SetActive(false);
progressBar.SetActive(false);
switch (Caapora.GameManager.next_scene)
{
case "Map1":
LoadLevel("Map1");
break;
case "Map2":
LoadLevel("Map2");
break;
case "TestMap":
LoadLevel("AmbienteTestes2.5D");
break;
case "MenuPrincipal":
LoadLevel("MenuPrincipal");
break;
}
}
void Update () {
if (loadProgress >= 100)
{
background.SetActive(false);
text.SetActive(false);
progressBar.SetActive(false);
}
}
public static void LoadLevel(string levelToLoad)
{
instance.StartCoroutine(instance.DisplayLoadingScreen(levelToLoad));
}
IEnumerator DisplayLoadingScreen(string level)
{
background.SetActive(true);
text.SetActive(true);
progressBar.SetActive(true);
text.GetComponent<Text>().text = "Loading Progress " + loadProgress + "%";
async = Application.LoadLevelAsync(level);
async.allowSceneActivation = false;
while (!async.isDone)
{
if(async.progress > 0.89f)
{
async.allowSceneActivation = true;
}
// Debug.Log("async progress " + async.progress.ToString());
loadProgress = (int)(async.progress * 100);
text.GetComponent<Text>().text = "Loading Progress " + loadProgress + "%";
progressBar.GetComponent<Scrollbar>().size = async.progress;
yield return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace szamologep
{
class Program
{
static void Main(string[] args)
{
string[] szam = {
"1+2*3-4",
"1*2+3-4",
"1+2-3*4",
"1+2*3-4*5+6",
"1+2*(3-4)*5+6" };
for (int i = 0; i < szam.Length; i++)
{
string tmp = szam[i];
Console.WriteLine(i+1 + ". megfejtés: " + szamol(tmp).ToString());
}
Console.ReadKey();
}
static double szamol(string szam)
{
return Convert.ToDouble(new DataTable().Compute(szam, null));
}
}
}
|
using NHibernate.Envers.Configuration.Attributes;
using Profiling2.Domain.Prf.Sources;
using SharpArch.Domain.DomainModel;
namespace Profiling2.Domain.Prf.Units
{
public class UnitSource : Entity
{
[Audited]
public virtual Unit Unit { get; set; }
[Audited]
public virtual Source Source { get; set; }
[Audited(TargetAuditMode = RelationTargetAuditMode.NotAudited)]
public virtual Reliability Reliability { get; set; }
[Audited]
public virtual string Commentary { get; set; }
[Audited]
public virtual bool Archive { get; set; }
[Audited]
public virtual string Notes { get; set; }
public override string ToString()
{
return (this.Unit != null ? "Unit(ID=" + this.Unit.Id.ToString() + ")" : string.Empty)
+ (this.Source != null ? " is linked with Source(ID=" + this.Source.Id.ToString() + ")" : string.Empty);
}
}
}
|
using gView.GraphicsEngine.Abstraction;
using gView.GraphicsEngine.GdiPlus.Extensions;
using System.Drawing.Drawing2D;
namespace gView.GraphicsEngine.GdiPlus
{
internal class GdiHatchBrush : IBrush
{
private HatchBrush _brush;
public GdiHatchBrush(HatchStyle hatchStyle, ArgbColor foreColor, ArgbColor backColor)
{
_brush = new HatchBrush((System.Drawing.Drawing2D.HatchStyle)hatchStyle,
foreColor.ToGdiColor(),
backColor.ToGdiColor());
}
public object EngineElement => _brush;
public ArgbColor Color { get; set; }
public void Dispose()
{
if (_brush != null)
{
_brush.Dispose();
_brush = null;
}
}
}
} |
using UnityEngine;
public class PlayerShootController : BasePlayerController
{
[SerializeField] private Hand _hand;
private void Update()
{
var ray = _camera.ScreenPointToRay(Input.mousePosition);
_hand.LookTo(ray.direction);
if (Input.GetMouseButtonDown(0))
_hand.StartShoot();
if (Input.GetMouseButtonUp(0))
_hand.StopShoot();
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.Marketplaces.Entityes;
namespace Infra.Mapeamentos
{
class MappingListingPicture : EntityTypeConfiguration<ListingPicture>
{
public MappingListingPicture()
{
// Primary Key
this.HasKey(t => t.ID);
// Properties
// Table & Column Mappings
this.ToTable("ListingPictures");
this.Property(t => t.ID).HasColumnName("ID");
this.Property(t => t.ListingID).HasColumnName("ListingID");
this.Property(t => t.PictureID).HasColumnName("PictureID");
this.Property(t => t.Ordering).HasColumnName("Ordering");
// Relationships
this.HasRequired(t => t.Listing)
.WithMany(t => t.ListingPictures)
.HasForeignKey(d => d.ListingID).WillCascadeOnDelete();
this.HasRequired(t => t.Picture)
.WithMany(t => t.ListingPictures)
.HasForeignKey(d => d.PictureID).WillCascadeOnDelete();
}
}
}
|
using System.Threading.Tasks;
using Alabo.Dependency;
using Alabo.Industry.Shop.Orders.Domain.Services;
using Alabo.Schedules.Job;
using Quartz;
namespace Alabo.Industry.Shop.Products.Schedules
{
/// <summary>
/// 商品库存更改
/// </summary>
public class ProductStockSchedule : JobBase
{
protected override async Task Execute(IJobExecutionContext context, IScope scope)
{
var orderAdminService = scope.Resolve<IOrderAdminService>();
// 更新库存,只有在更新货币类型和商城类型的时候,才更新数据库
orderAdminService.ProductStockUpdate();
}
}
} |
using System;
using System.Runtime.InteropServices;
using Vlc.DotNet.Core.Interops;
using Vlc.DotNet.Core.Interops.Signatures;
namespace Vlc.DotNet.Core
{
public partial class VlcMedia
{
public event EventHandler<VlcMediaDurationChangedEventArgs> DurationChanged;
private void OnMediaDurationChangedInternal(IntPtr ptr)
{
var args = MarshalHelper.PtrToStructure<VlcEventArg>(ptr);
OnMediaDurationChanged(args.eventArgsUnion.MediaDurationChanged.NewDuration);
}
public void OnMediaDurationChanged(long newDuration)
{
DurationChanged?.Invoke(this, new VlcMediaDurationChangedEventArgs(newDuration));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebTest.Code
{
public class MemberManage : CRL.BaseProvider<Member>
{
public static MemberManage ContextInstance<T>(CRL.BaseProvider<T> baseProvider) where T : CRL.IModel, new()
{
var instance = Instance;
instance.SetContext(baseProvider);
return instance;
}
/// <summary>
/// 实例访问入口
/// </summary>
public static MemberManage Instance
{
get { return new MemberManage(); }
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Pe.Stracon.SGC.Infraestructura.Core.QueryContract.Contractual;
using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.Repository.Base;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
namespace Pe.Stracon.SGC.Infraestructura.Repository.Query.Contractual
{
/// <summary>
/// Implementación del repositorio de Contrato
/// </summary>
public class ContratoLogicRepository : QueryRepository<ContratoLogic>, IContratoLogicRepository
{
/// <summary>
/// Metodo para listar los contrato por usuario.
/// </summary>
/// <param name="CodigoResponsable">Codigo de trabajador que consulta</param>
/// <param name="UnidadOperativa">Código de Unidad Operativa</param>
/// <param name="NombreProveedor">Nombre del proveedor</param>
/// <param name="NumdocPrv">Número de documento del proveedor</param>
/// <param name="TipoServicio">Tipo de Servicio</param>
/// <param name="TipoReq">Tipo de Requerimiento</param>
/// <returns>Lista de bandeja de contratos</returns>
public List<ContratoLogic> ListaBandejaContratos(
Guid CodigoResponsable,
Guid? UnidadOperativa,
string NombreProveedor,
string NumdocPrv,
string TipoServicio,
string TipoReq,
string nombreEstadio,
string indicadorFinalizarAprobacion)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CodigoResponsable",SqlDbType.UniqueIdentifier) { Value = (object)CodigoResponsable ?? DBNull.Value},
new SqlParameter("UnidadOperativa",SqlDbType.UniqueIdentifier) { Value = (object)UnidadOperativa ?? DBNull.Value},
new SqlParameter("NombreProveedor",SqlDbType.NVarChar) { Value = (object)NombreProveedor ?? DBNull.Value},
new SqlParameter("NumeroDocumentoPrv",SqlDbType.NVarChar) { Value = (object)NumdocPrv ?? DBNull.Value},
new SqlParameter("TipoServicio",SqlDbType.NVarChar) { Value = (object)TipoServicio ?? DBNull.Value},
new SqlParameter("TipoRequerimiento",SqlDbType.NVarChar) { Value = (object)TipoReq ?? DBNull.Value},
new SqlParameter("NombreEstadio",SqlDbType.NVarChar) { Value = (object)nombreEstadio ?? DBNull.Value},
new SqlParameter("IndicadorFinalizarAprobacion",SqlDbType.NVarChar) { Value = (object)indicadorFinalizarAprobacion ?? DBNull.Value},
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoLogic>("CTR.USP_BANDEJA_CONTRATOS_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Metodo para listar las Observaciones por Contrato por Estadio.
/// </summary>
/// <param name="CodigoContratoEstadio">Código de Contrato Estadio</param>
/// <returns>Lista de bandeja de contratos por observaciones</returns>
public List<ContratoEstadioObservacionLogic> ListaBandejaContratosObservacion(Guid CodigoContratoEstadio)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CodigoContratoEstadio",SqlDbType.UniqueIdentifier) { Value = (object)CodigoContratoEstadio ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoEstadioObservacionLogic>("CTR.USP_BANDEJA_OBSERVACIONES_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Metodo para listar las Consultas por Contrato por Estadio.
/// </summary>
/// <param name="CodigoContratoEstadio">Código de Contrato Estadio</param>
/// <returns>Lista de consultas por contrato</returns>
public List<ContratoEstadioConsultaLogic> ListaBandejaContratosConsultas(Guid CodigoContratoEstadio)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CodigoContratoEstadio",SqlDbType.UniqueIdentifier) { Value = (object)CodigoContratoEstadio ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoEstadioConsultaLogic>("CTR.USP_BANDEJA_CONSULTAS_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Método para aprobar cada contrato según su estadío.
/// </summary>
/// <param name="codigoContratoEstadio">Código de Contrato Estadío</param>
/// <param name="codigoIdentificacionUO">Código de Identificación UO</param>
/// <param name="UserUpdate">Usuario que actualiza</param>
/// <param name="TerminalUpdate">Terminal desde donde se ejecuta.</param>
/// <param name="codigoUsuarioCreacionContrato">Código usuario creación de contrato</param>
/// <param name="MotivoAprobacion"></param>
/// <returns>Lista de estadios aprobados</returns>
public int ApruebaContratoEstadio(Guid codigoContratoEstadio, string codigoIdentificacionUO, string UserUpdate, string TerminalUpdate, string codigoUsuarioCreacionContrato, string MotivoAprobacion)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO_ESTADIO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContratoEstadio ?? DBNull.Value},
new SqlParameter("CODIGO_IDENTIFICACION_UO",SqlDbType.NVarChar) { Value = (object)codigoIdentificacionUO ?? DBNull.Value},
new SqlParameter("USUARIO_CREACION",SqlDbType.NVarChar) { Value = (object)UserUpdate ?? DBNull.Value},
new SqlParameter("TERMINAL_CREACION",SqlDbType.NVarChar) { Value = (object)TerminalUpdate ?? DBNull.Value},
new SqlParameter("CodigoUsuarioCreacionContrato",SqlDbType.UniqueIdentifier) { Value = codigoUsuarioCreacionContrato == string.Empty ? (object)Guid.Empty : (object)new Guid(codigoUsuarioCreacionContrato) ?? DBNull.Value},
new SqlParameter("motivo_aprobacion",SqlDbType.VarChar) { Value = (object)MotivoAprobacion ?? DBNull.Value},
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<int>("CTR.USP_APRUEBA_CONTRATO_ESTADIO", parametros).FirstOrDefault();
return result;
}
/// <summary>
/// Método para retornar los párrafos por contrato
/// </summary>
/// <param name="CodigoContrato">Código de Contrato</param>
/// <returns>Parrafos por contrato</returns>
public List<ContratoParrafoLogic> RetornaParrafosPorContrato(Guid CodigoContrato)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)CodigoContrato ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoParrafoLogic>("CTR.USP_CONTRATO_PARRAFO_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Método que retorna los estadio del contrato para su observación.
/// </summary>
/// <param name="CodigoContratoEstadio">Código del Estadío del Contrato</param>
/// <returns>Estadios de contrato</returns>
public List<FlujoAprobacionEstadioLogic> RetornaEstadioContratoObservacion(Guid CodigoContratoEstadio)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CodigoContratoEstadio",SqlDbType.UniqueIdentifier) { Value = (object)CodigoContratoEstadio ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<FlujoAprobacionEstadioLogic>("CTR.USP_ESTADIOS_CONTRATO_OBSERVACION", parametros).ToList();
return result;
}
/// <summary>
/// Responder la Consulta que me han hecho
/// </summary>
/// <param name="codigoContratoEstadioConsulta"></param>
/// <param name="Respuesta"></param>
/// <param name="UsuarioModificacion"></param>
/// <param name="TerminalModificacion"></param>
/// <returns></returns>
public int Responder_Consulta(Guid codigoContratoEstadioConsulta,string Respuesta, string UsuarioModificacion, string TerminalModificacion)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO_ESTADIO_CONSULTA",SqlDbType.UniqueIdentifier) { Value = (object)codigoContratoEstadioConsulta ?? DBNull.Value},
new SqlParameter("RESPUESTA",SqlDbType.VarChar) { Value = (object)Respuesta ?? DBNull.Value},
new SqlParameter("USUARIO_MODIFICACION",SqlDbType.VarChar) { Value = (object)UsuarioModificacion ?? DBNull.Value},
new SqlParameter("TERMINAL_MODIFICACION",SqlDbType.VarChar) { Value = (object)TerminalModificacion ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<int>("CTR.USP_RESPONDER_CONSULTA", parametros).FirstOrDefault();
return result;
}
/// <summary>
/// Método para generar un nuevo Estadio de contrato cada vez que es observado.
/// </summary>
/// <param name="codigoContratoEstadio"></param>
/// <param name="codigoContratoEstadioObservado">Código de Contrato Estadio Observado</param>
/// <param name="codigoContrato"> Código de Contrato </param>
/// <param name="codigoFlujoEstadioRetorno">Código Flujo Estadio Retorno </param>
/// <param name="codigoResponsable">Código de Responsable </param>
/// <param name="UserUpdate">Usuario que actualiza</param>
/// <param name="TerminalUpdate">Terminal desde donde de actualiza</param>
/// <returns>Estadios de contrato segun observación</returns>
public int ObservaEstadioContrato(Guid codigoContratoEstadio, Guid codigoContratoEstadioObservado, Guid codigoContrato, Guid codigoFlujoEstadioRetorno,
Guid codigoResponsable, string UserUpdate, string TerminalUpdate)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO_ESTADIO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContratoEstadio ?? DBNull.Value},
new SqlParameter("CODIGO_CONTRATO_ESTADIO_OBSERVADO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContratoEstadioObservado ?? DBNull.Value},
new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContrato ?? DBNull.Value},
new SqlParameter("CODIGO_FLUJO_ESTADIO_RETORNO",SqlDbType.UniqueIdentifier) { Value = (object)codigoFlujoEstadioRetorno ?? DBNull.Value},
new SqlParameter("CODIGO_RESPONSABLE",SqlDbType.UniqueIdentifier) { Value = (object)codigoResponsable ?? DBNull.Value},
new SqlParameter("USER_CREATION",SqlDbType.NVarChar) { Value = (object)UserUpdate ?? DBNull.Value},
new SqlParameter("TERMINAL_CREATION",SqlDbType.NVarChar) { Value = (object)TerminalUpdate ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<int>("CTR.USP_OBSERVA_ESTADIO_CONTRATO_UPD", parametros).FirstOrDefault();
return result;
}
/// <summary>
/// Método que retorna los responsable por flujo de aprobación.
/// </summary>
/// <param name="codigoFlujoAprobacion">código del flujo de aprobación.</param>
/// <param name="codigoContrato"></param>
/// <returns>Responsable del flujo del estadio</returns>
public List<TrabajadorResponse> RetornaResponsablesFlujoEstadio(Guid codigoFlujoAprobacion, Guid codigoContrato)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CodigoFlujoAprobacion",SqlDbType.UniqueIdentifier) { Value = (object)codigoFlujoAprobacion ?? DBNull.Value},
new SqlParameter("CodigoContrato",SqlDbType.UniqueIdentifier) { Value = (object)codigoContrato ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<TrabajadorResponse>("CTR.USP_RESPONSABLES_FLUJO_ESTADIO", parametros).ToList();
return result;
}
/// <summary>
/// Método para listar los documentos de la bandeja de solicitud.
/// </summary>
/// <param name="NumeroContrato">número del contrato</param>
/// <param name="UnidadOperativa">unidad operativa</param>
/// <param name="NombreProveedor">nombre del proveedor</param>
/// <param name="NumdocPrv">numero documento del proveedor</param>
/// <returns>Documentos de la bandeja de solicitud</returns>
public List<ContratoLogic> ListaBandejaSolicitudContratos(string NumeroContrato, Guid? UnidadOperativa, string NombreProveedor, string NumdocPrv)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("NumeroContrato",SqlDbType.NVarChar) { Value = (object)NumeroContrato ?? DBNull.Value},
new SqlParameter("UnidadOperativa",SqlDbType.UniqueIdentifier) { Value = (object)UnidadOperativa ?? DBNull.Value},
new SqlParameter("NombreProveedor",SqlDbType.NVarChar) { Value = (object)NombreProveedor ?? DBNull.Value},
new SqlParameter("NumeroDocumentoPrv",SqlDbType.NVarChar) { Value = (object)NumdocPrv ?? DBNull.Value},
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoLogic>("CTR.USP_BANDEJA_SOLICITUD_CONTRATO_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Método para retornar los documentos PDf por Contrato
/// </summary>
/// <param name="CodigoContrato">Código de Contrato</param>
/// <returns>Documentos pdf por contrato</returns>
public List<ContratoDocumentoLogic> DocumentosPorContrato(Guid CodigoContrato)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CodigoContrato",SqlDbType.UniqueIdentifier) { Value = (object)CodigoContrato ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoDocumentoLogic>("CTR.USP_DOCUMENTO_POR_CONTRATO_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Metodo para cargar un Archivo a un estadio de contrato.
/// </summary>
/// <param name="objLogic">Objeto Contrato Documento Logic</param>
/// <param name="User">Usuario que ejecuta la transaccion</param>
/// <param name="Terminal">Terminal desde donde se ejecuta la transaccion</param>
/// <returns>Indicador con el resultado de la operación</returns>
public int RegistraContratoDocumentoCargaArchivo(ContratoDocumentoLogic objLogic, string User, string Terminal)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO_DOCUMENTO",SqlDbType.UniqueIdentifier) { Value = (object)objLogic.CodigoContratoDocumento ?? DBNull.Value},
new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)objLogic.CodigoContrato ?? DBNull.Value},
new SqlParameter("CODIGO_ARCHIVO",SqlDbType.Int ) { Value = (object)objLogic.CodigoArchivo ?? DBNull.Value},
new SqlParameter("RUTA_ARCHIVOSHP",SqlDbType.NVarChar) { Value = (object)objLogic.RutaArchivoSharePoint ?? DBNull.Value},
new SqlParameter("CONTENIDO",SqlDbType.NVarChar) { Value = (object)objLogic.Contenido ?? DBNull.Value},
new SqlParameter("USER_CREACION",SqlDbType.VarChar) { Value = (object)User ?? DBNull.Value},
new SqlParameter("TERMINAL_CREACION",SqlDbType.VarChar) { Value = (object)Terminal ?? DBNull.Value},
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<int>("CTR.USP_REGISTRA_CONTRATODOC_CARGA_ARCHIVO", parametros).FirstOrDefault();
return result;
}
/// <summary>
/// Método para retornar registros de Contrato Documento
/// </summary>
/// <param name="CodigoContrato">Llave primaria código contrato</param>
/// <returns>Lista de registros</returns>
public List<ContratoDocumentoLogic> ListarContratoDocumento(Guid codigoContrato)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContrato ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoDocumentoLogic>("CTR.USP_CONTRATO_DOCUMENTO_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Lista los Estadios de los Contratos
/// </summary>
/// <param name="codigoContratoEstadio">Codigo de Contrato Estadio</param>
/// <param name="codigoContrato">Código de contrato</param>
/// <param name="codigoFlujoAprobEsta">Código de flujo de aprobación</param>
/// <param name="fechaIngreso">Fecha de ingreso</param>
/// <param name="fechaFinaliz">Fecha de finalización</param>
/// <param name="codigoResponsable">Código de responsable</param>
/// <param name="codigoEstadoContratoEst">Código de Estados de Contrato Estadio</param>
/// <param name="fechaPrimera">Fecha de primera notificación</param>
/// <param name="fechaUltima">Fecha de última notificación</param>
/// <param name="PageNumero">número de página</param>
/// <param name="PageSize">tamaño por página</param>
/// <returns>Estadios de los contratos</returns>
public List<ContratoEstadioLogic> ListarContratoEstadio(Guid? codigoContratoEstadio = null, Guid? codigoContrato = null,
Guid? codigoFlujoAprobEsta = null, DateTime? fechaIngreso = null,
DateTime? fechaFinaliz = null, Guid? codigoResponsable = null,
string codigoEstadoContratoEst = null,
DateTime? fechaPrimera = null, DateTime? fechaUltima = null,
int PageNumero = 1, int PageSize = -1)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO_ESTADIO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContratoEstadio ?? DBNull.Value},
new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContrato ?? DBNull.Value},
new SqlParameter("CODIGO_FLUJO_APROBACION_ESTADIO",SqlDbType.UniqueIdentifier) { Value = (object)codigoFlujoAprobEsta ?? DBNull.Value},
new SqlParameter("FECHA_INGRESO",SqlDbType.DateTime) { Value = (object)fechaIngreso ?? DBNull.Value},
new SqlParameter("FECHA_FINALIZACION",SqlDbType.DateTime) { Value = (object)fechaFinaliz ?? DBNull.Value},
new SqlParameter("CODIGO_RESPONSABLE",SqlDbType.UniqueIdentifier) { Value = (object)codigoResponsable ?? DBNull.Value},
new SqlParameter("CODIGO_ESTADO_CONTRATO_ESTADIO",SqlDbType.NVarChar) { Value = (object)codigoEstadoContratoEst ?? DBNull.Value},
new SqlParameter("FECHA_PRIMERA_NOTIFICACION",SqlDbType.DateTime) { Value = (object)fechaPrimera ?? DBNull.Value},
new SqlParameter("FECHA_ULTIMA_NOTIFICACION",SqlDbType.DateTime) { Value = (object)fechaUltima ?? DBNull.Value},
new SqlParameter("PageNo",SqlDbType.Int) { Value = (object)PageNumero ?? DBNull.Value},
new SqlParameter("PageSize",SqlDbType.Int) { Value = (object)PageSize ?? DBNull.Value},
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoEstadioLogic>("CTR.USP_CONTRATO_ESTADIO_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Método para retornar las unidades operativas del responsable.
/// </summary>
/// <param name="codigoTrabajador">Código del Trabjador</param>
/// <returns>Lista de registros</returns>
public List<UnidadOperativaLogic> ListarUnidadOperativaResponsable(Guid codigoTrabajador)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_TRABAJADOR",SqlDbType.UniqueIdentifier) { Value = (object)codigoTrabajador ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<UnidadOperativaLogic>("CTR.USP_LISTAR_UO_POR_PARTICIPANTE_RESPONSABLE", parametros).ToList();
return result;
}
/// <summary>
/// Retorna el participante y el codigo del flujo de aprobacion anterior del contrato estadio.
/// </summary>
/// <param name="codigoContratoEstadio">Codigo de Contrato Estadio</param>
/// <param name="codigoContrato">Código de contrato</param>
/// <returns>Participante y el código del flujo de aprobación</returns>
public List<FlujoAprobacionParticipanteLogic> EstadoAnteriorContratoEstadio(Guid codigoContratoEstadio, Guid codigoContrato)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO_ESTADIO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContratoEstadio ?? DBNull.Value},
new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContrato ?? DBNull.Value},
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<FlujoAprobacionParticipanteLogic>("CTR.USP_ESTADIO_ANTERIOR_CONTRATO_ESTADIO", parametros).ToList();
return result;
}
/// <summary>
/// Notifica las acciones de contratos.
/// </summary>
/// <param name="asunto">Asunto de la notificación</param>
/// <param name="textoNotificar">contenido de la notificación</param>
/// <param name="cuentaNotificar">cuentas destino a notificar</param>
/// <param name="cuentaCopias">cuentas de copia del correo</param>
/// <param name="profileCorreo">profile de la configuración de correo</param>
/// <returns>Acciones del contrato</returns>
public int NotificaBandejaContratos(string asunto, string textoNotificar, string cuentaNotificar, string cuentaCopias, string profileCorreo)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("ASUNTO",SqlDbType.NVarChar) { Value = (object)asunto ?? DBNull.Value},
new SqlParameter("TEXTO_NOTIFICAR",SqlDbType.NVarChar ) { Value = (object)textoNotificar ?? DBNull.Value},
new SqlParameter("CUENTA_NOTIFICAR",SqlDbType.NVarChar) { Value = (object)cuentaNotificar ?? DBNull.Value},
new SqlParameter("CUENTAS_COPIAS",SqlDbType.NVarChar) { Value = (object)cuentaCopias ?? DBNull.Value},
new SqlParameter("PROFILE_CORREO",SqlDbType.NVarChar) { Value = (object)profileCorreo ?? DBNull.Value},
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<int>("CTR.USP_NOTIFICACION_BANDEJA_CONTRATOS", parametros).FirstOrDefault();
return result;
}
/// <summary>
/// Retorna los parámetros necesarios para enviar la notificación
/// </summary>
/// <param name="codigoContratoEstadio">Código de Contrato estadio</param>
/// <param name="TipoNotificacion">Tipo de notificación</param>
/// <returns>Parametros necesarios para enviar la notifación</returns>
public List<ContratoEstadioLogic> InformacionNotificacionContratoEstadio(Guid codigoContratoEstadio, string TipoNotificacion)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO_ESTADIO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContratoEstadio ?? DBNull.Value},
new SqlParameter("TIPO_NOTIFICACION",SqlDbType.NVarChar) { Value = (object)TipoNotificacion ?? DBNull.Value},
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoEstadioLogic>("CTR.USP_INF_NOTIFICACION_CONTRATO_ESTADIO_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Lista de contratos estadios por responsable
/// </summary>
/// <param name="codigoContrato">Codigo de Contrato</param>
/// <returns>Listado de contrato estadio</returns>
public List<ContratoEstadioLogic> ListadoContratoEstadioResponsable(Guid codigoContrato)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContrato ?? DBNull.Value},
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoEstadioLogic>("CTR.USP_CONTRATO_ESTADIO_RESPONSABLE_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Registrar adenda con contrato vencido
/// </summary>
/// <param name="unidadOperativa">Código Unidad Operativa</param>
/// <param name="numeroContrato">Número contrato</param>
/// <param name="descripcion">Descripción</param>
/// <param name="numeroAdenda">Número de adenda</param>
/// <param name="numeroAdendaConcatenado">Número de adenda concatenado</param>
/// <returns>Registro de adenda en tabla temporal</returns>
public int RegistraAdendaContratoVencido(Guid unidadOperativa, string numeroContrato, string descripcion, int numeroAdenda, string numeroAdendaConcatenado)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_UNIDAD_OPERATIVA",SqlDbType.UniqueIdentifier) { Value = (object)unidadOperativa ?? DBNull.Value},
new SqlParameter("NUMERO_CONTRATO",SqlDbType.NVarChar) { Value = (object)numeroContrato ?? DBNull.Value},
new SqlParameter("DESCRIPCION",SqlDbType.NVarChar) { Value = (object)descripcion ?? DBNull.Value},
new SqlParameter("NUMERO_ADENDA",SqlDbType.Int) { Value = (object)numeroAdenda ?? DBNull.Value},
new SqlParameter("NUMERO_ADENDA_CONCATENADO",SqlDbType.NVarChar) { Value = (object)numeroAdendaConcatenado ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedureNonQuery("CTR.USP_ADENDAS_CONTRATO_VENCIDO_INS", parametros);
return result;
}
/// <summary>
/// Método para listar los contrato por usuario.
/// </summary>
/// <param name="CodigoResponsable">Codigo de trabajador que consulta</param>
/// <param name="UnidadOperativa">Código de Unidad Operativa</param>
/// <param name="NombreProveedor">Nombre del proveedor</param>
/// <param name="NumdocPrv">Número de documento del proveedor</param>
/// <param name="TipoServicio">Tipo de Servicio</param>
/// <param name="TipoReq">Tipo de Requerimiento</param>
/// <param name="nombreEstadio">Nombre de estadio</param>
/// <param name="indicadorFinalizarAprobacion">Indicador de finalizar aprobación</param>
/// <param name="columnaOrden">Columna para ordenar</param>
/// <param name="tipoOrden">Tipo de ordenamiento</param>
/// <param name="numeroPagina">Número de página</param>
/// <param name="registroPagina">Número de registros por página</param>
/// <returns>Lista de bandeja de contratos</returns>
public List<ContratoLogic> ListaBandejaContratosOrdenado(
Guid CodigoResponsable,
Guid? UnidadOperativa,
string NombreProveedor,
string NumdocPrv,
string TipoServicio,
string TipoReq,
string nombreEstadio,
string indicadorFinalizarAprobacion,
string columnaOrden,
string tipoOrden,
int numeroPagina,
int registroPagina)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CodigoResponsable",SqlDbType.UniqueIdentifier) { Value = (object)CodigoResponsable ?? DBNull.Value},
new SqlParameter("UnidadOperativa",SqlDbType.UniqueIdentifier) { Value = (object)UnidadOperativa ?? DBNull.Value},
new SqlParameter("NombreProveedor",SqlDbType.NVarChar) { Value = (object)NombreProveedor ?? DBNull.Value},
new SqlParameter("NumeroDocumentoPrv",SqlDbType.NVarChar) { Value = (object)NumdocPrv ?? DBNull.Value},
new SqlParameter("TipoServicio",SqlDbType.NVarChar) { Value = (object)TipoServicio ?? DBNull.Value},
new SqlParameter("TipoRequerimiento",SqlDbType.NVarChar) { Value = (object)TipoReq ?? DBNull.Value},
new SqlParameter("NombreEstadio",SqlDbType.NVarChar) { Value = (object)nombreEstadio ?? DBNull.Value},
new SqlParameter("IndicadorFinalizarAprobacion",SqlDbType.NVarChar) { Value = (object)indicadorFinalizarAprobacion ?? DBNull.Value},
new SqlParameter("COLUMNA_ORDEN",SqlDbType.VarChar) { Value = (object)columnaOrden ?? DBNull.Value},
new SqlParameter("TIPO_ORDEN",SqlDbType.VarChar) { Value = (object)tipoOrden ?? DBNull.Value},
new SqlParameter("NUMERO_PAGINA",SqlDbType.Int) { Value = (object)numeroPagina ?? DBNull.Value},
new SqlParameter("TAMANIO_PAGINA",SqlDbType.BigInt) { Value = (object)registroPagina ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoLogic>("CTR.USP_BANDEJA_CONTRATOS_ORDENADO_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Metodo para obtener el estadio de edición de un flujo de aprobación de un contrato
/// </summary>
/// <param name="codigoContrato">Código contrato</param>
/// <param name="codigoFlujoAprobacion">Código flujo de aprobación</param>
/// <returns>Código de contrato estadio de edición</returns>
public Guid ObtenerContratoEstadioEdicion(Guid codigoContrato, Guid? codigoFlujoAprobacion)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContrato ?? DBNull.Value},
new SqlParameter("CODIGO_FLUJO_APROBACION",SqlDbType.UniqueIdentifier ) { Value = (object)codigoFlujoAprobacion ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<Guid>("CTR.USP_CONTRATO_ESTADIO_OBTENER_ESTADIO_EDICION", parametros).FirstOrDefault();
return result;
}
/// <summary>
/// Metodo para obtener el responsable de edición de un estadio
/// </summary>
/// <param name="codigoContratoEstadio">Código contrato estadio</param>
/// <param name="codigoEstadioRetorno">Código estadio retorno</param>
/// <param name="codigoResposable">Código responsale</param>
/// <returns>Código responsable de estadio de edición</returns>
public Guid ObtenerResponsableContratoEstadioEdicion(Guid codigoContratoEstadio, Guid codigoEstadioRetorno, Guid codigoResposable)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO_ESTADIO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContratoEstadio ?? DBNull.Value},
new SqlParameter("CODIGO_ESTADIO_RETORNO",SqlDbType.UniqueIdentifier ) { Value = (object)codigoEstadioRetorno ?? DBNull.Value},
new SqlParameter("CODIGO_RESPONSABLE",SqlDbType.UniqueIdentifier ) { Value = (object)codigoResposable ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<Guid>("CTR.USP_CONTRATO_ESTADIO_OBTENER_RESPONSABLE_EDICION", parametros).FirstOrDefault();
return result;
}
/// <summary>
/// Método para obtener la empresa vinculada por proveedor
/// </summary>
/// <param name="codigoProveedor">Código de proveedor</param>
/// <returns>Datos de empresa vinculada</returns>
public EmpresaVinculadaLogic ObtenerEmpresaVinculadaPorProveedor(Guid? codigoProveedor)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_PROVEEDOR",SqlDbType.UniqueIdentifier) { Value = (object)codigoProveedor ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<EmpresaVinculadaLogic>("CTR.USP_EMPRESA_VINCULADA_POR_PROVEEDOR", parametros).FirstOrDefault();
return result;
}
/// <summary>
/// Método para listar los contratos aprobados en la solicitud de modificación.
/// </summary>
/// <param name="NumeroContrato">número del contrato</param>
/// <param name="UnidadOperativa">unidad operativa</param>
/// <param name="NombreProveedor">nombre del proveedor</param>
/// <param name="NumdocPrv">numero documento del proveedor</param>
/// <returns>Listado de contratos para revisión</returns>
public List<ContratoLogic> ListaBandejaRevisionContratos(string NumeroContrato, Guid? UnidadOperativa, string NombreProveedor, string NumdocPrv)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("NumeroContrato",SqlDbType.NVarChar) { Value = (object)NumeroContrato ?? DBNull.Value},
new SqlParameter("UnidadOperativa",SqlDbType.UniqueIdentifier) { Value = (object)UnidadOperativa ?? DBNull.Value},
new SqlParameter("NombreProveedor",SqlDbType.NVarChar) { Value = (object)NombreProveedor ?? DBNull.Value},
new SqlParameter("NumeroDocumentoPrv",SqlDbType.NVarChar) { Value = (object)NumdocPrv ?? DBNull.Value},
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoLogic>("CTR.USP_BANDEJA_REVISION_CONTRATO_SEL", parametros).ToList();
return result;
}
/// <summary>
///
/// </summary>
/// <param name="codigoUnidadOperativa"></param>
/// <param name="numeroContrato"></param>
/// <param name="numeroPagina"></param>
/// <param name="registroPagina"></param>
/// <returns></returns>
public List<ContratoLogic> BuscarNumeroContrato(Guid? codigoUnidadOperativa,
string numeroContrato,
int numeroPagina,
int registroPagina)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_UNIDAD_OPERATIVA",SqlDbType.UniqueIdentifier) { Value = (object)codigoUnidadOperativa ?? DBNull.Value},
new SqlParameter("NUMERO_CONTRATO",SqlDbType.NVarChar) { Value = (object)numeroContrato ?? DBNull.Value},
new SqlParameter("PageNo",SqlDbType.Int) { Value = (object)numeroPagina ?? DBNull.Value},
new SqlParameter("PageSize",SqlDbType.Int) { Value = (object)registroPagina ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoLogic>("CTR.USP_NUMERO_CONTRATO_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Reporte Observado Aprobado
/// </summary>
/// <param name="codigoUnidadOperativa"></param>
/// <param name="codigoContrato"></param>
/// <param name="tipoAccion"></param>
/// <param name="fechaInicio"></param>
/// <param name="fechaFin"></param>
/// <param name="nombreBaseDatoPolitica"></param>
/// <param name="numeroPagina"></param>
/// <param name="registroPagina"></param>
/// <returns></returns>
public List<ContratoObservadoAprobadoLogic> BuscarContratoObservadoAprobado(Guid? codigoUnidadOperativa,
Guid? codigoContrato,
string tipoAccion,
DateTime? fechaInicio,
DateTime? fechaFin,
string nombreBaseDatoPolitica,
int numeroPagina,
int registroPagina)
{
try
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_UNIDAD_OPERATIVA",SqlDbType.UniqueIdentifier) { Value = (object)codigoUnidadOperativa ?? DBNull.Value},
new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)codigoContrato ?? DBNull.Value},
new SqlParameter("TIPO_ACCION_CONTRATO",SqlDbType.NVarChar) { Value = (object)tipoAccion ?? DBNull.Value},
new SqlParameter("FECHA_INICIO",SqlDbType.DateTime) { Value = (object)fechaInicio ?? DBNull.Value},
new SqlParameter("FECHA_FIN",SqlDbType.DateTime) { Value = (object)fechaFin ?? DBNull.Value},
new SqlParameter("NAME_DATABASE",SqlDbType.NVarChar) { Value = (object)nombreBaseDatoPolitica ?? DBNull.Value},
new SqlParameter("PageNo",SqlDbType.Int) { Value = (object)numeroPagina ?? DBNull.Value},
new SqlParameter("PageSize",SqlDbType.Int) { Value = (object)registroPagina ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ContratoObservadoAprobadoLogic>("CTR.USP_CONTRATO_OBSERVACIONES_APROBADAS_RPT", parametros).ToList();
return result;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace SSISTeam9.Models
{
public class Delegate
{
[Display(Name = "From")]
public DateTime FromDate { get; set; }
[Display(Name = "To")]
public DateTime ToDate { get; set; }
[Display(Name = "Employee Name")]
public Employee Employee { get; set; }
public Department Department { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Facturation.Shared
{
public class DashboardDto
{
public DashboardDto()
{
}
public DashboardDto(IBusinessData from)
{
CA = from.CA;
Percu = from.Percu;
MontantDus = from
.GetFactures(DateTime.Now, null)
.Select(f => new MontantDuDto(f));
}
public DashboardDto(IEnumerable<Facture> from)
{
foreach (Facture item in from)
{
CA += item.Montant;
Percu += item.MontantRegle;
MontantDus.Append(new MontantDuDto(item));
}
}
public decimal CA { get; set; }
public decimal Percu { get; set; }
public IEnumerable<MontantDuDto> MontantDus { get; set; }
}
}
|
using System;
using System.Windows.Data;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace TraceWizard.TwApp {
public interface IProgressOperation {
int Total { get; }
int Current { get; }
string KeyCode { get; }
void Start();
void CancelAsync();
event EventHandler ProgressChanged;
event EventHandler ProgressTotalChanged;
event EventHandler Complete;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HW2
{
public class Games
{
public Games()
{
Date = DateTime.Now.ToString("MM/dd/yyyy");
}
public int Score
{
get
{
return level * countBarrier * 10;
}
}
private int numMoveUP;
public int NumMoveUP
{
get
{
return numMoveUP;
}
set
{
numMoveUP = value;
}
}
private int numMoveDown;
public int NumMoveDown
{
get
{
return numMoveDown;
}
set
{
numMoveDown = value;
}
}
private int numMoveLeft;
public int NumMoveLeft
{
get
{
return numMoveLeft;
}
set
{
numMoveLeft = value;
}
}
private int numMoveRight;
public int NumMoveRight
{
get
{
return numMoveRight;
}
set
{
numMoveRight = value;
}
}
public int successfulMoves
{
get
{
return NumMoveUP + NumMoveDown + NumMoveRight + NumMoveLeft;
}
}
private int failedMoves;
public int FailedMoves
{
get
{
return failedMoves;
}
set
{
failedMoves = value;
}
}
public int TotleMoves
{
get
{
return failedMoves + successfulMoves;
}
}
private int level;
public int Level
{
get
{
return level;
}
set
{
level = value;
}
}
private int countBarrier;
public int CountBarrier
{
get
{
return countBarrier;
}
set
{
countBarrier = value;
}
}
private int duration;
public int Duration
{
set
{
duration = value;
}
get
{
return duration;
}
}
public string Date
{
get;
set;
}
public List<int> dirctionSteps = new List<int>();
public List<string> arr = new List<string>();
public int gameId;
}
}
|
using Assets.src.managers;
public class FriendlyAnimalIdleState : UnitIdleState
{
public FriendlyAnimalIdleState()
{
}
public FriendlyAnimalIdleState(UnitModel model, IAnimatorHelper animatorHelper) : base(model, animatorHelper)
{
}
public override void Start()
{
//idleCooldown = CooldownService.AddCooldown(0.5f, null, Stop, 0, 0.1f);
}
public override void Update()
{
var friendlyAnimalUnit = currentUnit as FriendlyAnimalModel;
var list = UnitManager.FindTargetsInRadius(currentUnit, currentUnit.Data.awarenessRadius,
UnitType.All ^ UnitType.Animal, true);
if (list.Count != 0)
{
friendlyAnimalUnit.RunAway(list[0].UnitBehaviour.CurrentTransform);
}
}
}
|
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Ricky.Infrastructure.Core
{
public enum eExpressionTextOperator
{
Equals,
Contains,
NotNullOrEmpty,
StartsWith,
}
public enum eExpressionNumberOperator
{
Equals,
NotEquals,
NotNull
}
public class ExpressionHelpers
{
public static Expression<Func<T, bool>> CreateExpressionTextNoneCompile<T>(string propertyName, string propertyValue, eExpressionTextOperator exOperator = eExpressionTextOperator.Equals)
{
if (String.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName");
if (String.IsNullOrEmpty(propertyValue)) throw new ArgumentNullException("propertyValue");
switch (exOperator)
{
case eExpressionTextOperator.Equals:
{
var arg = Expression.Parameter(typeof(T), "p");
var property = typeof(T).GetProperty(propertyName);
var comparison = Expression.Equal(
Expression.MakeMemberAccess(arg, property),
Expression.Constant(propertyValue));
var lambda = Expression.Lambda<System.Func<T, bool>>(comparison, arg);
return lambda;
}
case eExpressionTextOperator.NotNullOrEmpty:
{
var arg = Expression.Parameter(typeof(T), "p");
var property = typeof(T).GetProperty(propertyName);
var comparison = Expression.NotEqual(
Expression.MakeMemberAccess(arg, property),
Expression.Constant(null));
var lambda = Expression.Lambda<System.Func<T, bool>>(comparison, arg);
return lambda;
}
case eExpressionTextOperator.Contains:
{
var parameterExp = Expression.Parameter(typeof(T), "p");
var propertyExp = Expression.Property(parameterExp, propertyName);
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var someValue = Expression.Constant(propertyValue, typeof(string));
var methodExp = Expression.Call(propertyExp, method, someValue);
return Expression.Lambda<Func<T, bool>>(methodExp, parameterExp);
}
case eExpressionTextOperator.StartsWith:
{
var parameterExp = Expression.Parameter(typeof(T), "p");
var propertyExp = Expression.Property(parameterExp, propertyName);
MethodInfo method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
var someValue = Expression.Constant(propertyValue, typeof(string));
var methodExp = Expression.Call(propertyExp, method, someValue);
return Expression.Lambda<Func<T, bool>>(methodExp, parameterExp);
}
default:
return null;
}
}
public static Func<T, bool> ExpressionHasValue<T>(string propertyName)
{
var lambda = ExpressionHasValueNonCompile<T>(propertyName).Compile();
return lambda;
}
public static Expression<Func<T, bool>> ExpressionHasValueNonCompile<T>(string propertyName)
{
var arg = Expression.Parameter(typeof(T), "p");
var property = typeof(T).GetProperty(propertyName);
var comparison = Expression.Equal(
Expression.Property(Expression.MakeMemberAccess(arg, property), "HasValue"),
Expression.Constant(true));
var lambda = Expression.Lambda<System.Func<T, bool>>(comparison, arg);
return lambda;
}
public static Expression<Func<T, bool>> CreateExpressionNumberNoneCompile<T, TM>(string propertyName, TM propertyValue, eExpressionNumberOperator exOperator = eExpressionNumberOperator.Equals)
{
if (String.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName");
switch (exOperator)
{
case eExpressionNumberOperator.Equals:
{
var arg = Expression.Parameter(typeof(T), "p");
var property = typeof(T).GetProperty(propertyName);
var comparison = Expression.Equal(
Expression.MakeMemberAccess(arg, property),
Expression.Constant(propertyValue));
var lambda = Expression.Lambda<System.Func<T, bool>>(comparison, arg);
return lambda;
}
case eExpressionNumberOperator.NotNull:
{
var arg = Expression.Parameter(typeof(T), "p");
var property = typeof(T).GetProperty(propertyName);
var comparison = Expression.NotEqual(
Expression.MakeMemberAccess(arg, property),
Expression.Constant(null));
var lambda = Expression.Lambda<System.Func<T, bool>>(comparison, arg);
return lambda;
}
case eExpressionNumberOperator.NotEquals:
{
var arg = Expression.Parameter(typeof(T), "p");
var property = typeof(T).GetProperty(propertyName);
var comparison = Expression.NotEqual(
Expression.MakeMemberAccess(arg, property),
Expression.Constant(propertyValue));
var lambda = Expression.Lambda<System.Func<T, bool>>(comparison, arg);
return lambda;
}
default:
return null;
}
}
public static Func<T, bool> MakeQueryFilter<T>(string propertyName, object value, string dataOperator) where T : class
{
ParameterExpression parameter = Expression.Parameter(typeof(T), "p");
var property = typeof(T).GetProperty(propertyName);
MemberExpression propertyAccess = Expression.MakeMemberAccess(parameter, property);
Type propertyType = property.PropertyType;
//var typeDefinition = propertyType.GetGenericTypeDefinition();
//&& (typeDefinition == typeof(Nullable))
if ((propertyType.IsGenericType) && propertyType.GetGenericArguments().Count() > 0)
propertyType = propertyType.GetGenericArguments()[0];
object queryValue = null;
// convert the value appropriately
if (propertyType == typeof(System.Int32))
queryValue = Convert.ToInt32(value);
if (property.PropertyType == typeof(DateTime))
queryValue = Convert.ToDateTime(value);
if (property.PropertyType == typeof(Double))
queryValue = Convert.ToDouble(value);
if (property.PropertyType == typeof(String))
queryValue = Convert.ToString(value);
if (property.PropertyType == typeof(Guid))
queryValue = new Guid(value.ToString());
var constantValue = Expression.Constant(queryValue);
Type[] types = new Type[2];
types.SetValue(typeof(Expression), 0);
types.SetValue(typeof(Expression), 1);
var methodInfo = typeof(Expression).GetMethod(dataOperator, types);
var equality2 = (BinaryExpression)methodInfo.Invoke(null, new object[] { propertyAccess, constantValue });
//return equality2;
var lambda = Expression.Lambda<System.Func<T, bool>>(equality2).Compile();
return lambda;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentValidation;
using FluentValidation.Results;
namespace EBS.Application.DTO
{
public class MenuModel
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Icon { get; set; }
public int DisplayOrder { get; set; }
public int UrlType { get; set; }
public void Validate()
{
MenuModelValidator validator = new MenuModelValidator();
ValidationResult result = validator.Validate(this);
if (!result.IsValid)
{
StringBuilder sb = new StringBuilder();
result.Errors.ToList().ForEach(error => sb.Append(error.ErrorMessage + ";"));
throw new Exception(sb.ToString());
}
}
}
public class MenuModelValidator : AbstractValidator<MenuModel>
{
//.WithLocalizedMessage(() => "请输入{PropertyName}")
public MenuModelValidator()
{
RuleFor(m => m.Name).NotEmpty().WithLocalizedName(() => "菜单").WithLocalizedMessage(() => "请输入{PropertyName}");
// RuleFor(m => m.Password).NotEmpty().WithLocalizedName(() => "密码").WithLocalizedMessage(() => "请输入{PropertyName}");
}
}
}
|
using MikeGrayCodes.BuildingBlocks.Domain;
using System;
namespace MikeGrayCodes.Ordering.Domain.Entities.Buyers.Rules
{
public class PaymentSecurityNumberMustNotBeEmptyRule : IBusinessRule
{
private readonly string securityNumber;
internal PaymentSecurityNumberMustNotBeEmptyRule(string securityNumber)
{
this.securityNumber = securityNumber ?? throw new ArgumentNullException(nameof(securityNumber));
}
public bool IsBroken()
{
return string.IsNullOrWhiteSpace(securityNumber);
}
public string Message => "Payment security number must not be empty";
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using SistemaFacturacionWeb.Models;
using System.Configuration;
using System.Data.SqlClient;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
namespace SistemaFacturacionWeb.Controllers
{
[Authorize(Roles = "Facturador,Administrador")]
public class ComprasController : Controller
{
private SqlConnection con;
facturacionEntities db = new facturacionEntities();
private void Conectar()
{
string constr = ConfigurationManager.ConnectionStrings["facturacionConnectionString"].ToString();
con = new SqlConnection(constr);
}
public ActionResult Imprimir(string cod)
{
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Reportes"), "Compras.rpt"));
rd.SetParameterValue("@Param", cod);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Compras.pdf");
}
// GET: Compras
public ActionResult Index()
{
return View(db.Compras.ToList());
}
public ActionResult SaveOrder(string Cliente, String Factura, ComprasDetalles[] order)
{
string result = "Error! Order Is Not Complete!";
if (Cliente != null && Factura != null && order != null)
{
var CustomerId = Guid.NewGuid();
Compras model = new Compras();
model.CustomerId = CustomerId;
model.Proveedor = Cliente;
model.Factura = Factura;
model.OrderDate = DateTime.Now;
db.Compras.Add(model);
foreach (var item in order)
{
var orderId = Guid.NewGuid();
ComprasDetalles O = new ComprasDetalles();
O.OrderId = orderId;
O.Articulo = item.Articulo;
O.Cantidad = item.Cantidad;
O.Precio = item.Precio;
O.ArticuloCodigo = item.Articulo;
O.Total = item.Cantidad+ item.Precio;
O.CustomerId = CustomerId;
//
Conectar();
SqlCommand comando = new SqlCommand("update articulo set CantidadArticulo = ((CantidadArticulo)+('" + item.Cantidad + "')) where codigo='" + item.Articulo + "'", con);
con.Open();
int i = comando.ExecuteNonQuery();
con.Close();
db.ComprasDetalles.Add(O);
string Pid = Convert.ToString(CustomerId);
result = Pid;
}
db.SaveChanges();
//result = "Success! Order Is Complete!";
}
return Json(result, JsonRequestBehavior.AllowGet);
}
// GET: Compras/Details/5
public ActionResult Details(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Compras Compras = db.Compras.Find(id);
if (Compras == null)
{
return HttpNotFound();
}
return View(Compras);
}
// GET: Compras/Create
public ActionResult Create()
{
return View();
}
// POST: Compras/Create
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
// más información vea https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CustomerId,Cliente,Factura,OrderDate")] Compras Compras)
{
if (ModelState.IsValid)
{
Compras.CustomerId = Guid.NewGuid();
db.Compras.Add(Compras);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(Compras);
}
// GET: Compras/Edit/5
public ActionResult Edit(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Compras Compras = db.Compras.Find(id);
if (Compras == null)
{
return HttpNotFound();
}
return View(Compras);
}
// POST: Compras/Edit/5
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
// más información vea https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CustomerId,Cliente,Factura,OrderDate")] Compras Compras)
{
if (ModelState.IsValid)
{
db.Entry(Compras).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(Compras);
}
// GET: Compras/Delete/5
public ActionResult Delete(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Compras Compras = db.Compras.Find(id);
if (Compras == null)
{
return HttpNotFound();
}
return View(Compras);
}
// POST: Compras/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(Guid id)
{
Compras Compras = db.Compras.Find(id);
db.Compras.Remove(Compras);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class DestroyerTrigger : MonoBehaviour
{
public Text endText;
void Start ()
{
endText.text = "";
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
StartCoroutine(Test());
other.gameObject.SetActive(false);
endText.text = "Game Over!";
Test();
}
}
public IEnumerator Test()
{
yield return new WaitForSecondsRealtime(5);
SceneManager.LoadScene("Level02");
}
}
|
using System;
using MonoTouch.UIKit;
namespace iPadPos
{
public class ButtonCell : UITableViewCell, ICellSelectable
{
public Action Tapped = ()=>{};
public ButtonCell () : this("button")
{
//TextLabel.Layer.BorderWidth = .5f;
//TextLabel.Layer.CornerRadius = 5;
}
public ButtonCell(string key) : base(UITableViewCellStyle.Default,key)
{
TextLabel.Layer.BorderColor = TintColor.CGColor;
TextLabel.TextColor = TintColor;
TextLabel.TextAlignment = UITextAlignment.Center;
}
public string Text
{
get{ return TextLabel.Text; }
set { TextLabel.Text = value; }
}
// public override void LayoutSubviews ()
// {
// base.LayoutSubviews ();
// const float padding = 5;
//
// var frame = TextLabel.Frame;
// frame.Y = padding;
// frame.Height -= padding * 2;
// TextLabel.Frame = frame;
// }
#region ICellSelectable implementation
public virtual void OnSelect ()
{
if (Tapped != null)
Tapped ();
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
public class DoorScript : MonoBehaviour {
GameState gameState;
public int doorindex;
public string keyNameNeeded;
BoxCollider2D wallCollider;
public Sprite aperta;
public AudioClip enterInDoorSound;
// Use this for initialization
void Start () {
gameState = GameObject.Find ("GameState").GetComponent<GameState> ();
enterInDoorSound = GameObject.Find ("SoundsManager").GetComponent<SoundsScript> ().enterInDoorSound;
wallCollider = gameObject.transform.FindChild ("Wall").GetComponent<BoxCollider2D> ();
if (gameState.doorsState.ContainsKey (doorindex)) {
if (gameState.doorsState[doorindex]) { // if open
OpenDoor(false);
}
} else {
gameState.doorsState.Add (doorindex, false); // not open
}
}
void OnTriggerEnter2D(Collider2D coll){
if(coll.tag=="Player" && gameState.keysOwned.Contains(keyNameNeeded)){
OpenDoor (true);
gameState.keysOwned.Remove (keyNameNeeded);
}
}
void OpenDoor(bool playSound){
Debug.Log ("Open Door");
if(playSound)
SoundsScript.PlayOneShot ("enterInDoor", enterInDoorSound, GameObject.Find("SoundsManager").GetComponent<AudioSource> ());
GetComponent<SpriteRenderer>().sprite = aperta;
wallCollider.enabled = false;
GetComponent<BoxCollider2D> ().enabled = false;
if (gameState.doorsState.ContainsKey (doorindex)) {
gameState.doorsState[doorindex] = true;
}
//enabled = false;
}
}
|
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual;
using Pe.Stracon.SGC.Infraestructura.Core.Base;
using Pe.Stracon.SGC.Infraestructura.Core.Context;
using Pe.Stracon.SGC.Infraestructura.Core.QueryContract.Contractual;
using Pe.Stracon.SGC.Infraestructura.Repository.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
namespace Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual
{
/// <summary>
/// Implementación del repositorio Flujo Aprobacion
/// </summary>
public class ProcesoAuditoriaLogicRepository : QueryRepository<ProcesoAuditoriaLogic>, IProcesoAuditoriaLogicRepository
{
/// <summary>
/// Realiza la busqueda de Proceso Auditoria
/// </summary>
/// <param name="codigoAuditoria">Código de auditoria</param>
/// <param name="codigoUnidadOperativa">Código de unidad operativa</param>
/// <param name="fechaPlanificada">Fecha planificada</param>
/// <param name="fechaEjecucion">Fecha de Ejecución</param>
/// <param name="estadoRegistro">Estado de registro</param>
/// <returns>Procesos de Auditoria</returns>
public List<ProcesoAuditoriaLogic> BuscarBandejaProcesoAuditoria(
Guid? codigoAuditoria,
Guid? codigoUnidadOperativa,
DateTime? fechaPlanificada,
DateTime? fechaEjecucion,
string estadoRegistro
)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_AUDITORIA",SqlDbType.UniqueIdentifier) { Value = (object)codigoAuditoria ?? DBNull.Value},
new SqlParameter("CODIGO_UNIDAD_OPERATIVA",SqlDbType.UniqueIdentifier) { Value = (object)codigoUnidadOperativa ?? DBNull.Value},
new SqlParameter("FECHA_PLANIFICADA",SqlDbType.DateTime) { Value = (object)fechaPlanificada ?? DBNull.Value},
new SqlParameter("FECHA_EJECUCION",SqlDbType.DateTime) { Value = (object)fechaEjecucion ?? DBNull.Value},
new SqlParameter("ESTADO_REGISTRO",SqlDbType.NVarChar) { Value = (object)estadoRegistro ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ProcesoAuditoriaLogic>("CTR.USP_AUDITORIA_SEL", parametros).ToList();
return result;
}
/// <summary>
/// Verifica si se repite un proceso de Auditoria
/// </summary>
/// <param name="codigoUnidadOperativa">Código de Unidad Operativa</param>
/// <param name="fechaPlanificada">Fecha Planificada</param>
/// <returns>Indicador con el resultado de la operación</returns>
public List<ProcesoAuditoriaLogic> RepiteProcesoAuditoria(
Guid codigoUnidadOperativa,
DateTime fechaPlanificada
)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_UNIDAD_OPERATIVA",SqlDbType.UniqueIdentifier) { Value = (object)codigoUnidadOperativa ?? DBNull.Value},
new SqlParameter("FECHA_PLANIFICADA",SqlDbType.DateTime) { Value = (object)fechaPlanificada ?? DBNull.Value}
};
var result = this.dataBaseProvider.ExecuteStoreProcedure<ProcesoAuditoriaLogic>("CTR.USP_AUDITORIA_EXISTE_SEL", parametros).ToList();
return result;
}
}
}
|
namespace RosPurcell.Web.Constants.Images
{
public enum BreakPointSet
{
NotDefined,
Hero,
Teaser
}
}
|
using DistCWebSite.Core.Entities;
using DistCWebSite.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DistCWebSite.Infrastructure
{
public class EMDistributorPlanSaleMainRespository: IEMDistributorPlanSaleMainRespository
{
#region
public int Add(List<M_EMDistributorPlanSaleMain> list)
{
var ctx = new DistCSiteContext();
ctx.M_EMDistributorPlanSaleMain.AddRange(list);
ctx.SaveChanges();
return list[0].MainID;
}
public int Delete(M_EMDistributorPlanSaleMain entity)
{
var ctx = new DistCSiteContext();
ctx.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
return ctx.SaveChanges();
}
public List<M_EMDistributorPlanSaleMain> Get()
{
var ctx = new DistCSiteContext();
return ctx.M_EMDistributorPlanSaleMain.Where(x => x.Active == true).ToList();
}
public List<M_EMDistributorPlanSaleMain> Get(M_EMDistributorPlanSaleMain entity)
{
var ctx = new DistCSiteContext();
return ctx.M_EMDistributorPlanSaleMain.Where(x => x.Active == true && x.ProcInstID == entity.ProcInstID).ToList();
}
public int Update(M_EMDistributorPlanSaleMain entity)
{
var ctx = new DistCSiteContext();
ctx.Entry(entity).State = System.Data.Entity.EntityState.Modified;
return ctx.SaveChanges();
}
#endregion
}
}
|
using System;
namespace week05b
{
class MainClass
{
enum Days {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
enum Colour {Red, Green, Blue, Yellow};
enum Menu {New, Open, Save, Exit};
public static void Main (string[] args)
{
/*
* Enumerators are used to group related constants that are readable by
* programmers but are simple numbers behind the scenes
* These are often used for codes such as days of the week or common colors
*
* You declare the new enumerator type with the enum keyword and then a name.
* From there you enter the names of its types
*
*/
Days currentDay = Days.Wednesday;
Days tomorrow = Days.Thursday;
Colour favouriteColour = Colour.Blue;
Console.WriteLine ("Enter your favourite color");
string input = Console.ReadLine ().ToLower ();
switch (input) {
case "blue":
favouriteColour = Colour.Blue;
break;
case "red":
favouriteColour = Colour.Red;
break;
case "green":
favouriteColour = Colour.Green;
break;
case "yellow":
favouriteColour = Colour.Yellow;
break;
default:
Console.WriteLine ("Invalid input");
break;
}
if (favouriteColour == Colour.Green) {
Console.WriteLine ("Correct answer");
} else {
Console.WriteLine ("Bad Choice");
}
Console.WriteLine ("1: New\n2: Open\n3: Save\n4: Exit");
int userInput = int.Parse (Console.ReadLine ());
Menu selection = Menu.Save;
switch (userInput) {
case 1:
selection = Menu.New;
break;
case 2:
selection = Menu.Open;
break;
case 3:
selection = Menu.Save;
break;
case 4:
selection = Menu.Exit;
break;
default:
Console.WriteLine ("Invalid input");
break;
}
Console.WriteLine ("User selected {0}", selection);
if (selection == Menu.New)
Console.WriteLine ("The file has been created");
else if (selection == Menu.Open)
Console.WriteLine ("Navigate to the file you would like to open");
else if (selection == Menu.Save)
Console.WriteLine ("The file has been saved");
else if (selection == Menu.Exit)
Console.WriteLine ("Program has been closed");
}
}
}
|
using Cs_Gerencial.Aplicacao.Interfaces;
using Cs_Gerencial.Dominio.Entities;
using Cs_Notas.Aplicacao.Interfaces;
using Cs_Notas.Dominio.Entities;
using Cs_Notas.Windows;
using Cs_Notas.Windows.Procuracao;
using System;
using System.Collections.Generic;
using System.ComponentModel;
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 Cs_Notas.WindowsAgurde
{
/// <summary>
/// Lógica interna para AgurardeSalvandoProcuracao.xaml
/// </summary>
public partial class AgurardeSalvandoProcuracao : Window
{
BackgroundWorker worker;
DigitarProcuracao _digitarProcuracao;
string janelaChamada;
CadProcuracao _procuracao;
Principal _principal;
Cs_Notas.Dominio.Entities.Usuario _usuario;
List<AtoConjuntos> _listaAtoConjuntos;
List<Selos> _selos;
private readonly IAppServicoPessoas _AppServicoPessoas = BootStrap.Container.GetInstance<IAppServicoPessoas>();
private readonly IAppServicoNomes _AppServicoNomes = BootStrap.Container.GetInstance<IAppServicoNomes>();
private readonly IAppServicoCadProcuracao _AppServicoCadProcuracao = BootStrap.Container.GetInstance<IAppServicoCadProcuracao>();
private readonly IAppServicoAtoConjuntos _AppServicoAtoConjuntos = BootStrap.Container.GetInstance<IAppServicoAtoConjuntos>();
private readonly IAppServicoImovel _AppServicoImovel = BootStrap.Container.GetInstance<IAppServicoImovel>();
private readonly IAppServicoBensAtosConjuntos _AppServicoBensAtosConjuntos = BootStrap.Container.GetInstance<IAppServicoBensAtosConjuntos>();
private readonly IAppServicoParteConjuntos _IAppServicoParteConjuntos = BootStrap.Container.GetInstance<IAppServicoParteConjuntos>();
private readonly IAppServicoSelos _AppServicoSelos = BootStrap.Container.GetInstance<IAppServicoSelos>();
private readonly IAppServicoItensCustas _AppServicoItensCustas = BootStrap.Container.GetInstance<IAppServicoItensCustas>();
public AgurardeSalvandoProcuracao(DigitarProcuracao digitarProcuracao)
{
_procuracao = digitarProcuracao._procuracao;
_digitarProcuracao = digitarProcuracao;
janelaChamada = "digitarProcuracao";
InitializeComponent();
}
public AgurardeSalvandoProcuracao(CadProcuracao procuracao, List<AtoConjuntos> listaAtoConjuntos, Principal principal, Cs_Notas.Dominio.Entities.Usuario usuario, List<Selos> selos)
{
_procuracao = procuracao;
_principal = principal;
_usuario = usuario;
_listaAtoConjuntos = listaAtoConjuntos;
janelaChamada = "iniciarPrimeiraDigitacaoProcuracao";
_selos = selos;
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += worker_DoWork;
worker.ProgressChanged += worker_ProgressChanged;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.RunWorkerAsync();
}
catch (Exception)
{
MessageBox.Show("Ocorreu um erro ao tentar salvar a Escritua. Favor imformar ao Suporte.", "Erro", MessageBoxButton.OK, MessageBoxImage.Error);
Close();
}
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
if (janelaChamada == "iniciarPrimeiraDigitacaoProcuracao")
{
SalvarAddProcuracao();
SalvarAddAtoConjunto();
SalvaSeloReservado();
}
else
{
SalvarUpdateProcuracao();
SalvarItensCustas();
SalvarSelo();
}
}
catch (Exception ex)
{
MessageBox.Show("Ocorrreu um erro inesperado. " + ex.Message);
_digitarProcuracao.estado = "erro";
}
}
private void SalvarSelo()
{
var selo = _AppServicoSelos.ConsultarPorSerieNumero(_procuracao.Selo.Substring(0, 4), Convert.ToInt32(_procuracao.Selo.Substring(4, 5)));
selo.FormUtilizado = "Digitar Procuracão";
selo.IdAto = _procuracao.ProcuracaoId;
selo.DataPratica = _procuracao.DataLavratura;
if (_procuracao.Recibo != null && _procuracao.Recibo != "")
selo.Recibo = Convert.ToInt32(_procuracao.Recibo);
selo.TipoCobranca = _procuracao.TipoCobranca;
selo.Emolumentos = _procuracao.Emolumentos;
selo.Fetj = _procuracao.Fetj;
selo.Fundperj = _procuracao.Fundperj;
selo.Funperj = _procuracao.Funprj;
selo.Funarpen = _procuracao.Funarpen;
selo.Pmcmv = _procuracao.Pmcmv;
selo.Iss = _procuracao.Iss;
selo.Mutua = _procuracao.Mutua;
selo.Acoterj = _procuracao.Acoterj;
selo.Distribuicao = _procuracao.Distribuicao;
selo.Total = _procuracao.Total;
selo.Conjunto = "N";
selo.Escrevente = _procuracao.Login;
selo.Natureza = "PROCURAÇÂO";
_AppServicoSelos.SalvarSeloModificado(selo);
for (int y = 0; y < _digitarProcuracao.listaAtoConjuntos.Count; y++)
{
var conjunto = _AppServicoSelos.ConsultarPorSerieNumero(_digitarProcuracao.listaAtoConjuntos[y].Selo.Substring(0, 4), Convert.ToInt32(_digitarProcuracao.listaAtoConjuntos[y].Selo.Substring(4, 5)));
conjunto.Conjunto = "S";
conjunto.Sistema = "NOTAS";
conjunto.DataPratica = _procuracao.DataLavratura;
if (_procuracao.Recibo != "" && _procuracao.Recibo != null)
conjunto.Recibo = Convert.ToInt32(_procuracao.Recibo);
conjunto.Escrevente = _procuracao.Login;
conjunto.Natureza = _digitarProcuracao.listaAtoConjuntos[y].TipoAto;
_AppServicoSelos.SalvarSeloModificado(selo);
}
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (janelaChamada == "iniciarPrimeiraDigitacaoProcuracao")
{
var digitarEscritura = new DigitarProcuracao(_procuracao, _usuario, true);
digitarEscritura.Owner = _principal;
this.Close();
digitarEscritura.ShowDialog();
}
this.Close();
}
private void SalvarAddProcuracao()
{
_AppServicoCadProcuracao.Add(_procuracao);
}
private void SalvarUpdateProcuracao()
{
_AppServicoCadProcuracao.SalvarAlteracaoProcuracao(_procuracao);
}
private void SalvarItensCustas()
{
var custasExcluir = _AppServicoItensCustas.ObterItensCustasPorIdProcuracao(_procuracao.ProcuracaoId);
for (int i = 0; i < custasExcluir.Count; i++)
{
var excluirBanco = _AppServicoItensCustas.GetById(custasExcluir[i].ItensCustasId);
_AppServicoItensCustas.Remove(excluirBanco);
}
for (int i = 0; i < _digitarProcuracao.listaItensCustas.Count; i++)
{
var adicionarBanco = new ItensCustas();
adicionarBanco = _digitarProcuracao.listaItensCustas[i];
adicionarBanco.IdProcuracao = _procuracao.ProcuracaoId;
_AppServicoItensCustas.Add(adicionarBanco);
}
}
private void SalvarAddAtoConjunto()
{
for (int i = 0; i < _listaAtoConjuntos.Count; i++)
{
_listaAtoConjuntos[i].IdProcuracao = _procuracao.ProcuracaoId;
_AppServicoAtoConjuntos.Add(_listaAtoConjuntos[i]);
}
}
private void SalvaSeloReservado()
{
for (int i = 0; i < _selos.Count; i++)
{
if (i == 0)
{
var selo = _AppServicoSelos.GetById(_selos[i].SeloId);
selo.Status = "UTILIZADO";
selo.FormUtilizado = "Digitar Procuração";
selo.IdAto = _procuracao.ProcuracaoId;
selo.DataPratica = _procuracao.DataLavratura;
if (_procuracao.Recibo != null && _procuracao.Recibo != "")
selo.Recibo = Convert.ToInt32(_procuracao.Recibo);
selo.TipoCobranca = _procuracao.TipoCobranca;
selo.Emolumentos = _procuracao.Emolumentos;
selo.Fetj = _procuracao.Fetj;
selo.Fundperj = _procuracao.Fundperj;
selo.Funperj = _procuracao.Funprj;
selo.Funarpen = _procuracao.Funarpen;
selo.Pmcmv = _procuracao.Pmcmv;
selo.Iss = _procuracao.Iss;
selo.Mutua = _procuracao.Mutua;
selo.Acoterj = _procuracao.Acoterj;
selo.Distribuicao = _procuracao.Distribuicao;
selo.Total = _procuracao.Total;
selo.Conjunto = "N";
selo.Escrevente = _procuracao.Login;
selo.Natureza = "PROCURAÇÃO";
_AppServicoSelos.SalvarSeloModificado(selo);
}
}
for (int y = 0; y < _listaAtoConjuntos.Count; y++)
{
var selo = _AppServicoSelos.GetById(_selos[y + 1].SeloId);
selo.Status = "UTILIZADO";
selo.FormUtilizado = "Digitar Escrituras";
selo.Conjunto = "S";
selo.IdAto = _listaAtoConjuntos[y].ConjuntoId;
selo.DataPratica = _procuracao.DataLavratura;
selo.Escrevente = _procuracao.Login;
selo.Natureza = _listaAtoConjuntos[y].TipoAto;
_AppServicoSelos.SalvarSeloModificado(selo);
}
}
}
}
|
namespace TripDestination.Services.Web.Services.Contracts
{
using System;
public interface ICacheServices
{
T Get<T>(string itemName, Func<T> getDataFunc, int durationInSeconds);
void Remove(string itemName);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Specialized;
namespace primer
{
class FindFirstNonRepeatingChar
{
public static char findFirstNonRepeatingChar(string str) {
// first pass , count the chars
Dictionary<char, int> dictionary = new Dictionary<char, int>();
foreach (char c in str) {
if (dictionary.ContainsKey(c))
{
dictionary[c]++;
}
else {
dictionary[c] = 1;
}
}
foreach (var kv in dictionary) {
if (kv.Value == 1)
{
return kv.Key;
}
}
return '!';
}
/*having the numbers in the array, c will be found first, */
public static char findFirstNonRepeatingChar2(string str)
{
// first pass , count the chars
int[] dictionary = new int[128];
foreach (char c in str)
{
dictionary[c]++;
}
for (int t = 0; t < dictionary.Length; t++) {
if (dictionary[t] == 1)
return (char)t;
}
return '!';
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using MoreMountains.Tools;
using MoreMountains.Feedbacks;
namespace MoreMountains.CorgiEngine
{
public class AICrawler : MovingPlatform
{
/// This component works similar to Moving Platforms but have custom options for rotating Model prefab on path nodes.
/// Usage: Set this at Parent object with all components you like then make a Child with, at least, and Animator and set it on the inspector Model slot.
/// Intented to be used on Corgi Engine 6.4+
/// v1.0 (Muppo, 2020)
[System.Serializable]
public class PathMovementNode
{
public float nodeSpeed;
public bool RotationLeft;
public bool RotationRight;
// public MMFeedbacks nodeFeedback; // Check NODE FEEDBACKS below for info regarding this line.
}
[Header("Extra Settings")]
[MMInformation("If a Model is set, Rotation will rotate it on a 90º basis. Start Delay is applied any time the AI respawns."+
"\n<b>Warning</b>: Path Element Options size <b>must</b> match Path Elements size. Both directions checked means <i>No Rotation</i>.",MoreMountains.Tools.MMInformationAttribute.InformationType.Info,false)]
public Transform Model;
public float StartDelay;
[MMReadOnly] public float rotationValue;
// WalkingToRight means character will rotate -90 degrees on waypoints if True, otherwhise it takes 90 degrees value. It's set by Loop Initial Movement Direction.
// [HideInInspector]
[MMReadOnly] public bool WalkingToRight;
public List<PathMovementNode> PathElementsOptions;
protected Animator _animator;
protected Character _character;
protected float MovementSpeedORG;
protected float StartDelayORG;
/// Awake
protected override void Awake()
{
MovementSpeedORG = MovementSpeed;
StartDelayORG = StartDelay;
Initialization();
}
/// Initialization
protected override void Initialization()
{
base.Initialization();
_character = GetComponent<Character>();
CycleOption = CycleOptions.Loop;
StartDelay = StartDelayORG;
if (Model != null)
{
_animator = Model.gameObject.GetComponent<Animator>();
_animator.SetBool("Alive", true);
_animator.SetBool("Walking", true);
}
else
{ Debug.LogWarning("This component needs a Child with and Animator at least to work properly."); }
if(LoopInitialMovementDirection == MovementDirection.Ascending)
{ WalkingToRight = true; }
// We set the model in the right position for the rotation sequence
if(WalkingToRight) {
Model.rotation = Quaternion.Euler(0,0,90);
} else {
Model.rotation = Quaternion.Euler(0,0,0);
}
}
/// Update with check for delayed start
protected override void Update()
{
if(PathElements == null || PathElements.Count < 1 || _endReached || !CanMove)
{ return; }
// Check if a delay is set and start it before moving.
if(StartDelay > 0)
{
StartCoroutine(WaitABit());
}
else
{
Move();
}
}
/// Waits for the delay
IEnumerator WaitABit()
{
yield return new WaitForSeconds(StartDelay);
StartDelay = 0;
}
/// Move override with the extra features
protected override void Move()
{
_waiting -= Time.deltaTime;
if (_waiting > 0)
{
CurrentSpeed = Vector3.zero;
return;
}
_initialPosition = transform.position;
MoveAlongThePath();
_distanceToNextPoint = (transform.position - (_originalTransformPosition + _currentPoint.Current)).magnitude;
if(_distanceToNextPoint < MinDistanceToGoal)
{
if (PathElements.Count > _currentIndex)
{
_waiting = PathElements[_currentIndex].Delay;
/// Check if there is any Path Elements features set and, if so, changes next path element to the set value on the array
/// NODE SPEED
if (PathElementsOptions.Count > 0)
{
if (PathElementsOptions[_currentIndex].nodeSpeed > 0)
{
MovementSpeed = PathElementsOptions[_currentIndex].nodeSpeed;
}
if (PathElementsOptions[_currentIndex].nodeSpeed == 0)
{
MovementSpeed = MovementSpeedORG;
}
}
/// NODE ROTATION
if((PathElementsOptions[_currentIndex].RotationLeft) && (PathElementsOptions[_currentIndex].RotationRight))
{ return; }
if (PathElementsOptions[_currentIndex].RotationLeft)
{
rotationValue = 30f;
StartCoroutine(RotationSequence());
}
else if (PathElementsOptions[_currentIndex].RotationRight)
{
rotationValue = -30f;
StartCoroutine(RotationSequence());
}
// /// NODE FEEDBACKS
// /// In case you want to have Feedbacks per node, uncomment this and the Feedbacks line on the enum at the start of this script.
// if(PathElementsOptions[_currentIndex].nodeFeedback != null)
// {
// PathElementsOptions[_currentIndex].nodeFeedback?.PlayFeedbacks();
// }
}
_previousPoint = _currentPoint.Current;
_currentPoint.MoveNext();
}
_finalPosition = transform.position;
CurrentSpeed = (_finalPosition-_initialPosition) / Time.deltaTime;
if (_endReached)
{
CurrentSpeed = Vector3.zero;
}
}
///
protected virtual IEnumerator RotationSequence()
{
Model.Rotate (Vector3.forward * rotationValue);
yield return new WaitForSeconds(0.05f);
Model.Rotate (Vector3.forward * rotationValue);
yield return new WaitForSeconds(0.05f);
Model.Rotate (Vector3.forward * rotationValue);
}
}
} |
namespace RRExpress.Seller.Models {
public class GoodsFilter {
public int BigCat { get; set; }
public int Channel { get; set; }
public string SortType { get; set; }
public string Name { get; set; }
}
}
|
using Common.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Windows.Data;
namespace UI.Converters
{
public class CategoryGroupToDisplayNameConverter : IValueConverter
{
private readonly Dictionary<CategoryGroups, string> _categoryGroupsDisplayNames;
public CategoryGroupToDisplayNameConverter()
{
_categoryGroupsDisplayNames = new Dictionary<CategoryGroups, string>();
SetDisplayNames();
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var displayName = string.Empty;
if (value is CategoryGroups categoryGroup)
{
displayName = Enum.GetName(typeof(CategoryGroups), categoryGroup);
var attributesCollection = typeof(CategoryGroups)
.GetField(displayName)
.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributesCollection.Length > 0)
{
displayName = ((DisplayAttribute)attributesCollection[0]).Name;
}
}
return displayName;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var categoryGroup = CategoryGroups.Expenses;
if (value is string displayName)
{
foreach (var categoryGroupName in _categoryGroupsDisplayNames)
{
if (categoryGroupName.Value == displayName)
{
categoryGroup = categoryGroupName.Key;
break;
}
}
}
return categoryGroup;
}
private void SetDisplayNames()
{
foreach (CategoryGroups categoryGroup in Enum.GetValues(typeof(CategoryGroups)))
{
var displayName = Enum.GetName(typeof(CategoryGroups), categoryGroup);
var attributesCollection = typeof(CategoryGroups)
.GetField(displayName)
.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributesCollection.Length > 0)
{
displayName = ((DisplayAttribute)attributesCollection[0]).Name;
}
_categoryGroupsDisplayNames.Add(categoryGroup, displayName);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class LevelManager : MonoBehaviour {
public GameObject Item;
// Use this for initialization
void Start () {
NewItem();
}
public void NewItem()
{
GameObject x = Instantiate( Item, new Vector3(Random.Range(17,-18)*1.2f,1, Random.Range(8,-9)*1.2f), Quaternion.identity ) as GameObject;
ItemScript item = x.GetComponent<ItemScript>();
item.levelManager = this;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ace
{
/// <summary>
/// メッシュを表示する3Dオブジェクトの機能を提供するクラス
/// </summary>
public class ModelObject3D : Object3D
{
swig.CoreModelObject3D coreObject = null;
public ModelObject3D()
{
coreObject = Engine.ObjectSystemFactory.CreateModelObject3D();
GC.Object3Ds.AddObject(coreObject.GetPtr(), this);
commonObject = coreObject;
}
public override void Destroy()
{
coreObject = null;
base.Destroy();
}
protected override void OnStart() { }
protected override void OnUpdate() { }
internal protected override void OnDrawAdditionally() { }
/// <summary>
/// 描画に使用するモデルを設定する。
/// </summary>
/// <param name="model">モデル</param>
public void SetModel(Model model)
{
coreObject.SetModel(model.SwigObject);
}
/// <summary>
/// メッシュグループを追加する。
/// </summary>
public void AddMeshGroup()
{
coreObject.AddMeshGroup();
}
/// <summary>
/// メッシュグループの個数を取得する。
/// </summary>
/// <returns>個数</returns>
public int GetMeshGroupCount()
{
return coreObject.GetMeshGroupCount();
}
/// <summary>
/// 描画に使用するメッシュを追加する。
/// </summary>
/// <param name="meshGroupIndex">メッシュグループのインデックス</param>
/// <param name="mesh">メッシュ</param>
public void AddMesh(int meshGroupIndex, Mesh mesh)
{
coreObject.AddMesh(meshGroupIndex, mesh.SwigObject);
}
/// <summary>
/// 描画に使用するデフォーマーを設定する。
/// </summary>
/// <param name="meshGroupIndex">メッシュグループのインデックス</param>
/// <param name="deformer">デフォーマー</param>
public void SetDeformer(int meshGroupIndex, Deformer deformer)
{
coreObject.SetDeformer(meshGroupIndex, deformer.SwigObject);
}
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using SimpleJSON;
using System.Collections;
public class Storage : MonoBehaviour
{
public ContentController contentController;
public GameObject Item, hantuList, equipmentButton,ErrorCode, ValidationError;
public GameObject bintang1stats,bintang2stats,bintang3stats,bintang4stats,bintang5stats,loading;
public Text hantuName, attack, defense, hp,level,type ;
private bool toHome = true;
public GameObject show;
public string hantuPlayerId, hantuGrade;
public string file;
//test
public EXPdistribution exps;
public HantuLore LoreScript;
public void OnEquipmentClick () {
PlayerPrefs.SetString (Link.FOR_CONVERTING, hantuPlayerId);
PlayerPrefs.SetString (Link.FOR_CONVERTING_2, file);
SceneManagerHelper.LoadScene ("Equipment");
}
public void OnBack () {
SceneManagerHelper.LoadScene ("Home");
}
private void Start () {
//StartCoroutine (GetHantuUserLocal ());
StartCoroutine (GetHantuUser ());
if (SceneManager.GetActiveScene().name=="EXPDis") {
exps=GameObject.Find ("ExpDistribution").GetComponent<EXPdistribution>();
}
}
public void Reload () {
StartCoroutine (GetHantuUser ());
}
public IEnumerator GetHantuNextLevel ()
{
string url = Link.url + "getDataHantuUser";
WWWForm form = new WWWForm ();
form.AddField (Link.ID, PlayerPrefs.GetString(Link.ID));
WWW www = new WWW(url,form);
yield return www;
Debug.Log (www.text);
if (www.error == null) {
var jsonString = JSON.Parse (www.text);
PlayerPrefs.SetString (Link.FOR_CONVERTING, jsonString["code"]);
if (PlayerPrefs.GetString (Link.FOR_CONVERTING) == "0") {
}
else if (PlayerPrefs.GetString(Link.FOR_CONVERTING) == "33")
{
ValidationError.SetActive(true);
}
} else {
Debug.Log ("Gagal le");
}
}
public IEnumerator GetHantuUser ()
{
string url = Link.url + "getDataHantuUser";
WWWForm form = new WWWForm ();
form.AddField (Link.ID, PlayerPrefs.GetString(Link.ID));
form.AddField("DID", PlayerPrefs.GetString(Link.DEVICE_ID));
WWW www = new WWW(url,form);
yield return www;
Debug.Log (www.text);
if (www.error == null) {
var jsonString = JSON.Parse (www.text);
PlayerPrefs.SetString (Link.FOR_CONVERTING, jsonString ["code"]);
if (PlayerPrefs.GetString (Link.FOR_CONVERTING) == "0") {
for (int x = contentController.Content.childCount - 1; x >= 0; x--) {
Destroy (contentController.Content.GetChild (x).gameObject);
}
GameObject[] entry;
entry = new GameObject[int.Parse (jsonString ["count"])];
for (int x = 0; x < int.Parse (jsonString ["count"]); x++) {
entry [x] = Instantiate (Item);
entry [x].GetComponent<StorageItem> ().icon.sprite = Resources.Load<Sprite> ("icon_char/" + jsonString ["data"] [x] ["HantuFile"]);
entry [x].GetComponent<StorageItem> ().PlayerHantuId = jsonString ["data"] [x] ["HantuPlayerID"];
entry [x].GetComponent<StorageItem> ().hantuId = jsonString ["data"] [x] ["HantuId"];
entry [x].GetComponent<StorageItem> ().hantuGrade = jsonString ["data"] [x] ["HantuGrade"];
entry [x].GetComponent<StorageItem> ().name = jsonString ["data"] [x] ["HantuNama"];
entry [x].GetComponent<StorageItem> ().file = jsonString ["data"] [x] ["HantuFile"];
entry [x].GetComponent<StorageItem> ().Level.text = jsonString ["data"] [x] ["HantuLevel"];
entry [x].GetComponent<StorageItem> ().type = jsonString ["data"] [x] ["HantuType"];
entry [x].GetComponent<StorageItem> ().attack = int.Parse (jsonString ["data"] [x] ["HantuAttack"]);
entry [x].GetComponent<StorageItem> ().defense = int.Parse (jsonString ["data"] [x] ["HantuDefense"]);
entry [x].GetComponent<StorageItem> ().stamina = int.Parse (jsonString ["data"] [x] ["HantuStamina"]);
//misal posisi monster saat ini level 1
entry [x].GetComponent<StorageItem> ().Targetnextlevel = jsonString ["data"] [x] ["Targetnextlevel"]; //misal ini 450 adalah level 2
entry [x].GetComponent<StorageItem> ().Targetlusalevel = jsonString ["data"] [x] ["Targetlusalevel"]; //yg ini 960 adalah level 3 (baru sy buatkan di API)
//nah, animasinya kalo udh mentok 450,
//barnya ulang dari 0 kan ya. akhirnya jangan 450 lg,
//tp ambil yg 960, kan udah naik level.
if (int.Parse(jsonString["data"][x]["HantuStat"]) == 1)
{
entry[x].transform.Find("NewStat").gameObject.SetActive(true);
}
else {
entry[x].transform.Find("NewStat").gameObject.SetActive(false);
}
entry [x].GetComponent<StorageItem> ().exp = jsonString ["data"] [x] ["monstercurrentexp"];
entry [x].transform.SetParent (contentController.Content, false);
if (SceneManager.GetActiveScene ().name == "EXPDis") {
if (int.Parse (jsonString ["data"] [x] ["HantuPlayerID"]) == int.Parse (exps.idhantuplayer)) {
Debug.Log ("getin");
exps.att = jsonString ["data"] [x] ["HantuAttack"];
exps.def = jsonString ["data"] [x] ["HantuDefense"];
exps.stam = jsonString ["data"] [x] ["HantuStamina"];
//exps.Targetnextlevel=float.Parse(jsonString["data"][x]["Targetnextlevel"]);
//exps.att.text = jsonString["data"][x]["HantuAttack"];
//exps.def.text = jsonString["data"][x]["HantuDefense"];
//exps.stam.text = jsonString["data"][x]["HantuStamina"];
}
}
var nilai = int.Parse (jsonString ["count"]) - 1;
}
}
else if (PlayerPrefs.GetString(Link.FOR_CONVERTING) == "33")
{
ValidationError.SetActive(true);
loading.SetActive(false);
}
else {
Debug.Log("GAGAL");
//ErrorCode.transform.FindChild ("Dialog").gameObject.SetActive (true);
//ErrorCode.SetActive (true);
ValidationError.SetActive(true);
}
yield return new WaitForSeconds (.5f);
ErrorCode.SetActive (false);
loading.SetActive (false);
} else {
ErrorCode.transform.Find ("Dialog").gameObject.SetActive (true);
ErrorCode.SetActive (true);
}
}
private IEnumerator GetHantuUserLocal ()
{
GameObject[] entry;
entry = new GameObject[6];
//for (int x = 0; x < 6; x++) {
entry [0] = Instantiate (Item);
entry [1] = Instantiate (Item);
entry [2] = Instantiate (Item);
entry [3] = Instantiate (Item);
entry [4] = Instantiate (Item);
entry [5] = Instantiate (Item);
entry[0].GetComponent<StorageItem>().icon.sprite = Resources.Load<Sprite>("icon_char/" + "Kunti_Fire");
entry[1].GetComponent<StorageItem>().icon.sprite = Resources.Load<Sprite>("icon_char/" + "Genderuwo_Fire");
entry[0].GetComponent<StorageItem>().PlayerHantuId = "PemburuHantu";
entry[0].GetComponent<StorageItem>().hantuId = "H001";
entry[0].GetComponent<StorageItem>().name = "Kuntilanak";
entry[0].GetComponent<StorageItem>().file = "Kunti_Fire";
entry[0].GetComponent<StorageItem>().Level.text = "40";
entry[0].GetComponent<StorageItem>().type = "Fire";
entry[0].GetComponent<StorageItem>().attack = 400;
entry[0].GetComponent<StorageItem>().defense = 400;
entry[0].GetComponent<StorageItem>().stamina = 400;
entry[0].transform.SetParent (contentController.Content, false);
entry[1].GetComponent<StorageItem>().PlayerHantuId = "PemburuHantu";
entry[1].GetComponent<StorageItem>().hantuId = "H002";
entry[1].GetComponent<StorageItem>().name = "Genderuwo";
entry[1].GetComponent<StorageItem>().file = "Genderuwo_Fire";
entry[1].GetComponent<StorageItem>().Level.text = "40";
entry[1].GetComponent<StorageItem>().type = "Fire";
entry[1].GetComponent<StorageItem>().attack = 400;
entry[1].GetComponent<StorageItem>().defense = 400;
entry[1].GetComponent<StorageItem>().stamina = 400;
entry[1].transform.SetParent (contentController.Content, false);
entry[2].GetComponent<StorageItem>().icon.sprite = Resources.Load<Sprite>("icon_char/" + "Pocong_Fire");
entry[2].GetComponent<StorageItem>().PlayerHantuId = "PemburuHantu";
entry[2].GetComponent<StorageItem>().hantuId = "H003";
entry[2].GetComponent<StorageItem>().name = "Pocong";
entry[2].GetComponent<StorageItem>().file = "Pocong_Fire";
entry[2].GetComponent<StorageItem>().Level.text = "40";
entry[2].GetComponent<StorageItem>().type = "Fire";
entry[2].GetComponent<StorageItem>().attack = 400;
entry[2].GetComponent<StorageItem>().defense = 400;
entry[2].GetComponent<StorageItem>().stamina = 400;
entry[2].transform.SetParent (contentController.Content, false);
entry[3].GetComponent<StorageItem>().icon.sprite = Resources.Load<Sprite>("icon_char/" + "SusterNgesot_Fire");
entry[3].GetComponent<StorageItem>().PlayerHantuId = "PemburuHantu";
entry[3].GetComponent<StorageItem>().hantuId = "H004";
entry[3].GetComponent<StorageItem>().name = "Suster Ngesot";
entry[3].GetComponent<StorageItem>().file = "SusterNgesot_Fire";
entry[3].GetComponent<StorageItem>().Level.text = "40";
entry[3].GetComponent<StorageItem>().type = "Fire";
entry[3].GetComponent<StorageItem>().attack = 400;
entry[3].GetComponent<StorageItem>().defense = 400;
entry[3].GetComponent<StorageItem>().stamina = 400;
entry[3].transform.SetParent (contentController.Content, false);
entry[4].GetComponent<StorageItem>().icon.sprite = Resources.Load<Sprite>("icon_char/" + "Babingepet_Fire");
entry[4].GetComponent<StorageItem>().PlayerHantuId = "PemburuHantu";
entry[4].GetComponent<StorageItem>().hantuId = "H005";
entry[4].GetComponent<StorageItem>().name = "Babi Ngepet";
entry[4].GetComponent<StorageItem>().file = "Babingepet_Fire";
entry[4].GetComponent<StorageItem>().Level.text = "40";
entry[4].GetComponent<StorageItem>().type = "Fire";
entry[4].GetComponent<StorageItem>().attack = 400;
entry[4].GetComponent<StorageItem>().defense = 400;
entry[4].GetComponent<StorageItem>().stamina = 400;
entry[4].transform.SetParent (contentController.Content, false);
entry[5].GetComponent<StorageItem>().icon.sprite = Resources.Load<Sprite>("icon_char/" + "Kolorijo_Fire");
entry[5].GetComponent<StorageItem>().PlayerHantuId = "PemburuHantu";
entry[5].GetComponent<StorageItem>().hantuId = "H006";
entry[5].GetComponent<StorageItem>().name = "Kolor Ijo";
entry[5].GetComponent<StorageItem>().file = "Kolorijo_Fire";
entry[5].GetComponent<StorageItem>().Level.text = "40";
entry[5].GetComponent<StorageItem>().type = "Fire";
entry[5].GetComponent<StorageItem>().attack = 400;
entry[5].GetComponent<StorageItem>().defense = 400;
entry[5].GetComponent<StorageItem>().stamina = 400;
entry[5].transform.SetParent (contentController.Content, false);
yield return null;
// }
}
public void Update(){
int test;
var angka = int.TryParse( hantuGrade,out test);
if (test != null || test != 0) {
switch (test) {
case 1:
bintang1stats.SetActive (true);
bintang2stats.SetActive (false);
bintang3stats.SetActive (false);
bintang4stats.SetActive (false);
bintang5stats.SetActive (false);
break;
case 2:
bintang2stats.SetActive (true);
bintang1stats.SetActive (false);
bintang3stats.SetActive (false);
bintang4stats.SetActive (false);
bintang5stats.SetActive (false);
break;
case 3:
bintang3stats.SetActive (true);
bintang1stats.SetActive (false);
bintang2stats.SetActive (false);
bintang4stats.SetActive (false);
bintang5stats.SetActive (false);
break;
case 4:
bintang4stats.SetActive (true);
bintang1stats.SetActive (false);
bintang2stats.SetActive (false);
bintang3stats.SetActive (false);
bintang5stats.SetActive (false);
break;
case 5:
bintang5stats.SetActive (true);
bintang1stats.SetActive (false);
bintang2stats.SetActive (false);
bintang3stats.SetActive (false);
bintang4stats.SetActive (false);
break;
}
}
}
}
|
using SGCFT.Dominio.Entidades;
using System.Data.Entity.ModelConfiguration;
namespace SGCFT.Dados.Mapeamentos
{
public class ModuloMap : EntityTypeConfiguration<Modulo>
{
public ModuloMap()
{
this.ToTable("Modulo");
this.HasKey(x => x.Id);
this.Property(x => x.Titulo).HasColumnType("VARCHAR").HasMaxLength(200);
this.HasRequired(x => x.Treinamento).WithMany(x => x.Modulos).HasForeignKey(x => x.IdTreinamento);
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
using System;
namespace GameFrame
{
/// <summary>
/// 定时器管理类
/// </summary>
public class TimerManager : Singleton<TimerManager>
{
Dictionary<int, Timer> m_timers = new Dictionary<int, Timer>();//<TimerID, Timer>
int m_curTimerId = 1;
public void Schedule(TimerCallback callback, int timerID = 0, float intervalTime = 1.0f, float delayTime = 0.0f, bool loop = true)
{
if (callback != null)
{
Timer timer = Timer.CreateTimer();
if (timerID == 0)
{
timerID = GetTimerID();
}
timer.Register(callback, timerID, intervalTime, delayTime, loop);
m_timers.Add(timerID, timer);
}
}
/// <summary>
/// 延迟调用
/// </summary>
/// <param name="callback">调用函数</param>
/// <param name="delayTime">延迟时间:0 下一帧调用; 1 延迟 delayTime调用.</param>
public void DelayCall(DelayCallback callback, float delayTime = 0f)
{
DelayCallTarget delayCall = DelayCallTarget.AddDelayCall();
delayCall.Register(callback, delayTime);
}
public bool Unschedule(int timerID)
{
bool ret = false;
Timer timer = null;
if (m_timers.TryGetValue(timerID, out timer))
{
timer.UnregisterTimer();
m_timers.Remove(timerID);
ret = true;
}
else
{
ret = false;
}
return ret;
}
public int GetTimerID()
{
return m_curTimerId ++;
}
}
}
|
using UnityEngine;
public class Launcher : Photon.PunBehaviour {
//Client's version number. Used to tell users appart from each other
string gameVersion = "1";
//Used to know if a user is trying to connect
bool userTryingToConnect;
public PhotonLogLevel logLevel = PhotonLogLevel.Informational;
public byte MaxNumberOfPlayersPerRoom = 4;
public string levelToLoad = "Loby";
//UI Elements
public GameObject controlPanel;
public GameObject connectionProgressLabel;
void Awake()
{
//Initial settings
PhotonNetwork.autoJoinLobby = false;
//Can use this to sync all connected users to the same scene
PhotonNetwork.automaticallySyncScene = true;
//Loging setting
PhotonNetwork.logLevel = logLevel;
}
// Use this for initialization
void Start () {
//Set UI elements
connectionProgressLabel.SetActive(false);
controlPanel.SetActive(true);
}
/// <summary>
/// Try to connect To the Photon cloud network or if already connected then join a room
/// </summary>
public void Connect()
{
userTryingToConnect = true;
connectionProgressLabel.SetActive(true);
controlPanel.SetActive(false);
if (PhotonNetwork.connected)
{
PhotonNetwork.JoinRandomRoom();
}
else
{
PhotonNetwork.ConnectUsingSettings(gameVersion);
}
}
public override void OnConnectedToMaster()
{
Debug.Log("Connected to master");
if(userTryingToConnect)
PhotonNetwork.JoinRandomRoom();
}
public override void OnJoinedRoom()
{
Debug.Log("User joined a room");
//If we are the first player to join
if(PhotonNetwork.room.PlayerCount == 1)
{
Debug.Log("Load Level: " + levelToLoad);
PhotonNetwork.LoadLevel(levelToLoad);
}
}
public override void OnDisconnectedFromPhoton()
{
connectionProgressLabel.SetActive(false);
controlPanel.SetActive(true);
Debug.LogWarning("Disconnected from Photon Server");
}
// If failure to join a random room then we need to create a new one
public override void OnPhotonRandomJoinFailed(object[] codeAndMsg)
{
Debug.Log("No rooms to connect to, creating a new Room");
PhotonNetwork.CreateRoom(null, new RoomOptions() { MaxPlayers = MaxNumberOfPlayersPerRoom }, null);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class start : MonoBehaviour
{
// start screen
public PlayerMoved scr;
private void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
scr.start = false;
}
}
}
|
using System;
using UnityEngine;
using Unity.Mathematics;
using static Unity.Mathematics.math;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace IzBone.Common.Field {
/**
* bool値をToggleLeftとして表示するための属性
*/
internal sealed class LeftToggleAttribute : PropertyAttribute {
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Patientenanwendung.Data
{
public class Anfrage
{
public Bett Bett { get; set; }
public DateTime DateTime { get; set; }
public AnfrageArt AnfrageArt { get; set; }
public int Schmerzlevel { get; set; }
public String Zusatz { get; set; }
}
public enum AnfrageArt
{
Schmerzen,
Medikamente,
Hygiene,
Nahrungsmittel,
Sonstiges
}
}
|
using System.Collections.Generic;
using System.Linq;
using Atc.Rest.Results;
using AutoFixture;
using FluentAssertions;
using Xunit;
namespace Atc.Rest.Tests.Results
{
public class PaginationTests
{
private Fixture Fixture { get; } = new Fixture();
[Fact]
public void Ctor_Copies_Items_To_Pagination()
{
// Arrange
var data = Fixture.Create<List<string>>();
var sut = new Pagination<string>(data, 5, null, null);
// Act
data.Add(Fixture.Create<string>());
// Assert
sut.Count.Should().Be(data.Count - 1);
sut.Items.Should().NotContain(data.Last());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.WindowsAPICodePack.Dialogs;
using Prism.Mvvm;
using Prism.Commands;
using Prism.Interactivity.InteractionRequest;
using HabMap.SolutionHierarchyModule.Models;
namespace HabMap.SolutionHierarchyModule.ViewModels
{
public class ProjectCreationViewModel : BindableBase, IInteractionRequestAware
{
#region Private Fields
/// <summary>
/// Solution Name
/// </summary>
private string _solutionName;
/// <summary>
/// Solution Location path
/// </summary>
private string _solutionLocation;
private INewSolutionNotification _notification;
/// <summary>
/// Wheter or not the specified project settings is valid
/// </summary>
private bool _isValid;
/// <summary>
/// Message to be displayed if invalid properties entered
/// </summary>
private string _message;
#endregion
#region Public Properties
/// <summary>
/// Solution Name
/// </summary>
public string SolutionName
{
get { return _solutionName; }
set { SetProperty(ref _solutionName, value); ValidateProperties(); }
}
/// <summary>
/// Solution Location path
/// </summary>
public string SolutionLocation
{
get { return _solutionLocation; }
set { SetProperty(ref _solutionLocation, value); ValidateProperties(); }
}
/// <summary>
/// Command for browsing folder location
/// </summary>
public DelegateCommand BrowseLocationCommand { get; set; }
/// <summary>
/// Command for Accept command
/// </summary>
public DelegateCommand AcceptCommand { get; set; }
/// <summary>
/// Command for cancel command
/// </summary>
public DelegateCommand CancelCommand { get; set; }
/// <summary>
/// Action for indicating if interaction is finished
/// </summary>
public Action FinishInteraction { get; set; }
public INotification Notification
{
get { return _notification; }
set { SetProperty(ref _notification, (INewSolutionNotification)value); }
}
/// <summary>
/// Wheter or not the specified project settings is valid
/// <seealso cref="_isValid"/>
/// </summary>
public bool IsValid
{
get { return _isValid; }
set { SetProperty(ref _isValid, value); }
}
/// <summary>
/// Message to be displayed if invalid properties entered
/// </summary>
public string Message
{
get { return _message; }
set { SetProperty(ref _message, value); }
}
#endregion
#region Constructors
public ProjectCreationViewModel()
{
BrowseLocationCommand = new DelegateCommand(OnBrowseLocationCommand);
AcceptCommand = new DelegateCommand(() =>
{
_notification.SolutionName = this.SolutionName;
_notification.SolutionLocation = this.SolutionLocation;
_notification.Confirmed = true;
FinishInteraction?.Invoke();
}).ObservesCanExecute(() => IsValid);
CancelCommand = new DelegateCommand(() =>
{
_notification.SolutionName = null;
_notification.SolutionLocation = null;
_notification.Confirmed = false;
FinishInteraction?.Invoke();
});
}
#endregion
#region Methods
/// <summary>
/// For when the browse buttion is clicked
/// </summary>
private void OnBrowseLocationCommand()
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = true;
if(dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
SolutionLocation = dialog.FileName;
}
}
/// <summary>
/// Checks whether or not the specified solution name and location is valid
/// </summary>
private void ValidateProperties()
{
// Checks if the solution name or location is empty
if (string.IsNullOrEmpty(SolutionName) || string.IsNullOrEmpty(SolutionLocation))
{
IsValid = false;
return;
}
// If valid solution name and location is entered, check if the solution already exists
if(Directory.Exists(SolutionLocation + @"\" + SolutionName))
{
Message = "Project Solution Folder Already Exists!";
IsValid = false;
return;
}
Message = null;
IsValid = true;
}
#endregion
}
}
|
using System.Collections.Generic;
namespace Fragenkatalog.Model
{
class Fach
{
private uint fach_nr;
private uint kapazitaet;
private uint wiederholungsspanne;
private uint anzahlWiederholungen;
private uint benutzer_nr;
private List<Frage> fragenliste = new List<Frage>();
public uint Fach_nr { get { return this.fach_nr; } set { fach_nr = value; } }
public uint Kapazitaet { get { return this.kapazitaet; } set { kapazitaet = value; } }
public uint Wiederholungsspanne { get { return this.wiederholungsspanne; } set { wiederholungsspanne = value; } }
public uint AnzahlWiederholungen { get { return this.anzahlWiederholungen; } set { anzahlWiederholungen = value; } }
public uint Benutzer_nr { get { return benutzer_nr; } set { benutzer_nr = value; } }
public List<Frage> Fragenliste { get { return fragenliste; } }
public Fach(uint fach_nr, uint kapazitaet, uint anzahlWiederholungen, uint wiederholungsspanne)
{
Fach_nr = fach_nr;
Kapazitaet = kapazitaet;
Wiederholungsspanne = wiederholungsspanne;
AnzahlWiederholungen = anzahlWiederholungen;
}
}
}
|
using System;
using System.Collections.Generic;
using gView.Drawing.Pro.Exif;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gView.Drawing.Pro
{
public class ImageMetadata
{
public double? Longitute { get; set; }
public double? Latitude { get; set; }
public DateTime? DateTimeOriginal { get; set; }
public void ReadExif(ExifTagCollection exif)
{
if (exif == null)
return;
if (exif["GPSLatitude"] != null)
{
try
{
string lat = exif["GPSLatitude"].Value;
this.Latitude = FromGMS(lat);
if (exif["GPSLatitudeRef"] != null && exif["GPSLatitudeRef"].Value.ToLower().StartsWith("south"))
this.Latitude = -this.Latitude;
}
catch { }
}
if (exif["GPSLongitude"] != null)
{
try
{
string lng = exif["GPSLongitude"].Value;
this.Longitute = FromGMS(lng);
if (exif["GPSLongitudeRef"] != null && exif["GPSLongitudeRef"].Value.ToLower().StartsWith("west"))
this.Longitute = -this.Longitute;
}
catch { }
}
if (exif["DateTimeOriginal"] != null)
{
DateTime t;
if (DateTime.TryParseExact(exif["DateTimeOriginal"].Value, "yyyy:MM:dd HH:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.None, out t))
this.DateTimeOriginal = t;
}
}
#region Helper
private double FromGMS(string gms)
{
gms = gms.Replace("°", " ").Replace("'", " ").Replace("\"", " ").Replace(",", ".");
while (gms.Contains(" "))
gms = gms.Replace(" ", " ");
string[] p = gms.Split(' ');
double ret = double.Parse(p[0], ImageGlobals.Nhi );
if (p.Length > 1)
ret += double.Parse(p[1], ImageGlobals.Nhi) / 60.0;
if (p.Length > 2)
ret += double.Parse(p[2], ImageGlobals.Nhi) / 3600.0;
return ret;
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseSelectScript : MonoBehaviour
{
private Ray _mouseRay;
private RaycastHit _raycastHit;
private PointToPointMoveManagerScript _p2pMoveManager;
private ClockUIScript _clockUiScript;
void Start()
{
_p2pMoveManager = GetComponent<PointToPointMoveManagerScript>();
_clockUiScript = GetComponent<ClockUIScript>();
}
void Update()
{
if (Input.GetButtonDown("Fire1") /*&& !_p2pMoveManager.UIOpen*/)
{
MouseSelect();
}
}
private void MouseSelect()
{
_mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(_mouseRay, out _raycastHit);
//Debug.Log("Ray hit: " +_raycastHit.transform.name);
if (_raycastHit.transform.tag == "Checkpoint" && !_p2pMoveManager.AllowMove &&
_clockUiScript.FillAmount < 1)
{
Debug.Log("TEst");
if (_p2pMoveManager.ActiveSpace != null)
{
_p2pMoveManager.ActiveSpace.CloseUI();
Debug.Log("Close UI");
}
_p2pMoveManager.TargetIndex = _raycastHit.transform.GetSiblingIndex();
_p2pMoveManager.LoopCheck = true;
}
else
{
//Debug.Log("Did not click on a move space");
return;
}
}
}
|
using MeriMudra.Models.ViewModels;
using System.Data.Entity;
namespace MeriMudra.Models
{
public class MmDbContext : DbContext
{
public MmDbContext() : base("name=MmDbConnectionString")
{
Database.SetInitializer<MmDbContext>(null); //disable initializer i.e. disable code first migrations
}
public virtual DbSet<City> Citys { get; set; }
public virtual DbSet<State> States { get; set; }
public virtual DbSet<BusinessPartnerProgramme> BusinessPartnerProgrammes { get; set; }
public virtual DbSet<Bank> Banks { get; set; }
public virtual DbSet<CreditCard> CreditCards { get; set; }
public virtual DbSet<CcDetail> CcDetails { get; set; }
public virtual DbSet<CcInfoSectionMaster> CcInfoSectionMasters { get; set; }
public virtual DbSet<Areas.Admin.Models.User> UserLogin { get; set; }
public virtual DbSet<Company> Companys { get; set; }
public virtual DbSet<UserCCApplyDetail> UserCCApplyDetail { get; set; }
public virtual DbSet<UserLoanApplyDetail> UserLoanApplyDetail { get; set; }
public virtual DbSet<EligibilityCriteria> CcEligibilityCriterias { get; set; }
public virtual DbSet<CityGroup> CityGroups { get; set; }
public virtual DbSet<ApplicationStatus> ApplicationStatus { get; set; }
}
} |
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Web.Security;
public class Platform
{
public int Id { get; set; }
public string UniqueName { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string CreatedAt { get; set; }
public string UpdatedAt { get; set; }
public Well[] Well { get; set; }
}
public class Well
{
public int Id { get; set; }
public string PlatformId { get; set; }
public string UniqueName { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string CreatedAt { get; set; }
public string UpdatedAt { get; set; }
}
public partial class _Default : System.Web.UI.Page
{
private static HttpClient httpClient = new HttpClient();
private const string URLAEMEnersol = "http://test-demo.aem-enersol.com/api/PlatformWell/GetPlatformWellActual";
private SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalDBConn"].ConnectionString);
string myUsername;
string myToken;
Platform[] platform;
protected void Page_Load(object sender, EventArgs e)
{
// Make sure user is logged in to access other features
if (Session["username"] != null && Session["token"] != null)
{
//myUsername = Session["username"].ToString();
//myToken = Session["token"].ToString();
//lblUser.Text = "You are logged in as <b>" + myUsername + "</b> <a id=\"hyperlinkLogout\" href=\"Login.aspx\">Logout</a>";
// Redirect to Dashboard page
Response.Redirect("Dashboard.aspx", true);
}
// Else, redirect to Login page
else
{
// Redirect to Login page
Response.Redirect("Login.aspx", true);
}
}
protected void BtnSync_Click(object sender, EventArgs e)
{
//lblStatus.Text = "Sync button clicked";
// Get Platform and Well data from API
GetPlatformAndWell();
}
private async void GetPlatformAndWell()
{
var request = new HttpRequestMessage(HttpMethod.Get, URLAEMEnersol);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", myToken);
//request.Content = new StringContent("{'username': '" + myUsername + "', 'password': '" + myPassword + "'}", Encoding.UTF8, "application/json");
//var responseTask = await httpClient.SendAsync(request, CancellationToken.None);
var responseTask = httpClient.SendAsync(request, CancellationToken.None);
responseTask.Wait();
var response = responseTask.Result;
if (response.IsSuccessStatusCode)
{
// Get response body
string responseBody = await response.Content.ReadAsStringAsync();
// Deserialize responsebody JSON in string to Employee (array) object
platform = Newtonsoft.Json.JsonConvert.DeserializeObject<Platform[]>(responseBody);
//foreach (Platform p in platform)
//{
// lblStatus.Text += "<br>" + p.UniqueName;
// if (p.Well != null && p.Well.Length > 0)
// {
// foreach (Well w in p.Well)
// {
// lblStatus.Text += "<br> " + w.UniqueName;
// }
// }
//}
// Show success message
//lblStatus.Text += "<br>SUCCESS";
SyncPlatformAndWell();
}
else
{
// Show failed message
lblStatus.Text = "Synchronization from API to localDB failed";
//lblStatus.Text = "FAILED<br>"+response.ToString();
}
}
private void SyncPlatformAndWell()
{
DateTime now = DateTime.Now;
SyncPlatform();
SyncWell();
lblStatus.Text += "<br>Synchronization from API to localDB sucessfully done<br>on " + now.ToString("dd/MM/yyyy hh:mm tt");
}
private void SyncPlatform()
{
if (con.State == System.Data.ConnectionState.Closed)
{ con.Open(); }
SqlCommand commandClear = new SqlCommand("DELETE FROM Platform", con);
commandClear.ExecuteNonQuery();
string commandInsert = "";
int platformCount = platform.Length;
foreach (Platform p in platform)
{
// Add to command insert
commandInsert += "(@Id" + p.Id + ", "
+ "@UniqueName" + p.Id + ", "
+ "@Latitude" + p.Id + ", "
+ "@Longitude" + p.Id + ", "
+ "@CreatedAt" + p.Id + ", "
+ "@UpdatedAt" + p.Id + ")";
platformCount--;
if(platformCount!=0)
{
commandInsert += ",";
}
}
SqlCommand command = new SqlCommand("INSERT INTO Platform ([Id],[UniqueName],[Latitude],[Longitude],[CreatedAt],[UpdatedAt]) VALUES "
+ commandInsert, con);
foreach (Platform p in platform)
{
command.Parameters.AddWithValue("@Id" + p.Id, p.Id);
command.Parameters.AddWithValue("@UniqueName" + p.Id, p.UniqueName != null ? p.UniqueName : string.Empty);
command.Parameters.AddWithValue("@Latitude" + p.Id, p.Latitude != null ? p.Latitude : string.Empty);
command.Parameters.AddWithValue("@Longitude" + p.Id, p.Longitude != null ? p.Longitude : string.Empty);
command.Parameters.AddWithValue("@CreatedAt" + p.Id, p.CreatedAt != null ? p.CreatedAt : string.Empty);
command.Parameters.AddWithValue("@UpdatedAt" + p.Id, p.UpdatedAt != null ? p.UpdatedAt : string.Empty);
}
command.ExecuteNonQuery();
con.Close();
}
private void SyncWell()
{
if (con.State == System.Data.ConnectionState.Closed)
{ con.Open(); }
SqlCommand commandClear = new SqlCommand("DELETE FROM Well", con);
commandClear.ExecuteNonQuery();
foreach (Platform p in platform)
{
string commandInsert = "";
if (p.Well != null && p.Well.Length > 0)
{
int wellCount = p.Well.Length;
foreach (Well w in p.Well)
{
// Add to command insert
commandInsert += "(@Id" + w.Id + ", "
+ "@PlatformId" + w.Id + ", "
+ "@UniqueName" + w.Id + ", "
+ "@Latitude" + w.Id + ", "
+ "@Longitude" + w.Id + ", "
+ "@CreatedAt" + w.Id + ", "
+ "@UpdatedAt" + w.Id + ")";
wellCount--;
if (wellCount != 0)
{
commandInsert += ",";
}
}
SqlCommand command = new SqlCommand("INSERT INTO Well (Id,PlatformId,UniqueName,Latitude,Longitude,CreatedAt,UpdatedAt) VALUES "
+ commandInsert, con);
foreach (Well w in p.Well)
{
command.Parameters.AddWithValue("@Id" + w.Id, w.Id);
command.Parameters.AddWithValue("@PlatformId" + w.Id, w.PlatformId);
command.Parameters.AddWithValue("@UniqueName" + w.Id, w.UniqueName != null ? w.UniqueName : string.Empty);
command.Parameters.AddWithValue("@Latitude" + w.Id, w.Latitude != null ? w.Latitude : string.Empty);
command.Parameters.AddWithValue("@Longitude" + w.Id, w.Longitude != null ? w.Longitude : string.Empty);
command.Parameters.AddWithValue("@CreatedAt" + w.Id, w.CreatedAt != null ? w.CreatedAt : string.Empty);
command.Parameters.AddWithValue("@UpdatedAt" + w.Id, w.UpdatedAt != null ? w.UpdatedAt : string.Empty);
}
command.ExecuteNonQuery();
}
}
con.Close();
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DelftTools.Controls;
using DelftTools.Controls.Swf;
using DelftTools.Tests.TestObjects;
using NUnit.Framework;
using Rhino.Mocks;
using TreeNode = DelftTools.Controls.Swf.TreeNode;
using TreeView = DelftTools.Controls.Swf.TreeView;
namespace DelftTools.Tests.Controls.Swf
{
[TestFixture]
public class TreeViewTests
{
readonly MockRepository mockRepository=new MockRepository();
/// <summary>
/// Assure the correct node is returned containing a specific tag
/// </summary>
[Test]
public void GetNodeByTag()
{
var o1 = new object();
var treeView = new TreeView();
ITreeNode node = treeView.NewNode();
node.Tag = o1;
treeView.Nodes.Add(node);
ITreeNode node1 = treeView.GetNodeByTag(o1);
Assert.AreEqual(node, node1);
}
/// <summary>
/// Assure a nodepresenter is returned that corresponds to the given datatype
/// </summary>
[Test]
public void GetNodePresenterForDataType()
{
var presenter= mockRepository.Stub<ITreeNodePresenter>();
Expect.Call(presenter.NodeTagType).Return(typeof (object));
var treeView = new TreeView();
//treeview is assigned to presenter when it's added to the list of nodepresenters
treeView.NodePresenters.Add(presenter);
Assert.AreEqual(treeView, presenter.TreeView);
mockRepository.ReplayAll();
Assert.AreEqual(presenter, treeView.GetTreeViewNodePresenter(new object()));
mockRepository.VerifyAll();
}
[Test]
public void HiseSelectionIsFalseByDefault()
{
new TreeView().HideSelection.Should().Be.False();
}
[Test]
public void RefreshShouldNotRefreshNodesWhichAreNotLoaded()
{
var treeView = new TreeView();
var parent = new Parent {Name = "parent1"};
var child = new Child();
parent.Children.Add(child);
var parentNodePresenter = new ParentNodePresenter();
var childNodePresenter = new ChildNodePresenter();
treeView.NodePresenters.Add(parentNodePresenter);
treeView.NodePresenters.Add(childNodePresenter);
childNodePresenter.AfterUpdate += delegate { Assert.Fail("Child nodes which are not loaded should not be updated"); };
treeView.Refresh();
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void ExceptionWhenTwoNodePresentersUseTheSameNodeTagType()
{
var treeView = new TreeView();
var parentNodePresenter1 = new ParentNodePresenter();
var parentNodePresenter2 = new ParentNodePresenter();
treeView.NodePresenters.Add(parentNodePresenter1);
treeView.NodePresenters.Add(parentNodePresenter2);
}
[Test]
public void GetAllLoadedNodes()
{
/*
* RootNode
|-LoadedChild
|-NotLoadedChild
|-LoadedChild2
|-LoadedGrandChild
|-NotLoadedChild2
|-LoadedGrandChild2
*/
var treeView = new TreeView();
ITreeNode rootNode = new MockTestNode(treeView, true) { Text = "RootNode" };
var loadedChild = new MockTestNode(treeView, true) { Text = "LoadedChild" };
rootNode.Nodes.Add(loadedChild);
var notLoadedChild = new MockTestNode(treeView, false) { Text = "NotLoadedChild" };
rootNode.Nodes.Add(notLoadedChild);
var loadedChild2 = new MockTestNode(treeView, true) { Text = "LoadedChild2" };
rootNode.Nodes.Add(loadedChild2);
var loadedGrandChild = new MockTestNode(treeView, true) { Text = "LoadedGrandChild" };
loadedChild2.Nodes.Add(loadedGrandChild);
var notLoadedChild2 = new MockTestNode(treeView, false) { Text = "NotLoadedChild2" };
rootNode.Nodes.Add(notLoadedChild2);
notLoadedChild2.Nodes.Add(new MockTestNode(treeView, true) { Text = "LoadedGrandChild2" });
//reset the loaded flag. It was set set to true by the previous call
notLoadedChild2.SetLoaded(false);
treeView.Nodes.Add(rootNode);
Assert.AreEqual(new[] { rootNode, loadedChild, notLoadedChild, loadedChild2, loadedGrandChild, notLoadedChild2 }, treeView.AllLoadedNodes.ToArray());
}
}
} |
using Clients.Common;
using Common;
using Entity;
using Report.ChildForms;
using SessionSettings;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace Report
{
public partial class MainReport : Form
{
#region Private Fields
private List<Tuple<string, string, Color>> mConformingColors = new List<Tuple<string, string, Color>>();
private string mConnectionString = String.Empty;
private ClientPresentation mClientPresentation = null;
private string mDbLiveStaging = String.Empty;
private string mDepartment = String.Empty;
private ParameterStruct mParameters = new ParameterStruct();
private List<string> mReportForms = new List<string>();
private Users mUserData = null;
private string mUserName = String.Empty;
private UsersProxy mUserProxy = null;
#endregion
#region Constructors
public MainReport()
{
InitializeComponent();
}
public MainReport(Form owner)
: this()
{
if (DesignMode)
return;
mUserData = Settings.User;
mConnectionString = Settings.ConnectionString;
mUserName = mUserData.UserName;
mDepartment = mUserData.Department;
mClientPresentation = new ClientPresentation();
}
#endregion
#region Private Methods
private void BlockContentListingMenu_Click(object sender, EventArgs e)
{
ETCBlockContentListingForm etcForm = new ETCBlockContentListingForm(mParameters, "Block Content Listing");
etcForm.MdiParent = this;
etcForm.StartPosition = FormStartPosition.CenterParent;
etcForm.Show();
}
private void CastListMenu_Click(object sender, EventArgs e)
{
CastListForm castListForm = new CastListForm(mParameters, "Cast List");
castListForm.MdiParent = this;
castListForm.StartPosition = FormStartPosition.CenterParent;
castListForm.Show();
}
private void ClosedCaptionedTitlesMenu_Click(object sender, EventArgs e)
{
ClosedCaptionedTitlesForm ccTitlesForm = new ClosedCaptionedTitlesForm(mParameters, "Closed-Captioned Titles");
ccTitlesForm.MdiParent = this;
ccTitlesForm.StartPosition = FormStartPosition.CenterParent;
ccTitlesForm.Show();
}
private void DaycartReportsMenu_Click(object sender, EventArgs e)
{
MovieDaycartForm daycartForm = new MovieDaycartForm(mParameters, "Daycart Reports");
daycartForm.MdiParent = this;
daycartForm.StartPosition = FormStartPosition.CenterParent;
daycartForm.Show();
}
private void ExitMenu_Click(object sender, EventArgs e)
{
this.Close();
}
private void HelpMenu_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
private void HustlerAccountingReportsMenu_Click(object sender, EventArgs e)
{
HustlerAccountingForm hustlerForm = new HustlerAccountingForm(mParameters, "Hustler");
hustlerForm.MdiParent = this;
hustlerForm.StartPosition = FormStartPosition.CenterParent;
hustlerForm.Show();
}
private void MainReport_FormClosing(object sender, FormClosingEventArgs e)
{
foreach (ReportForm rf in Application.OpenForms.OfType<ReportForm>())
{
rf.Close();
}
ReportForm.ReportFormClosed -= ReportForm_ReportFormClosed;
ReportForm.ReportFormOpened -= ReportForm_ReportFormOpened;
FormSize formSize = new FormSize()
{
Form_Height = this.Height,
Form_Width = this.Width,
Form_Left = this.Left,
Form_Top = this.Top,
Form_Name = this.Name,
Username = mUserName
};
if (!Settings.SaveFormSize(mConnectionString, formSize))
mClientPresentation.ShowError("Unable to save Report form size.");
}
private void MainReport_Load(object sender, EventArgs e)
{
if (DesignMode)
return;
SetUpForm();
}
private void MarketAnalysisMenu_Click(object sender, EventArgs e)
{
MarketAnalysisForm marketForm = new MarketAnalysisForm(mParameters, "Market Analysis");
marketForm.MdiParent = this;
marketForm.StartPosition = FormStartPosition.CenterParent;
marketForm.Show();
}
private void MasterRecordsAndFADsMenu_Click(object sender, EventArgs e)
{
MasterFADsForm masterFADForm = new MasterFADsForm(mParameters, "Master Records and FADs");
masterFADForm.MdiParent = this;
masterFADForm.StartPosition = FormStartPosition.CenterParent;
masterFADForm.Show();
}
private void MovieAndClipAirDatesMenu_Click(object sender, EventArgs e)
{
AccountingAirDatesForm airDatesForm = new AccountingAirDatesForm(mParameters, "Movie and Clip Air Dates");
airDatesForm.MdiParent = this;
airDatesForm.StartPosition = FormStartPosition.CenterParent;
airDatesForm.Show();
}
private void MovieListingByActorActressMenu_Click(object sender, EventArgs e)
{
MovieActorListForm actorForm = new MovieActorListForm(mParameters, "Movie Listing by Actor");
actorForm.MdiParent = this;
actorForm.StartPosition = FormStartPosition.CenterParent;
actorForm.Show();
}
private void MoviesWithNoCastSynopsisMenu_Click(object sender, EventArgs e)
{
MovieNoCastSynopsisForm movieForm = new MovieNoCastSynopsisForm(mParameters, "Movies with No Cast/Synopsis");
movieForm.MdiParent = this;
movieForm.StartPosition = FormStartPosition.CenterParent;
movieForm.Show();
}
private void ReportForm_ReportFormClosed(string reportName)
{
if (mReportForms.Contains(reportName))
mReportForms.Remove(reportName);
}
private void ReportForm_ReportFormOpened(string reportName)
{
if (!mReportForms.Contains(reportName))
mReportForms.Add(reportName);
}
private void ReportUsageMenu_Click(object sender, EventArgs e)
{
ReportUsageForm usageForm = new ReportUsageForm(mParameters, "Report Usage");
usageForm.MdiParent = this;
usageForm.StartPosition = FormStartPosition.CenterParent;
usageForm.Show();
}
private void SetFormSize()
{
FormSize formSize = Settings.GetFormSize(mConnectionString, mUserName, this.Name);
//Create a default size for the Search form in case the user is not in the database.
//Use the MinimumSize set in the designer.
if (formSize == null)
{
formSize = new FormSize()
{
Form_Left = 0,
Form_Top = 0,
Form_Width = 500,
Form_Height = 500
};
}
Left = formSize.Form_Left.Value;
Top = formSize.Form_Top.Value;
Width = formSize.Form_Width.Value;
Height = formSize.Form_Height.Value;
WindowState = FormWindowState.Normal;
}
private void SetUpForm()
{
mParameters = mUserData.ToParameterStruct();
mUserProxy = new UsersProxy(Settings.Endpoints["User"]);
SetFormSize();
mConformingColors = ClientPresentation.AssignConforming();
ReportForm.ReportFormClosed += ReportForm_ReportFormClosed;
ReportForm.ReportFormOpened += ReportForm_ReportFormOpened;
}
#endregion
private void LinearAsRunReportMenu_Click(object sender, EventArgs e)
{
//frmReportLinearAsRun
}
private void InvoicingImportMenu_Click(object sender, EventArgs e)
{
//frmInvoicingImport
}
private void InvoicingReportSearchMenu_Click(object sender, EventArgs e)
{
//frmReportInvoicingSearch -> calls frmReportInvoicing
}
private void MaterialsCompleteMenu_Click(object sender, EventArgs e)
{
//frmReportMaterialsComplete
}
private void MovieLicenseExpiryMenu_Click(object sender, EventArgs e)
{
//frmReportExpiry
}
private void MonthlyQCStatusMenu_Click(object sender, EventArgs e)
{
//frmReportBroadcastQC
}
private void ClipsToBeLoggedMenu_Click(object sender, EventArgs e)
{
//frmReportClipsNeedLogged
}
private void AssetsWithNoAirDatesMenu_Click(object sender, EventArgs e)
{
//frmReportAssetsNoAirDates
}
private void MastersWithNoAirDatesMenu_Click(object sender, EventArgs e)
{
//frmReportMastersNoAirDates
}
private void AddendumNumMenu_Click(object sender, EventArgs e)
{
//frmReportAddendumNum
}
private void Broadcast3MonthMenu_Click(object sender, EventArgs e)
{
//frmReportScheduleBroadcast3Month
}
private void BroadcastDailyChecklistMenu_Click(object sender, EventArgs e)
{
//frmReportCheckList
}
private void CounterProgrammingCheckMenu_Click(object sender, EventArgs e)
{
//frmReportCrossChannelCheck
}
private void IDListingMenu_Click(object sender, EventArgs e)
{
//frmReportIDListing
}
private void PerformerNationalitiesMenu_Click(object sender, EventArgs e)
{
//frmReportPerformerNationalities
}
private void ScheduleHistoryMenu_Click(object sender, EventArgs e)
{
//frmReportScheduleHistory
}
private void SocialMediaExportMenu_Click(object sender, EventArgs e)
{
//frmSocialMediaExport
}
private void SocialMediaExportDISHMenu_Click(object sender, EventArgs e)
{
//frmSocialMediaExportDISH
}
private void StructureCheckMenu_Click(object sender, EventArgs e)
{
//frmReportStructureCheck
}
private void SynopsisReportMenu_Click(object sender, EventArgs e)
{
//frmSynopsis
}
private void CMCTotalAssetsMenu_Click(object sender, EventArgs e)
{
//frmReportVODCMCTotal
}
private void DeliveredToCOAMenu_Click(object sender, EventArgs e)
{
//frmReportDeliveredToCOA
}
private void MasterRelatedIdsMenu_Click(object sender, EventArgs e)
{
//frmMasterRelatedIDs
}
private void FailedUnderReviewMenu_Click(object sender, EventArgs e)
{
//frmReportFailedClips
}
private void FCPQCMenu_Click(object sender, EventArgs e)
{
//frmReportFCPQC
}
private void EmployeeStatisticsMenu_Click(object sender, EventArgs e)
{
//frmReportConformEmpStat
}
private void FixedNotQCdMenu_Click(object sender, EventArgs e)
{
//frmReportConformFixNotQCd
}
private void LinearRevenueByLicensorMenu_Click(object sender, EventArgs e)
{
//frmReportLinearRevenueByLicensor
}
private void RevShareLicensorsByMSOMenu_Click(object sender, EventArgs e)
{
//frmReportRevShareLic1
}
private void MoviesErrorsMenu_Click(object sender, EventArgs e)
{
//frmReportMovieErrors
}
private void VODPitchWeekMenu_Click(object sender, EventArgs e)
{
//frmReportVODPitchWeek
}
}
} |
using System.Collections;
using System.Collections.Generic;
using EntityClasses;
using UnityEngine;
public static class Extensions
{
public static Vector3 GetHitLocation(Player player, Entity target) {
Vector3 location = Vector3.zero;
if (player == null || target == null) {
Debug.LogError("ERROR: Passed in null argument into GetHitLocation.");
} else {
if (player.Instance == null || target.Instance == null) {
Debug.Log("ERROR: Player or target instance is null in GetHitLocation.");
} else {
// TODO: Use Vector3.Lerp or Vector3.MoveTowards to get distance from target in player's direction.
Vector3 playerLoc = target.Instance.transform.position;
Vector3 targetLoc = target.Instance.transform.position;
location = Vector3.MoveTowards(targetLoc, playerLoc, 0.25f);
}
}
// location = Vector3.zero;
return location;
}
public static int IntegerDifference(int value1, int value2)
{
return Mathf.Abs(value1 - value2);
}
public static Vector2 Rotate(this Vector2 o, float degrees)
{
Vector2 res = Quaternion.Euler(0, 0, -degrees) * o;
return res;
}
}
|
using Projeto.Domain.Aggregates.Produtos.Models;
using Projeto.Domain.Bases;
using System;
using System.Collections.Generic;
using System.Text;
namespace Projeto.Domain.Aggregates.Produtos.Contracts.Services
{
public interface ICategoriaDomainService : IBaseDomainService<Categoria>
{
}
}
/*
using Projeto.Domain.Aggregates.Produtos.Models;
using Projeto.Domain.Bases;
using System;
using System.Collections.Generic;
using System.Text;
namespace Projeto.Domain.Aggregates.Produtos.Contracts.Services
{
public interface ICategoriaDomainService : IBaseDomainService<Categoria>
{
}
}
====================
using Projeto.Domain.Aggregates.Produtos.Models;
using Projeto.Domain.Bases;
using System;
using System.Collections.Generic;
using System.Text;
namespace Projeto.Domain.Aggregates.Produtos.Contracts.Services
{
public interface IFornecedorDomainService : IBaseDomainService<Fornecedor>
{
}
}
====================
using Projeto.Domain.Aggregates.Produtos.Models;
using Projeto.Domain.Bases;
using System;
using System.Collections.Generic;
using System.Text;
namespace Projeto.Domain.Aggregates.Produtos.Contracts.Services
{
public interface IProdutoDomainService : IBaseDomainService<Produto>
{
}
}
=======================
using System;
using System.Collections.Generic;
using System.Text;
namespace Projeto.Domain.Bases
{
public interface IBaseDomainService<TEntity>
where TEntity : class
{
void Create(TEntity obj);
void Update(TEntity obj);
void Delete(TEntity obj);
List<TEntity> GetAll();
TEntity GetById(Guid id);
}
}
=======================
*/
|
using System;
namespace BartlettGenesisLogFileParser
{
internal class BartlettTempRecord
{
public DateTime Time { get; set; }
public int Setpoint { get; set; }
public int TempAvg { get; set; }
public int OutAvg { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace Test01_BO
{
//ajout de master/modif/dev
public class CBaseBO : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Lecture07.BlogPosts.EntityFramework.Contexts;
using Lecture07.BlogPosts.EntityFramework.Repositories;
namespace Lecture07.BlogPosts.WebAPI.Demo.Controllers
{
public class DefaultController : ApiController
{
private readonly DatabaseBlogPostRepository repository;
public DefaultController()
{
var context = new LocalDatabaseContext(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=BLOGDATABASE_25f1476eeb6f46e5b0cd8c7e02644db2;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
this.repository = new DatabaseBlogPostRepository(context);
}
[HttpGet]
[Route("api/author")]
public IHttpActionResult GetAuthors()
{
var authors = GetAuthorsFromRepository(repository);
return Ok(authors);
}
private IEnumerable<AuthorDTO> GetAuthorsFromRepository(DatabaseBlogPostRepository repository)
{
return repository.GetAuthors()
.Select(author => new AuthorDTO
{
Id = author.Id,
FullName = author.FullName
});
}
[HttpGet]
[Route("api/author/{id}")]
public IHttpActionResult GetAuthor(Int32 id)
{
var actualAuthor = GetAuthorsFromRepository(repository)
.FirstOrDefault(author => author.Id == id);
return Ok(actualAuthor);
}
[HttpDelete]
[Route("api/author/{id}")]
public IHttpActionResult DeleteAuthor(Int32 id)
{
try
{
repository.DeleteAuthor(id);
return Ok();
}
catch (Exception exception)
{
return BadRequest(exception.Message);
}
}
[HttpPost]
[Route("api/author")]
public IHttpActionResult AddAuthor(String fullName)
{
try
{
repository.AddAuthor(fullName);
return Ok();
}
catch (Exception exception)
{
return BadRequest(exception.Message);
}
}
[HttpPut]
[Route("api/author/{id}")]
public IHttpActionResult UpdateAuthor([FromUri] Int32 id, [FromBody] AuthorDTO author)
{
try
{
if (author == null) throw new ArgumentNullException(nameof(author));
repository.ChangeAuthor(id, author.FullName);
return Ok();
}
catch (Exception exception)
{
return BadRequest(exception.Message);
}
}
}
} |
using UnityEngine;
using System.Collections;
using Mio.Utils.MessageBus;
//using Facebook.Unity;
using MovementEffects;
using System.Collections.Generic;
namespace Mio.TileMaster
{
public class InviteFriendItemView : MonoBehaviour
{
[SerializeField]
private UIToggle toggle;
[SerializeField]
private UILabel friendName;
[SerializeField]
private UI2DSprite spriteAvatar;
[SerializeField]
private Sprite defaultAvatar;
private bool onSelected;
//public string idfriend;
private int index;
public int Index
{
get { return index; }
set
{
index = value;
//lbindex.text = index.ToString();
}
}
private InvitableFriend model;
public InvitableFriend Model { get { return model; } set { model = value; RefreshItemView(); } }
private void RefreshItemView()
{
//Debug.Log(model.id);
friendName.text = model.name;
//Debug.Log(model.isSelected);
toggle.value = model.isSelected;
//lbindex.text = index.ToString();
this.Index = model.index;
ResetAvatar(model);
}
private void ResetAvatar(InvitableFriend model)
{
if (model.avatar != null)
spriteAvatar.sprite2D = model.avatar;
else
{
spriteAvatar.sprite2D = defaultAvatar;
Timing.RunCoroutine(IEDownloadAvatar(model));
}
}
void Start() {
// toggle.activeSprite.cachedGameObject.SetActive(false);
onSelected = toggle.startsActive;
}
public void TouchInCheckboxAction()
{
onSelected = toggle.value;
if(model != null)
model.isSelected = onSelected;
MessageBus.Annouce(new Message(MessageBusType.OnSelectedOrUnselectedInviteFriend, model));
// toggle.activeSprite.cachedGameObject.SetActive(onSelected);
}
private IEnumerator<float> IEDownloadAvatar(InvitableFriend _modelFriend)
{
yield return Timing.WaitForSeconds(1f);
if (_modelFriend.index == this.Index)
{
DownloadFacebookAvatar(_modelFriend);
}
}
private void DownloadFacebookAvatar(InvitableFriend modelForGetAvatar)
{
if (string.IsNullOrEmpty(modelForGetAvatar.picture.data.url))
return;
string linkAvatar = modelForGetAvatar.picture.data.url;
AssetDownloader.Instance.DownloadAndCacheAsset(linkAvatar, 0, null, null,
(WWW www) =>
{
Rect rec = new Rect(0, 0, www.texture.width, www.texture.height);
Sprite.Create(www.texture, rec, new Vector2(0, 0), 1);
Sprite sprite = Sprite.Create(www.texture, rec, new Vector2(0, 0), .01f);
//if (pModel != null)
// pModel.avatar = spriteAvatar;
//avatar.sprite2D = spriteAvatar;
modelForGetAvatar.avatar = sprite;
if (modelForGetAvatar.index == this.Index)
{
spriteAvatar.sprite2D = sprite;
}
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Media;
namespace WpfApplication1.Data
{
public class CommonData
{
public Player[] players;
public Card[] cards=new Card[60];
public Property[] properties=new Property[40];
public Cell[] cells = new Cell[40];
public MainWindow wnd;
public Player cPlayer;
public CardStack FreePark = new CardStack("..\\..\\..\\park.txt");
public CardStack od = new CardStack("..\\..\\..\\vault.txt");
public CardStack rd = new CardStack("..\\..\\..\\chance.txt");
public CardStack lt = new CardStack("..\\..\\..\\lux_tax.txt");
public CardStack it = new CardStack("..\\..\\..\\inc_tax.txt");
//public CardStack Luxury
public CommonData(MainWindow Wnd)
{
wnd = Wnd;
for (int i = 0; i < 40; i++) { cells[i] = new Cell(); }
var line = "";
var path = "..\\..\\..\\countries.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path);
while ((line = file.ReadLine()) != null)
{
string[] part = line.Split('\t'); // разбили строку на part
cells[Convert.ToInt16(part[0])].card.color = part[1];
cells[Convert.ToInt16(part[0])].card.img = part[2];
if (part[3] != "0") //country or service or transport
{
if (part[4] != "0")
{
properties[Convert.ToInt16(part[0])] = new Country { PropType = cellType.country, name = null, cost_to_build=Convert.ToInt16(part[11]), cost_to_buy = Convert.ToInt16(part[3]), zalog = Convert.ToInt16(part[3]) >> 1 };
for (int i = 0; i < 6; i++)
{
((Country)properties[Convert.ToInt16(part[0])]).rent[i] = Convert.ToInt16(part[i + 4]);
}
cells[Convert.ToInt16(part[0])].type = cellType.country;
}
if (part[4] == "0" && part[3] == "200") //transport
{
cells[Convert.ToInt16(part[0])].type = cellType.transport;
properties[Convert.ToInt16(part[0])] = new Service { PropType = cellType.transport, name = null, cost_to_buy = Convert.ToInt16(part[3]), zalog = Convert.ToInt16(part[3]) >> 1, multiplier = 25 };
}
if (part[4] == "0" && part[3] == "150") //service
{
cells[Convert.ToInt16(part[0])].type = cellType.service;
properties[Convert.ToInt16(part[0])] = new Service { PropType = cellType.service, name = null, cost_to_buy = Convert.ToInt16(part[3]), zalog = Convert.ToInt16(part[3]) >> 1, multiplier = 4 };
}
cells[Convert.ToInt16(part[0])].prop = properties[Convert.ToInt16(part[0])];
cells[Convert.ToInt16(part[0])].textDescr = Convert.ToString(part[12]);
}
else //vault, chance
{
cells[Convert.ToInt16(part[0])].type = cellType.random;
switch (part[10])
{
case "0":
cells[Convert.ToInt16(part[0])].eff = rd;
break;
case "1":
cells[Convert.ToInt16(part[0])].eff = od;
break;
case "2":
cells[Convert.ToInt16(part[0])].eff = lt;
break;
case "3":
cells[Convert.ToInt16(part[0])].eff = it;
break;
}
}
cells[30].type = cellType.jail;
cells[20].type = cellType.random;
cells[20].eff = FreePark;
cells[0].type = cellType.special;
cells[10].type = cellType.special;
}
for (int i = 0; i <= 10; i++)
{
cells[i].y = 0;
cells[i].x = i;
};
for (int i = 11; i < 20; i++)
{
cells[i].x = 10;
cells[i].y = i - 10;
};
for (int i = 20; i <= 30; i++)
{
cells[i].y = 10;
cells[i].x = 30 - i;
};
for (int i = 31; i < 40; i++)
{
cells[i].x = 0;
cells[i].y = 40 - i;
};
for (int i = 0; i <40; i++)
{
if (cells[i].card.img != "")
{
var str = "p" + Convert.ToString(cells[i].y) + Convert.ToString(cells[i].x);
cells[i].prop.name = str;
str=str+ "2";
Image d = (Image)wnd.Board.FindName(str);
d.Source = new BitmapImage(new Uri("pack://application:,,,/WpfApplication1;component/Resources/" + cells[i].card.img));
if (cells[i].textDescr != "")
{
var des = (TextBlock)wnd.Board.FindName(str + "t");
des.Text = cells[i].textDescr;
}
str = "p" + Convert.ToString(cells[i].y) + Convert.ToString(cells[i].x) + "1";
Rectangle r = (Rectangle)wnd.Board.FindName(str);
r.Fill = new SolidColorBrush(Color.FromRgb(Convert.ToByte((cells[i].card.color).Substring(1, 2), 16), Convert.ToByte((cells[i].card.color).Substring(3, 2), 16), Convert.ToByte((cells[i].card.color).Substring(5, 2), 16)));
};
};
}
}
}
|
/*
* Created by SharpDevelop.
* User: stanguay
* Date: 2/7/2017
* Time: 4:48 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Windows.Forms;
using System.Threading;
using System.IO.Ports;
using System.Diagnostics;
namespace SimulateBalance
{
public class SerialPortConnection : IDisposable
{
readonly SerialPort _serialPort = new SerialPort();
bool _continue = true;
private const int _baudRate = 1200;
private const int _dataBits = 8;
private Handshake _handshake = Handshake.None;
private Parity _parity = Parity.None;
private StopBits _stopBits = StopBits.One;
readonly Stopwatch delayStopWatch = new Stopwatch();
int _testWeight = 0;
public SerialPortConnection()
{
ConfigureSerialPort(_serialPort, "COM2");
_serialPort.Open();
}
private void ConfigureSerialPort(SerialPort port, string portName)
{
port.BaudRate = _baudRate;
port.DataBits = _dataBits;
port.Handshake = _handshake;
port.Parity = _parity;
port.PortName = portName;
port.StopBits = _stopBits;
port.ReadTimeout = 500;
port.WriteTimeout = 500;
}
public void Dispose()
{
_continue = false;
Thread.Sleep(110);
if(_serialPort != null)
_serialPort.Close();
}
public void Write(string weight)
{
if(_continue)
{
_testWeight++;
weight = weight.PadLeft(8);
_serialPort.WriteLine("ST,GS,??," + weight + " kg");
//_testTimer.Change(100, Timeout.Infinite);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.